repo_name
stringlengths 5
114
| repo_url
stringlengths 24
133
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| branch_name
stringclasses 209
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 9.83k
683M
⌀ | star_events_count
int64 0
22.6k
| fork_events_count
int64 0
4.15k
| gha_license_id
stringclasses 17
values | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_language
stringclasses 115
values | files
listlengths 1
13.2k
| num_files
int64 1
13.2k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TatukiKonnami/judge_curriculum_model
|
https://github.com/TatukiKonnami/judge_curriculum_model
|
89dd651b73448b227e6c6f54cb8bb73b9b2d83ef
|
5f53b76dcd97130d9f15320575ce6eaa9297064c
|
d5b9a0ece3773a89523d92ce43aa8ad27350bc77
|
refs/heads/master
| 2023-02-22T16:28:56.181505 | 2021-01-27T06:10:31 | 2021-01-27T06:10:31 | 333,304,274 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6435331106185913,
"alphanum_fraction": 0.6435331106185913,
"avg_line_length": 30.700000762939453,
"blob_id": "67de4ca70c2e2be43f243e3bb9e90f05f6b0ad00",
"content_id": "9a34e95b28357751f1e6057f0a4256a6708235ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 634,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 20,
"path": "/learning_unit.py",
"repo_name": "TatukiKonnami/judge_curriculum_model",
"src_encoding": "UTF-8",
"text": "from learning_content import LearningContent\nfrom typing import List\n\nclass LearningUnit():\n def __init__(self, contents:List[LearningContent], name: str, transitions ):\n self.contents = contents\n self.name = name\n self.transitions = transitions\n\n def addContents(self, content: LearningContent):\n self.contents.append(content)\n\n def addTransition(self, unit):\n self.transitions.append(unit)\n\n def print(self):\n print('\\t{}'.format(self.name))\n for content in self.contents:\n content.print()\n print('\\t-----> ' + str([i.name for i in self.transitions ]))\n"
},
{
"alpha_fraction": 0.6248062252998352,
"alphanum_fraction": 0.6558139324188232,
"avg_line_length": 28.272727966308594,
"blob_id": "9eeaec34d4151c492f48a3388e8b9453aa06355d",
"content_id": "79677dec0fe025d8170e20ccac754327f80dc479",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 645,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 22,
"path": "/main.py",
"repo_name": "TatukiKonnami/judge_curriculum_model",
"src_encoding": "UTF-8",
"text": "from curriculum_model import Curriculum\n\ndef createCurriculum(name: str) -> Curriculum:\n curriculum: Curriculum = Curriculum([], name)\n return curriculum\n\nif __name__ == '__main__':\n curriculum = createCurriculum('C1')\n curriculum.addUnit('U1')\n curriculum.addUnit('U2')\n curriculum.addUnit('U3')\n curriculum.addContent('U1', 'C1')\n curriculum.addContent('U1', 'C2')\n curriculum.addContent('U2', 'C3')\n curriculum.addContent('U2', 'C4')\n curriculum.addContent('U3', 'C5')\n\n curriculum.addTransit('U1', 'U2')\n curriculum.addTransit('U1', 'U3')\n curriculum.addTransit('U2', 'U3')\n\n curriculum.print()\n\n"
},
{
"alpha_fraction": 0.652314305305481,
"alphanum_fraction": 0.6533907651901245,
"avg_line_length": 32.17856979370117,
"blob_id": "b1896fa68dce4e81e0e421672204c92e90374e98",
"content_id": "5a5e20d19d1db86a440f9f2990b9637c0750dcfe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 28,
"path": "/curriculum_model.py",
"repo_name": "TatukiKonnami/judge_curriculum_model",
"src_encoding": "UTF-8",
"text": "from learning_unit import LearningUnit\nfrom learning_content import LearningContent\nfrom typing import List\n\nclass Curriculum():\n def __init__(self, units: List[LearningUnit], name: str):\n self.units = units\n self.name = name\n\n def addUnit(self, name: str):\n self.units.append(LearningUnit([], name, []))\n\n def searchUnit(self, unit_name: str) -> LearningUnit:\n return [i for i in self.units if i.name == unit_name][0]\n\n def addContent(self, unit_name: str, name: str):\n unit:LearningUnit = self.searchUnit(unit_name)\n unit.addContents(LearningContent(name))\n\n def addTransit(self, origin_name: str, dest_name: str):\n origin: LearningUnit = self.searchUnit(origin_name)\n dest: LearningUnit = self.searchUnit(dest_name)\n origin.addTransition(dest)\n\n def print(self):\n print(self.name)\n for unit in self.units:\n unit.print()\n"
},
{
"alpha_fraction": 0.5253164768218994,
"alphanum_fraction": 0.5253164768218994,
"avg_line_length": 21.571428298950195,
"blob_id": "495013671a7573b904fb8fe6a8b1512f3f5ddd47",
"content_id": "1ae83b8a603a5c4c7263f5f7493ce34b3012bd25",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 7,
"path": "/learning_content.py",
"repo_name": "TatukiKonnami/judge_curriculum_model",
"src_encoding": "UTF-8",
"text": "class LearningContent():\n def __init__(self, name: str):\n self.name = name\n \n\n def print(self):\n print('\\t\\t{}'.format(self.name))\n"
}
] | 4 |
JoaoMariaOliveira/DynamicModel_v1
|
https://github.com/JoaoMariaOliveira/DynamicModel_v1
|
b3b62bd91fe545f51227f431682c8266ab6b578f
|
4f1e0997c40c0f8faea64041b44a14ca0aab48e5
|
37f42800f6549b672a0124eb902cfc04c3298543
|
refs/heads/master
| 2020-03-30T04:43:48.468620 | 2018-10-19T15:32:58 | 2018-10-19T15:32:58 | 150,759,189 | 1 | 0 | null | 2018-09-28T15:19:39 | 2018-10-02T04:11:48 | 2018-10-18T20:43:54 |
Python
|
[
{
"alpha_fraction": 0.6491712927818298,
"alphanum_fraction": 0.6519337296485901,
"avg_line_length": 20.294116973876953,
"blob_id": "8499ad113ab8f078a9358ef0945805636a81f8fe",
"content_id": "4f9b487f5f75e275080585afa8a6c49fc5ad90e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 362,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 17,
"path": "/setup.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "import numpy\nfrom distutils.core import setup\nfrom distutils.extension import Extension\nfrom Cython.Build import cythonize\n\next_modules = [\n Extension(\n 'cfuncs',\n ['cfuncs.pyx'],\n extra_compile_args=['-O3', '-ffast-math'],\n ),\n]\n\nsetup(\n ext_modules = cythonize(ext_modules, language='c'),\n include_dirs=[numpy.get_include()]\n)\n"
},
{
"alpha_fraction": 0.5991870164871216,
"alphanum_fraction": 0.6081300973892212,
"avg_line_length": 41.41379165649414,
"blob_id": "81fa364abeed0ff87e11a34a3e6959550c6f5d52",
"content_id": "07152c93f83d91230e2f52033c85285b0510653b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 29,
"path": "/Dinprime.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\ndef Dinprime(Din, mTauHat, mCost, mLinearThetas, mThetas, nSectors, nCountries):\n # reformatting theta vector\n# mLinearThetas = np.ones([nSectors * nCountries,1], dtype=float)\n# for j in range(nSectors):\n# for n in range(nCountries):\n# mLinearThetas[j * nCountries + n, :] = mThetas[j]\n\n pwr = (-1 / mThetas.reshape(1, nSectors))\n cp = mCost ** pwr.T\n # cp_old = np.ones(mCost.shape)\n # for n in range(nCountries):\n # cp_old[:, n] = mCost[:, n] ** pwr\n # assert np.array_equal(cp, cp_old)\n\n Din_om = Din * (mTauHat ** (-1 / (mLinearThetas * np.ones([1, nCountries]))))\n\n idx = np.arange(0, nSectors*nCountries, nCountries) + np.arange(nCountries)[:,None]\n DD = (Din_om[idx] * cp).reshape(-1, nCountries, order='F')\n # DD_old = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n # for n in range(nCountries):\n # idx = np.arange( n, nSectors * nCountries - (nCountries - (n + 1) ), nCountries)\n # DD_old[idx, :] = Din_om[idx, :] * cp\n # assert np.array_equal(DD, DD_old)\n\n phat = np.power(DD.sum(axis=1).T.reshape(nCountries * nSectors, 1), -mLinearThetas)\n Dinp = DD * (phat ** (1 / mLinearThetas))\n return Dinp\n"
},
{
"alpha_fraction": 0.5749292969703674,
"alphanum_fraction": 0.5876531600952148,
"avg_line_length": 39.03773498535156,
"blob_id": "11c709f1dce5b5b07a0a7b84e92e966608992da2",
"content_id": "ecbc0a18f7e13baa97ba6e15bf5a014c1da87f5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2122,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 53,
"path": "/Expenditure.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# Eexpenditure Function\n# Portada para Python por João Maria em 26/4/2018\n# ============================================================================================\n\"\"\" This function calculates de Omega matrix in Caliendo - Parro (2009)\n Inputs are A = alphas, B = bethas, G = I-O matrix, Dinp = trade shares,\n tarifap = tarifs, mWeightedTariffs = trade weighted tariffs \"\"\"\n\ndef kron(a, nrows):\n return np.repeat(a, nrows * np.ones(a.shape[0], np.int), axis=0)\n\nimport numpy as np\nfrom cfuncs import ExpenditureAux, OM_sum_f, compute_IA, compute_NBP\n\ndef Expenditure(mAlphas, mShareVA, mIO, mTradeShare, mTauActual, mWeightedTariffs, VAn, mWages, Sn, nSectors, nCountries,\n LG, VA_Br, mWagesBrasil, nPositionBR, PQ, tolerance):\n\n IA = compute_IA(mWeightedTariffs, mAlphas, nSectors, nCountries)\n\n Pit = mTradeShare / mTauActual\n Bt = 1 - mShareVA\n NBP = compute_NBP(Pit, Bt, nSectors, nCountries)\n\n NNBP = kron(NBP, nSectors)\n # NNBP_old = np.kron(NBP, np.ones([nSectors, 1], dtype=float))\n # assert np.array_equal(NNBP, NNBP_old)\n GG = np.tile(mIO, nCountries)\n # GG_old = np.kron(np.ones([1, nCountries], dtype=float), mIO)\n # assert np.array_equal(GG, GG_old)\n OM = OM_sum_f(GG, NNBP, IA, nSectors, nCountries)\n # OM_old = OM_sum(GG, NNBP, IA, nSectors, nCountries)\n # assert np.array_equal(OM, OM_old)\n\n A = np.kron(np.ones([nSectors, 1], dtype=float), (mWages * VAn).T) #.reshape(1, N))\n mShareVA = mWagesBrasil * LG * VA_Br\n C = np.sum(mShareVA)\n A[:, nPositionBR] = C\n\n Vb = mAlphas * A\n\n Vb = Vb.reshape(nSectors * nCountries, 1, order='F')\n Bb = -mAlphas * (Sn * np.ones((1, nSectors))).T\n Bb = Bb.reshape(nSectors * nCountries, 1, order='F')\n PQ_vec = PQ.T.reshape(nSectors * nCountries, 1, order='F')\n\n Soma = Vb + Bb\n PQ = ExpenditureAux(OM, Soma, PQ_vec, tolerance)\n\n #temp = matrix_power(OM, -1)\n #DD1 = temp.dot(Vb)\n #DD2 = temp.dot(Bb)\n #PQ = DD1 + DD2\n return PQ.reshape(nSectors, nCountries, order='F')\n"
},
{
"alpha_fraction": 0.5180492401123047,
"alphanum_fraction": 0.5305485725402832,
"avg_line_length": 59.24112319946289,
"blob_id": "a4381a4c4ebd6691dbf4cf6629fb8e1b7da725bc",
"content_id": "d3b1f94b2fbfc8b0ca92ced0aa2c7fbd3ac213bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 40722,
"license_type": "no_license",
"max_line_length": 229,
"num_lines": 676,
"path": "/Principal.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# Main Module of Dynamic Computable General Equilibrium Model\n# ported to Python by João Maria de Oliveira -\n# Original Model - cAliendo e Parro (2017)\n# ============================================================================================\nimport yaml\nimport numpy as np\nimport SupportFunctions as Support\nfrom Controle import Equilibrium\nfrom multiprocessing import Pool, cpu_count\nimport time\n\nconf = yaml.load(open('config.yaml', 'r'))\n\nsDirectoryInput = conf['sDirectoryInput']\nsDirectoryOutput = conf['sDirectoryOutput']\nnFactor = conf['nFactor']\nnTolerance = conf['nTolerance']\nnMaxIteration = conf['nMaxIteration']\nnAdjust = conf['nAdjust']\nnSectors = conf['nSectors']\nnTradebleSectors = conf['nTradebleSectors']\nnCountries = conf['nCountries']\nM = conf['M']\nnYears = conf['nYears']\nnSectorsLabor = nSectors+1\nnPositionBR = conf['nPositionBR']\nnBeta = conf['nBeta']\nnValIntertemp = conf['nValIntertemp']\n\n# ============================================================================================\n# read follows data of Brazil in txt files:\n# L - labor Vector stock by GTAP sector + unemployment ( 0 pos)\n# migracao - migracao Matrix by GTAP sector + unemployment\n# Csi - Csi Matrix by GTAP sector - Percentual do Capital no VA letra grega CI\n# ============================================================================================\nmInitialLaborStock = Support.read_file_txt('L', sDirectoryInput)\nmInitialMigration = Support.read_file_txt('migracao', sDirectoryInput)\nmCsiBrasil = Support.read_file_txt('Csi', sDirectoryInput).reshape(nSectors, 1)\n\n\ndef run_scenario(scenario):\n # Assume normal scenario name is 'normal'\n isNormal = scenario['name'] == 'normal'\n\n # generation of initial values (from the beginning or from previously saved data in an iteration)\n if scenario['nStart'] == 0:\n Y1 = np.ones([nYears, nSectorsLabor], dtype=float)\n w_aux = np.ones([nCountries, nYears], dtype=float)\n wbr_aux = np.ones([nSectors, nYears], dtype=float)\n lData = [Y1, w_aux, wbr_aux]\n if isNormal:\n lDataToSave = ['Y1', 'w_aux', 'wbr_aux']\n else:\n lDataToSave = ['Y1_C', 'w_aux_C', 'wbr_aux_C']\n Support.write_data_csv(lDataToSave, lData, sDirectoryOutput)\n else:\n Y1 = Support.read_file_csv(scenario['Y1_input'], sDirectoryOutput)\n Y1_ant = Support.read_file_csv(scenario['Y1_ant_input'], sDirectoryOutput)\n Y2 = Y1_ant - 1 * (Y1_ant - Y1)\n Y1 = Y2\n\n mInitialY = Y1\n\n if isNormal:\n lSheet = ['VABrasil', 'w_Brasil', 'P_Brasil', 'Y', 'cresc_trab', 'PBr',\n 'xbilat_total', 'GO_total', 'p_total', 'migr']\n else:\n lSheet = ['VABrasil_C', 'w_Brasil_C', 'P_Brasil_C', 'Y_C', 'cresc_trab_C', 'PBr_C',\n 'xbilat_total_C', 'GO_total_C', 'p_total_C', 'migr_C']\n\n if scenario['nExecute'] == 0:\n sDirectoryInputScenario = scenario['sDirectoryInputScenario']\n sNameScenario = scenario['name']\n results = Equilibrium(nCountries, nSectors, nTradebleSectors, nSectorsLabor, nYears, nBeta, nValIntertemp,\n nPositionBR, mInitialMigration, mInitialLaborStock, nFactor, nMaxIteration, nTolerance,\n mInitialY, nAdjust, mCsiBrasil, isNormal, sDirectoryInputScenario, sDirectoryOutput, sNameScenario)\n sFileName = scenario['output']\n lData = list(results)\n Support.write_data_excel(sDirectoryOutput, sFileName, lSheet, lData)\n return results\n else:\n return Support.read_data_excel(sDirectoryOutput, scenario['output'], lSheet)\n\n\nif __name__ == '__main__':\n\n nBeginModel = time.perf_counter()\n sTimeBeginModel = time.localtime()\n # Assuming first scenario is normal\n normal_scenario = conf['scenarios'][0]\n counter_scenarios = conf['scenarios'][1:]\n nNumberScenarios = len(conf['scenarios'])\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"Running Model for \", nYears, \"Years to \", nSectors, \" Sect. x \", nCountries, \" Coun. and Tolerance = \",\n nTolerance)\n print(nNumberScenarios, \"Scenarios : \", end=\" \")\n for i in range(nNumberScenarios):\n if (i == 0):\n print(\"Normal\", end=\" \")\n else:\n print(\",\", counter_scenarios[i-1]['name'], end=\" \")\n\n print(\" \")\n print(\"Begin at \", time.strftime(\"%d/%b/%Y - %H:%M:%S\",sTimeBeginModel ))\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n if conf['parallel']:\n # Use either max available cores,\n # or enough to cover all scenarios\n cores = min(cpu_count(), nNumberScenarios)\n p = Pool(cores)\n\n normal_res = p.apply_async(run_scenario, (normal_scenario,))\n\n # Run other scenarios\n shock_res = [(scenario['name'], p.apply_async(run_scenario, (scenario,))) for scenario in counter_scenarios]\n\n VABrasil_pre, w_Brasil_pre, mPricesBrazilNorm, mYNorm, mGrowthLaborNorm, PBr_pre, xbilat_total_pre, \\\n mGrossOutputTotalNorm, mAllPriceNorm, mMigrationNorm, sDirectoryInputScenarioNom, mTauNorm,\\\n mAlphasNorm = normal_res.get(timeout=None)\n shock_res = [(name, res.get(timeout=None)) for (name, res) in shock_res]\n p.close()\n else:\n VABrasil_pre, w_Brasil_pre, mPricesBrazilNorm, mYNorm, mGrowthLaborNorm, PBr_pre, xbilat_total_pre, \\\n mGrossOutputTotalNorm, mAllPriceNorm, mMigrationNorm, sDirectoryInputScenarioNom, mTauNorm,\\\n mAlphasNorm = run_scenario(normal_scenario)\n shock_res = [(scenario['name'], run_scenario(scenario)) for scenario in counter_scenarios]\n\n # Compare normal against each counterfactual\n\n nEndModel = time.perf_counter()\n nElapsedTime = (nEndModel - nBeginModel)\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"Model for \", nYears, \"Years to \", nSectors,\" Sect. x \", nCountries, \" Coun. and Tolerance = \",nTolerance)\n print(\"Begin at \",time.strftime(\"%d/%b/%Y - %H:%M:%S\",sTimeBeginModel )\n ,\" End at \", time.strftime(\"%d/%b/%Y - %H:%M:%S\", time.localtime()), \"Spent: %.2f segs\" % nElapsedTime )\n print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n\n for scenario_name, res in shock_res:\n VABrasil_pos, w_Brasil_pos, mPricesBrazilShock, mYShock, mGrowthLaborShock, PBr_pos, xbilat_total_pos, \\\n mGrossOutputTotalShock, mAllPriceShock, mMigrationShock, sDirectoryInputScenario, mTau, mAlphas = res\n\n print(\"+++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"Data Treatment of Counterfactual Scenario \", scenario_name )\n print(\"+++++++++++++++++++++++++++++++++++++++++++++\")\n # ============================================================================================\n # Treatment of data for presentation of results\n # ============================================================================================\n vDataSheet = []\n vSheetName = []\n # ============================================================================================\n # variation of Prices\n # ============================================================================================\n p_pre = np.zeros([nYears, nSectors], dtype=float)\n p_pos = np.zeros([nYears, nSectors], dtype=float)\n p_pre[0, :] = mPricesBrazilNorm[0, :]\n p_pos[0, :] = mPricesBrazilShock[0, :]\n for t in range(1,nYears):\n for j in range(nSectors):\n p_pre[t, j] = mPricesBrazilNorm[t, j] * p_pre[t - 1, j]\n p_pos[t, j] = mPricesBrazilShock[t, j] * p_pos[t - 1, j]\n\n Crescimento_Preco = (p_pos / p_pre - 1) * 100\n vDataSheet.append(Crescimento_Preco)\n vSheetName.append('VariacaoPrecos')\n # ============================================================================================\n # Price Index Variation\n # ============================================================================================\n IP_pre = np.zeros([nYears], dtype=float)\n IP_pos = np.zeros([nYears], dtype=float)\n\n IP_pre[0] = PBr_pre[0]\n IP_pos[0] = PBr_pos[0]\n\n for t in range(1,nYears):\n IP_pre[t] = PBr_pre[t] * IP_pre[t - 1]\n IP_pos[t] = PBr_pos[t] * IP_pos[t - 1]\n Crescimento_Indice_Preco = ((IP_pos / IP_pre - 1) * 100).reshape(nYears, 1)\n vDataSheet.append(Crescimento_Indice_Preco)\n vSheetName.append('IndicePrecos')\n # ============================================================================================\n # Variation of wages\n # ============================================================================================\n S_pre = np.zeros([nYears, nSectors], dtype=float)\n S_pos = np.zeros([nYears, nSectors], dtype=float)\n S_pre[0, :] = w_Brasil_pre[0, :]\n S_pos[0, :] = w_Brasil_pos[0, :]\n for t in range(1,nYears):\n for j in range(nSectors):\n S_pre[t, j] = w_Brasil_pre[t, j] * S_pre[t - 1, j]\n S_pos[t, j] = w_Brasil_pos[t, j] * S_pos[t - 1, j]\n\n IP_pre_aux = np.tile(IP_pre.reshape(nYears,1), nSectors)\n S_pre = S_pre / IP_pre_aux\n IP_pos_aux = np.tile(IP_pos.reshape(nYears,1), nSectors)\n S_pos = S_pos / IP_pos_aux\n Crescimento_Salario = (S_pos / S_pre - 1) * 100\n vDataSheet.append(Crescimento_Salario)\n vSheetName.append('VariacaoSalarios')\n # ============================================================================================\n #\n # ============================================================================================\n VA_pre = VABrasil_pre / p_pre\n VA_pos = VABrasil_pos / p_pos\n VA_total_pre = (sum(VA_pre.T)).reshape(nYears,1)\n VA_total_pos = (sum(VA_pos.T)).reshape(nYears,1)\n VA_pre = np.hstack((VA_pre, VA_total_pre))\n VA_pos = np.hstack((VA_pos, VA_total_pos))\n Crescimento = (VA_pos / VA_pre - 1) * 100\n vDataSheet.append(Crescimento)\n vSheetName.append('VariacaoPIB')\n # ============================================================================================\n # Change in GDP (growth)\n # ============================================================================================\n VA_agricultura_pre = np.zeros([nYears], dtype=float)\n VA_agricultura_pos = np.zeros([nYears], dtype=float)\n VA_ind_extr_pre = np.zeros([nYears], dtype=float)\n VA_ind_extr_pos = np.zeros([nYears], dtype=float)\n VA_ind_tran_pre = np.zeros([nYears], dtype=float)\n VA_ind_tran_pos = np.zeros([nYears], dtype=float)\n VA_serv_pre = np.zeros([nYears], dtype=float)\n VA_serv_pos = np.zeros([nYears], dtype=float)\n for t in range(nYears):\n VA_agricultura_pre[t] = sum(VA_pre[t, 0:14])\n VA_agricultura_pos[t] = sum(VA_pos[t, 0:14])\n VA_ind_extr_pre[t] = sum(VA_pre[t, 14:18])\n VA_ind_extr_pos[t] = sum(VA_pos[t, 14:18])\n VA_ind_tran_pre[t] = sum(VA_pre[t, 18:42])\n VA_ind_tran_pos[t] = sum(VA_pos[t, 18:42])\n VA_serv_pre[t] = sum(VA_pre[t, 42:57])\n VA_serv_pos[t] = sum(VA_pos[t, 42:57])\n\n VA_setores_pre = np.concatenate((VA_agricultura_pre.reshape(nYears,1), VA_ind_extr_pre.reshape(nYears,1), VA_ind_tran_pre.reshape(nYears,1), VA_serv_pre.reshape(nYears,1)),axis=1)\n VA_setores_pos = np.concatenate((VA_agricultura_pos.reshape(nYears,1), VA_ind_extr_pos.reshape(nYears,1), VA_ind_tran_pos.reshape(nYears,1), VA_serv_pos.reshape(nYears,1)),axis=1)\n Crescimento_setores = (VA_setores_pos / VA_setores_pre - 1) * 100\n vDataSheet.append(Crescimento_setores)\n vSheetName.append('VariacaoPIBSetorial')\n # ============================================================================================\n # Exchange Variation\n # ============================================================================================\n GO_pre_time = np.zeros([nSectors, nCountries], dtype=float)\n GO_pos_time = np.zeros([nSectors, nCountries], dtype=float)\n p_pre_time = np.zeros([nSectors, nCountries], dtype=float)\n p_pos_time = np.zeros([nSectors, nCountries], dtype=float)\n tau_pre_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n tau_pos_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n# tau = np.vstack((1 + Tarifas / 100, np.ones([15 * nCountries, nCountries], dtype=float)))\n# tau_pre = np.tile(tau, (nYears, 1))\n# tau = np.vstack((1 + TarifasZero / 100, np.ones([15 * nCountries, nCountries], dtype=float)))\n# tau_pos = np.tile(tau, (nYears, 1))\n GO_totalaux_pre = np.zeros([nSectors, nCountries], dtype=float)\n GO_totalaux_pos = np.zeros([nSectors, nCountries], dtype=float)\n tau_pre_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n tau_pos_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n total_comex_pre = np.zeros([nCountries, nCountries], dtype=float)\n total_comex_pos = np.zeros([nCountries, nCountries], dtype=float)\n Cambio = np.zeros([nYears, nCountries], dtype=float)\n for nActualYear in range(nYears):\n\n for j in range(nSectors):\n for n in range(nCountries):\n GO_pre_time[j, n] = mGrossOutputTotalNorm[nActualYear * nSectors + j, n]\n GO_pos_time[j, n] = mGrossOutputTotalShock[nActualYear * nSectors + j, n]\n p_pre_time[j, n] = mAllPriceNorm[nActualYear * nSectors + j, n]\n p_pos_time[j, n] = mAllPriceShock[nActualYear * nSectors + j, n]\n\n export_pre = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n export_pos = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n for i in range(nSectors * nCountries):\n export_pre[i, :] = xbilat_total_pre[nActualYear * nSectors * nCountries + i, :]\n export_pos[i, :] = xbilat_total_pos[nActualYear * nSectors * nCountries + i, :]\n# tau_pre_time[i, n] = tau_pre[nActualYear * nSectors * nCountries + i, n]\n# tau_pos_time[i, n] = tau_pos[nActualYear * nSectors * nCountries + i, n]\n tau_pre_time[i, :] = mTauNorm[nActualYear * nSectors * nCountries + i, :]\n tau_pos_time[i, :] = mTau[nActualYear * nSectors * nCountries + i, :]\n\n\n GO_aux_pre = sum(GO_pre_time)\n GO_aux_pos = sum(GO_pos_time)\n\n for j in range(nSectors):\n for n in range(nCountries):\n GO_totalaux_pre[j, n] = GO_aux_pre[n]\n GO_totalaux_pos[j, n] = GO_aux_pos[n]\n\n GO_pesos_pre = GO_pre_time / GO_totalaux_pre\n GO_pesos_pos = GO_pos_time / GO_totalaux_pos\n ind_p_pre = np.prod(p_pre_time ** GO_pesos_pre, axis=0)\n ind_p_pos = np.prod(p_pos_time ** GO_pesos_pos, axis=0)\n export_pre_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n export_pos_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n for i in range(nCountries * nTradebleSectors):\n export_pre_aux[i, :] = export_pre[i, :]\n export_pos_aux[i, :] = export_pos[i, :]\n tau_pre_aux[i, :] = tau_pre_time[i, :]\n tau_pos_aux[i, :] = tau_pos_time[i, :]\n\n del export_pre, export_pos\n export_pre = export_pre_aux / tau_pre_aux\n export_pos = export_pos_aux / tau_pos_aux\n del export_pre_aux, export_pos_aux\n export_pre_aux = np.zeros([M , nCountries], dtype=float)\n export_pos_aux = np.zeros([M , nCountries], dtype=float)\n for n in range(nCountries):\n for m in range(M):\n export_pre_aux[m, n] = sum(export_pre[m: M * nTradebleSectors:M, n]).T\n export_pos_aux[m, n] = sum(export_pos[m: M * nTradebleSectors:M, n]).T\n\n sum_export_pre = sum(export_pre_aux.T)\n sum_export_pos = sum(export_pos_aux.T)\n\n sum_import_pre = sum(export_pre_aux)\n sum_import_pos = sum(export_pos_aux)\n\n comex_pre = sum_export_pre + sum_import_pre\n comex_pos = sum_export_pos + sum_import_pos\n for i in range(nCountries):\n for n in range(nCountries):\n total_comex_pre[i, n] = (export_pre_aux[i, n] + export_pre_aux[n, i])\n total_comex_pos[i, n] = (export_pos_aux[i, n] + export_pos_aux[n, i])\n\n comex_pre = np.tile(comex_pre, (nCountries, 1))\n comex_pos = np.tile(comex_pos, (nCountries, 1))\n pesos_comex_pre = total_comex_pre / comex_pre\n pesos_comex_pos = total_comex_pos / comex_pos\n ind_p_pre_aux = np.tile(ind_p_pre.T.reshape(nCountries,1), (1, nCountries))\n ind_p_pos_aux = np.tile(ind_p_pos.T.reshape(nCountries,1), (1, nCountries))\n p_exterior_pre = np.prod(ind_p_pre_aux ** pesos_comex_pre, axis=0)\n p_exterior_pos = np.prod(ind_p_pos_aux ** pesos_comex_pos, axis=0)\n cambio_pre = p_exterior_pre / ind_p_pre\n cambio_pos = p_exterior_pos / ind_p_pos\n for n in range(nCountries):\n Cambio[nActualYear, n] = cambio_pos[n] / cambio_pre[n]\n\n Crescimento_cambio = np.zeros([nYears, nCountries], dtype=float)\n Crescimento_cambio[0, :] = Cambio[0, :]\n for nActualYear in range(1, nYears):\n Crescimento_cambio[nActualYear, :] = Cambio[nActualYear, :] * Crescimento_cambio[nActualYear - 1, :]\n\n vDataSheet.append(Crescimento_cambio)\n vSheetName.append('VariacaoCambial')\n\n # ============================================================================================\n # Variation of sector-country exports and Brasil exports by sector\n # ============================================================================================\n tau_pre_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n tau_pos_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n tau_pre_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n tau_pos_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n cresc_export_brasil = np.zeros([nYears, nTradebleSectors], dtype=float)\n export_brasil_pre = np.zeros([nYears, nTradebleSectors], dtype=float)\n export_brasil_pos = np.zeros([nYears, nTradebleSectors], dtype=float)\n cresc_export = np.zeros([nYears*nSectors, nCountries], dtype=float)\n cresc_export_total = np.zeros([nYears, nCountries], dtype=float)\n export_brasil_pre_aux = np.zeros([nYears*nSectors*nTradebleSectors, nCountries], dtype=float)\n export_brasil_pos_aux = np.zeros([nYears*nSectors*nTradebleSectors, nCountries], dtype=float)\n for nActualYear in range(nYears):\n\n export_pre = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n export_pos = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n for i in range(nSectors * nCountries):\n for n in range(nCountries):\n export_pre[i, n] = xbilat_total_pre[nActualYear * nSectors * nCountries + i, n]\n export_pos[i, n] = xbilat_total_pos[nActualYear * nSectors * nCountries + i, n]\n tau_pre_time[i, n] = mTauNorm[nActualYear * nSectors * nCountries + i, n]\n tau_pos_time[i, n] = mTau[nActualYear * nSectors * nCountries + i, n]\n\n export_pre_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n export_pos_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n for i in range(nCountries * nTradebleSectors):\n export_pre_aux[i, :] = export_pre[i, :]\n export_pos_aux[i, :] = export_pos[i, :]\n tau_pre_aux[i, :] = tau_pre_time[i, :]\n tau_pos_aux[i, :] = tau_pos_time[i, :]\n\n del export_pre, export_pos\n export_pre = export_pre_aux / tau_pre_aux\n export_pos = export_pos_aux / tau_pos_aux\n\n del export_pre_aux, export_pos_aux\n export_pre_aux = np.zeros([nTradebleSectors, nCountries], dtype=float)\n export_pos_aux = np.zeros([nTradebleSectors, nCountries], dtype=float)\n\n for j in range(nTradebleSectors):\n for n in range(nCountries):\n # Exports 1+nCountries*(j-1):nCountries*j,n)\n export_pre_aux[j, n] = sum(export_pre[nCountries*j:(nCountries*(j+1)), n]).T\n # Exports\n export_pos_aux[j, n] = sum(export_pos[nCountries*j:(nCountries*(j+1)), n]).T\n\n cresc_export[nActualYear * nSectors + j, n] = export_pos_aux[j, n] / export_pre_aux[j, n]\n\n export_brasil_pre_aux[nActualYear * nSectors + j, n] = export_pre_aux[j, n]\n export_brasil_pos_aux[nActualYear * nSectors + j, n] = export_pos_aux[j, n]\n\n export_pre_soma = sum(export_pre_aux)\n export_pos_soma = sum(export_pos_aux)\n for n in range(nCountries):\n cresc_export_total[nActualYear, n] = export_pos_soma[n] / export_pre_soma[n]\n\n for nActualYear in range(nYears):\n for i in range (nTradebleSectors):\n cresc_export_brasil[nActualYear,i] = cresc_export[nActualYear*nSectors+i,nPositionBR]\n export_brasil_pre[nActualYear,i] = export_brasil_pre_aux[nActualYear*nSectors+i,nPositionBR]\n export_brasil_pos[nActualYear,i] = export_brasil_pos_aux[nActualYear*nSectors+i,nPositionBR]\n\n vDataSheet.append(cresc_export_total)\n vSheetName.append('CrescExportTotal')\n vDataSheet.append(cresc_export_brasil)\n vSheetName.append('CrescExportBrasil')\n # ============================================================================================\n # Variation in sectoral exports\n # ============================================================================================\n export_agricultura_pre = np.zeros([nYears], dtype=float)\n export_agricultura_pos = np.zeros([nYears], dtype=float)\n export_ind_extr_pre = np.zeros([nYears], dtype=float)\n export_ind_extr_pos = np.zeros([nYears], dtype=float)\n export_ind_tran_pre = np.zeros([nYears], dtype=float)\n export_ind_tran_pos = np.zeros([nYears], dtype=float)\n for t in range(nYears):\n export_agricultura_pre[t] = np.sum(export_brasil_pre[t, 0:14], axis=0)\n export_agricultura_pos[t] = np.sum(export_brasil_pos[t, 0:14], axis=0)\n export_ind_extr_pre[t] = np.sum(export_brasil_pre[t, 14:18], axis=0)\n export_ind_extr_pos[t] = np.sum(export_brasil_pos[t, 14:18], axis=0)\n export_ind_tran_pre[t] = np.sum(export_brasil_pre[t, 18:42], axis=0)\n export_ind_tran_pos[t] = np.sum(export_brasil_pos[t, 18:42], axis=0)\n\n export_setores_pre = np.concatenate((export_agricultura_pre.reshape(nYears,1), export_ind_extr_pre.reshape(nYears,1), export_ind_tran_pre.reshape(nYears,1)), axis=1)\n export_setores_pos = np.concatenate((export_agricultura_pos.reshape(nYears,1), export_ind_extr_pos.reshape(nYears,1), export_ind_tran_pos.reshape(nYears,1)), axis=1)\n Crescimento_export_setores = (export_setores_pos / export_setores_pre-1)*100\n vDataSheet.append(Crescimento_export_setores)\n vSheetName.append('ExportacaoSetorial')\n # ============================================================================================\n # Variation of exports country x country\n # ============================================================================================\n export_pre = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n export_pos = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n GO_pre_time = np.zeros([nSectors, nCountries], dtype=float)\n GO_pos_time = np.zeros([nSectors, nCountries], dtype=float)\n p_pre_time = np.zeros([nSectors, nCountries], dtype=float)\n p_pos_time = np.zeros([nSectors, nCountries], dtype=float)\n tau_pre_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n tau_pos_time = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n for i in range(nSectors * nCountries):\n for n in range(nCountries):\n export_pre[i, n] = xbilat_total_pre[(nYears-2)* nSectors * nCountries + i, n]\n export_pos[i, n] = xbilat_total_pos[(nYears-2) * nSectors * nCountries + i, n]\n tau_pre_time[i, n] = mTauNorm[(nYears-2) * nSectors * nCountries + i, n]\n tau_pos_time[i, n] = mTau[(nYears-2) * nSectors * nCountries + i, n]\n\n export_pre_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n export_pos_aux = np.zeros([nCountries * nTradebleSectors, nCountries], dtype=float)\n for i in range(nCountries * nTradebleSectors):\n export_pre_aux[i, :] = export_pre[i, :]\n export_pos_aux[i, :] = export_pos[i, :]\n tau_pre_aux[i, :] = tau_pre_time[i, :]\n tau_pos_aux[i, :] = tau_pos_time[i, :]\n\n del export_pre, export_pos\n export_pre = export_pre_aux / tau_pre_aux\n export_pos = export_pos_aux / tau_pos_aux\n del export_pre_aux, export_pos_aux\n export_pre_aux = np.zeros([M, nCountries], dtype=float)\n export_pos_aux = np.zeros([M, nCountries], dtype=float)\n for n in range(nCountries):\n for m in range(M):\n # Exports\n export_pre_aux[m, n] = sum(export_pre[m: M * nTradebleSectors:M, n]).T\n # Exports\n export_pos_aux[m, n] = sum(export_pos[m: M * nTradebleSectors:M, n]).T\n\n Crescimento_export_por_pais = (export_pos_aux / export_pre_aux-1)*100\n for n in range (nCountries):\n Crescimento_export_por_pais[n,n] = 0\n\n vDataSheet.append(Crescimento_export_por_pais)\n vSheetName.append('ExportacaoPorPais')\n # ============================================================================================\n # Variation of exports Brazil x country x sector\n # ============================================================================================\n export_por_produto_pais_pos = (export_pos / export_pre - 1)*100\n export_por_produto_pais_pos[np.isnan(export_por_produto_pais_pos)]=0\n export_Brasil_pos = export_por_produto_pais_pos[:, nPositionBR]\n export_Brasil_final = np.zeros([nTradebleSectors, nCountries], dtype=float)\n for n in range(nCountries):\n export_Brasil_final[:,n] = export_Brasil_pos[n:nCountries*nTradebleSectors:nCountries]\n\n vDataSheet.append(export_Brasil_final)\n vSheetName.append('ExportacaoBrasil')\n # ============================================================================================\n # Variation of imports Brazil x country x sector\n # ============================================================================================\n import_Brasil_final = np.zeros([nTradebleSectors, nCountries], dtype=float)\n for n in range(nCountries):\n import_Brasil_final[:,n] = export_por_produto_pais_pos[nPositionBR:nCountries*nTradebleSectors:nCountries,n]\n\n vDataSheet.append(import_Brasil_final)\n vSheetName.append('ImportacaoBrasil')\n # ============================================================================================\n # variation in Labor Market\n # ============================================================================================\n num_trab_pre = np.zeros([nYears, nSectorsLabor], dtype=float)\n num_trab_pos = np.zeros([nYears, nSectorsLabor], dtype=float)\n num_trab_pre[0,:] = mInitialLaborStock * mGrowthLaborNorm[0, :]\n num_trab_pos[0,:] = mInitialLaborStock * mGrowthLaborShock[0, :]\n for t in range(1,nYears):\n num_trab_pre[t, :] = num_trab_pre[t-1,:] * mGrowthLaborNorm[t, :]\n num_trab_pos[t, :] = num_trab_pos[t-1,:] * mGrowthLaborShock[t, :]\n\n Cresc_PO = (num_trab_pos / num_trab_pre-1)*100\n vDataSheet.append(Cresc_PO)\n vSheetName.append('VariacaoPO')\n num_trab_aux_pre = num_trab_pre[:, 1:nSectors+1]\n num_trab_aux_pos = num_trab_pos[:, 1:nSectors+1]\n PO_agricultura_pre = np.zeros([nYears], dtype=float)\n PO_agricultura_pos = np.zeros([nYears], dtype=float)\n PO_ind_extr_pre = np.zeros([nYears], dtype=float)\n PO_ind_extr_pos = np.zeros([nYears], dtype=float)\n PO_ind_tran_pre = np.zeros([nYears], dtype=float)\n PO_ind_tran_pos = np.zeros([nYears], dtype=float)\n PO_serv_pre = np.zeros([nYears], dtype=float)\n PO_serv_pos = np.zeros([nYears], dtype=float)\n for t in range(nYears):\n PO_agricultura_pre[t] = np.sum(num_trab_aux_pre[t, 0:14], axis=0)\n PO_agricultura_pos[t] = np.sum(num_trab_aux_pos[t, 0:14], axis=0)\n PO_ind_extr_pre[t] = np.sum(num_trab_aux_pre[t, 14:18], axis=0)\n PO_ind_extr_pos[t] = np.sum(num_trab_aux_pos[t, 14:18], axis=0)\n PO_ind_tran_pre[t] = np.sum(num_trab_aux_pre[t, 18:42], axis=0)\n PO_ind_tran_pos[t] = np.sum(num_trab_aux_pos[t, 18:42], axis=0)\n PO_serv_pre[t] = np.sum(num_trab_aux_pre[t, 42:57], axis=0)\n PO_serv_pos[t] = np.sum(num_trab_aux_pos[t, 42:57], axis=0)\n\n PO_setores_pre = np.concatenate((PO_agricultura_pre.reshape(nYears,1), PO_ind_extr_pre.reshape(nYears,1), PO_ind_tran_pre.reshape(nYears,1), PO_serv_pre.reshape(nYears,1)), axis=1)\n PO_setores_pos = np.concatenate((PO_agricultura_pos.reshape(nYears,1), PO_ind_extr_pos.reshape(nYears,1), PO_ind_tran_pos.reshape(nYears,1), PO_serv_pos.reshape(nYears,1)), axis=1)\n Crescimento_PO_setores = (PO_setores_pos /PO_setores_pre-1)*100\n vDataSheet.append(Crescimento_PO_setores)\n vSheetName.append('POSetorial')\n # ============================================================================================\n # variation of productivity total and by sector\n # ============================================================================================\n num_trab_aux2_pre = np.sum(num_trab_aux_pre,axis=1)\n num_trab_aux2_pre = np.concatenate((num_trab_aux_pre, num_trab_aux2_pre.reshape(nYears,1)), axis=1)\n num_trab_aux2_pos = np.sum(num_trab_aux_pos,axis=1)\n num_trab_aux2_pos = np.concatenate((num_trab_aux_pos, num_trab_aux2_pos.reshape(nYears,1)), axis=1)\n produtividade_pre = VA_pre / num_trab_aux2_pre\n produtividade_pos = VA_pos / num_trab_aux2_pos\n Crescimento_produtividade = (produtividade_pos/produtividade_pre-1)*100\n vDataSheet.append(Crescimento_produtividade)\n vSheetName.append('Produtividade')\n prod_agricultura_pre = VA_agricultura_pre / PO_agricultura_pre\n prod_agricultura_pos = VA_agricultura_pos / PO_agricultura_pos\n prod_ind_extr_pre = VA_ind_extr_pre / PO_ind_extr_pre\n prod_ind_extr_pos = VA_ind_extr_pos / PO_ind_extr_pos\n prod_ind_tran_pre = VA_ind_tran_pre / PO_ind_tran_pre\n prod_ind_tran_pos = VA_ind_tran_pos / PO_ind_tran_pos\n prod_serv_pre = VA_serv_pre / PO_serv_pre\n prod_serv_pos = VA_serv_pos / PO_serv_pos\n prod_setores_pre = np.concatenate((prod_agricultura_pre.reshape(nYears,1), prod_ind_extr_pre.reshape(nYears,1), prod_ind_tran_pre.reshape(nYears,1), prod_serv_pre.reshape(nYears,1)), axis=1)\n prod_setores_pos = np.concatenate((prod_agricultura_pos.reshape(nYears,1), prod_ind_extr_pos.reshape(nYears,1), prod_ind_tran_pos.reshape(nYears,1), prod_serv_pos.reshape(nYears,1)), axis=1)\n Cresc_produtividade_setores = (prod_setores_pos / prod_setores_pre-1)*100\n vDataSheet.append(Cresc_produtividade_setores)\n vSheetName.append('ProdutividadeSetorial')\n # ============================================================================================\n # Variation of adjustment of costs\n # ============================================================================================\n\n\n # ============================================================================================\n # Variation of sectoral wages\n # ============================================================================================\n Sal_agricultura_pre = np.zeros([nYears], dtype=float)\n Sal_agricultura_pos = np.zeros([nYears], dtype=float)\n Sal_ind_extr_pre = np.zeros([nYears], dtype=float)\n Sal_ind_extr_pos = np.zeros([nYears], dtype=float)\n Sal_ind_tran_pre = np.zeros([nYears], dtype=float)\n Sal_ind_tran_pos = np.zeros([nYears], dtype=float)\n Sal_serv_pre = np.zeros([nYears], dtype=float)\n Sal_serv_pos = np.zeros([nYears], dtype=float)\n Sal_economia_pre = np.zeros([nYears], dtype=float)\n Sal_economia_pos = np.zeros([nYears], dtype=float)\n for t in range(nYears):\n Sal_agricultura_pre[t] = np.sum(S_pre[t, 0:14] * num_trab_aux_pre[t, 0:14], axis=0) / PO_agricultura_pre[t]\n Sal_agricultura_pos[t] = np.sum(S_pos[t, 0:14] * num_trab_aux_pos[t,0:14], axis=0) / PO_agricultura_pos[t]\n Sal_ind_extr_pre[t] = np.sum(S_pre[t, 14:18] * num_trab_aux_pre[t, 14:18], axis=0) / PO_ind_extr_pre[t]\n Sal_ind_extr_pos[t] = np.sum(S_pos[t, 14:18] * num_trab_aux_pos[t, 14:18], axis=0) / PO_ind_extr_pos[t]\n Sal_ind_tran_pre[t] = np.sum(S_pre[t, 18:42] * num_trab_aux_pre[t, 18:42], axis=0) / PO_ind_tran_pre[t]\n Sal_ind_tran_pos[t] = np.sum(S_pos[t, 18:42] * num_trab_aux_pos[t, 18:42], axis=0) / PO_ind_tran_pos[t]\n Sal_serv_pre[t] = np.sum(S_pre[t, 42:57] * num_trab_aux_pre[t, 42:57], axis=0) / PO_serv_pre[t]\n Sal_serv_pos[t] = np.sum(S_pos[t, 42:57] * num_trab_aux_pos[t, 42:57], axis=0) / PO_serv_pos[t]\n Sal_economia_pre[t] = np.sum(S_pre[t, 0:57] * num_trab_aux_pre[t, 0:57], axis=0) / np.sum(num_trab_aux_pre[t,0:57], axis=0)\n Sal_economia_pos[t] = np.sum(S_pos[t, 0:57] * num_trab_aux_pos[t, 0:57], axis=0) / np.sum(num_trab_aux_pos[t,0:57], axis=0)\n\n Sal_setores_pre = np.concatenate((Sal_agricultura_pre.reshape(nYears,1), Sal_ind_extr_pre.reshape(nYears,1), Sal_ind_tran_pre.reshape(nYears,1), Sal_serv_pre.reshape(nYears,1), Sal_economia_pre.reshape(nYears,1)), axis=1)\n Sal_setores_pos = np.concatenate((Sal_agricultura_pos.reshape(nYears,1), Sal_ind_extr_pos.reshape(nYears,1), Sal_ind_tran_pos.reshape(nYears,1), Sal_serv_pos.reshape(nYears,1), Sal_economia_pos.reshape(nYears,1)), axis=1)\n Crescimento_Salario_setores = (Sal_setores_pos / Sal_setores_pre-1)*100\n vDataSheet.append(Crescimento_Salario_setores)\n vSheetName.append('SalariosSetoriais')\n # ============================================================================================\n # Variation of sectoral wages\n # ============================================================================================\n P_agricultura_pre = np.zeros([nYears], dtype=float)\n P_agricultura_pos = np.zeros([nYears], dtype=float)\n P_ind_extr_pre = np.zeros([nYears], dtype=float)\n P_ind_extr_pos = np.zeros([nYears], dtype=float)\n P_ind_tran_pre = np.zeros([nYears], dtype=float)\n P_ind_tran_pos = np.zeros([nYears], dtype=float)\n P_serv_pre = np.zeros([nYears], dtype=float)\n P_serv_pos = np.zeros([nYears], dtype=float)\n P_economia_pre = np.zeros([nYears], dtype=float)\n P_economia_pos = np.zeros([nYears], dtype=float)\n P_pre = np.zeros([nYears,nSectors], dtype=float)\n P_pos = np.zeros([nYears,nSectors], dtype=float)\n p_pre[0,:] = mPricesBrazilNorm[0, :]\n p_pos[0,:] = mPricesBrazilShock[0, :]\n for t in range(1,nYears):\n for j in range(nSectors):\n p_pre[t, j] = mPricesBrazilNorm[t, j] * p_pre[t - 1, j]\n p_pos[t, j] = mPricesBrazilShock[t, j] * p_pos[t - 1, j]\n\n alphas_aux = mAlphas.T.reshape(nCountries, nSectors)\n\n for t in range(nYears):\n P_agricultura_pre[t] = np.prod(p_pre[t, 0:14] ** (alphas_aux[nPositionBR, 0:14]), axis=0)\n P_agricultura_pos[t] = np.prod(p_pos[t, 0:14] ** (alphas_aux[nPositionBR, 0:14]), axis=0)\n P_ind_extr_pre[t] = np.prod(p_pre[t, 14:18] ** (alphas_aux[nPositionBR, 14:18]), axis=0)\n P_ind_extr_pos[t] = np.prod(p_pos[t, 14:18] ** (alphas_aux[nPositionBR, 14:18]), axis=0)\n\n P_ind_tran_pre[t] = np.prod(p_pre[t, 18:42] ** (alphas_aux[nPositionBR, 18:42]), axis=0)\n P_ind_tran_pos[t] = np.prod(p_pos[t, 18:42] ** (alphas_aux[nPositionBR, 18:42]), axis=0)\n P_serv_pre[t] = np.prod(p_pre[t, 42:57] ** (alphas_aux[nPositionBR, 42:57]), axis=0)\n P_serv_pos[t] = np.prod(p_pos[t, 42:57] ** (alphas_aux[nPositionBR, 42:57]), axis=0)\n\n Precos_setores_pre = np.concatenate((P_agricultura_pre.reshape(nYears,1), P_ind_extr_pre.reshape(nYears,1), P_ind_tran_pre.reshape(nYears,1), P_serv_pre.reshape(nYears,1)), axis=1)\n Precos_setores_pos = np.concatenate((P_agricultura_pos.reshape(nYears,1), P_ind_extr_pos.reshape(nYears,1), P_ind_tran_pos.reshape(nYears,1), P_serv_pos.reshape(nYears,1)), axis=1)\n\n Crescimento_Precos_setores = (Precos_setores_pos / Precos_setores_pre-1)*100\n vDataSheet.append(Crescimento_Precos_setores)\n vSheetName.append('PrecosSetoriais')\n # ============================================================================================\n # Adjustment Rate Variation of Labor stock\n # ============================================================================================\n num_trab_pre = np.zeros([nYears, nSectorsLabor], dtype=float)\n num_trab_pos = np.zeros([nYears, nSectorsLabor], dtype=float)\n cum_ajuste_aux = np.zeros([nYears, nSectorsLabor], dtype=float)\n ajuste_PO = np.zeros([nYears], dtype=float)\n num_trab_pre[0,:] = mInitialLaborStock * mGrowthLaborNorm[0, :]\n num_trab_pos[0,:] = mInitialLaborStock * mGrowthLaborShock[0, :]\n for t in range(1,nYears):\n num_trab_pre[t,:] = num_trab_pre[t-1,:] * mGrowthLaborNorm[t, :]\n num_trab_pos[t,:] = num_trab_pos[t-1,:] * mGrowthLaborShock[t, :]\n\n for t in range(nYears):\n cum_ajuste_aux[t,:] = .5 * abs(num_trab_pos[t,:]-num_trab_pre[t,:])\n\n cum_ajuste = sum(cum_ajuste_aux,1)\n for t in range(nYears):\n ajuste_PO[t] = 100*(cum_ajuste[t]/cum_ajuste[nYears-1])\n vDataSheet.append(ajuste_PO)\n vSheetName.append('AjustePO')\n # ============================================================================================\n # Variation of sectoral exports only to the counterfactual scenario\n # ============================================================================================\n\n\n # ============================================================================================\n # Variation of sectoral imports only to the counterfactual scenario\n # ============================================================================================\n\n\n # ============================================================================================\n # Recording ResultModel\n # ============================================================================================\n Support.write_data_excel(sDirectoryOutput, \"ResultsOfModel_{}.xlsx\".format(scenario_name), vSheetName, vDataSheet)\n\n print(\"End\")"
},
{
"alpha_fraction": 0.5997514128684998,
"alphanum_fraction": 0.6134244799613953,
"avg_line_length": 45,
"blob_id": "1b02523c278e18de176296bbadfcd8f3d2c71985",
"content_id": "0f0da1e908383d5f707a0f28113fffe19c2af1cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1609,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 35,
"path": "/LMC.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# EquiliBrium Function\n# Portada para Python por João Maria em 26/4/2018\n# ============================================================================================\"\n#\n#Calculating new wages using the labor market clearing condition\n#\nimport numpy as np\n\ndef LMC(Xp, mTradeShareOM, nSectors, nCountries, mShareVA, VAL, VA_Br, nPositionBR, LG):\n PQ_vec = Xp.T.reshape(nSectors * nCountries, 1, order='F').copy()\n # Check if mTradeShareAux gives a different value\n\n mTradeShareAux = mTradeShareOM * PQ_vec\n # mTradeShareAux_old = np.zeros((nSectors * nCountries, nCountries))\n # for n in range(nCountries):\n # mTradeShareAux_old[:, n] = mTradeShareOM[:, n] * PQ_vec[:, 0]\n # assert np.array_equal(mTradeShareAux, mTradeShareAux_old)\n\n mTradeShareIdxs = np.arange(0, nCountries) + (np.arange(nSectors) * nCountries)[:,None]\n mTradeShareTemp = np.sum(mTradeShareAux[mTradeShareIdxs,:], axis=1)\n # mTradeShareTemp_old = np.zeros((nSectors, nCountries))\n # for n in range(nSectors):\n # mTradeShareTemp_old[n, :] = sum(mTradeShareAux[n * nCountries: (n + 1) * nCountries, :])\n # assert np.array_equal(mTradeShareTemp, mTradeShareTemp_old)\n\n mAux4 = mShareVA * mTradeShareTemp\n mAux5 = sum(mAux4).reshape(nCountries, 1)\n mWagesAux = (1 / VAL) * mAux5\n mAux6 = mAux4[:, nPositionBR].reshape(nSectors, 1)\n mWagesBrasilAux = mAux6 / VA_Br\n mWagesBrasilAux = mWagesBrasilAux / LG\n # mWagesBrasilAux = mWagesBrasilAux.T\n\n return mWagesAux, mWagesBrasilAux"
},
{
"alpha_fraction": 0.535595715045929,
"alphanum_fraction": 0.5479063987731934,
"avg_line_length": 47.41960906982422,
"blob_id": "6f1073aa9dde5ee0ca7827d8ad1fac982047e718",
"content_id": "7dd1cd5b573a5f86f053674c57f8df9a202518f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12347,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 255,
"path": "/Controle.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# EquiliBrium Function\n# ported to Python by João Maria at 26/4/2018\n# ============================================================================================\nimport numpy as np\nimport SupportFunctions as Support\nfrom LC import equilibrium_LC\nfrom cfuncs import Labor\nimport time\n\ndef Equilibrium(nCountries, nSectors, nTradebleSectors, nSectorsLabor, nYears, nBeta, nValIntertemp, nPositionBR,\n mInitialMigration, mInitialLaborStock, vFactor, nMaxIterations, nTolerance, mInitialY, nAdjust,\n mCsiBrasil, isNormal, sDirectoryInputScenario, sDirectoryOutput, sNameScenario):\n\n mY = mInitialY\n # Loading trade flows in files txt\n # B - Share of value added\n # GO - Gross Output\n # IO - Input Output Matrix\n # T (Thetas)- dispersion of productivity - non-tradables = 8.22\n # Need Checks that dispersion of productivity\n lRead = ['B', 'Comercio', 'Csi_total', \"GO\", 'IO', 'Tarifas', 'T']\n mShareVA, mTrade, Csi_total, mGrossOutputOrigin, mIO, mTariffs, mThetasOrigin\\\n = Support.read_data_txt(lRead, sDirectoryInputScenario)\n# ============================================================================================\n# Loading data from prior run from csv files\n if isNormal:\n lRead = ['w_aux', 'wbr_aux']\n else:\n lRead = ['w_aux_C', 'wbr_aux_C']\n\n w_aux, wbr_aux = Support.read_data_csv(lRead, sDirectoryOutput)\n mTau = 1 + mTariffs / 100\n nIteration = 1\n Ymax = 1\n while (nIteration <= nMaxIterations) and (Ymax > nTolerance):\n\n nBeginInteration = time.perf_counter()\n nTimeBeginInteration = time.localtime()\n print(\"Running \", sNameScenario, \"int = \", nIteration)\n\n mGrowthLabor, mMigration = \\\n Labor(mY, nCountries, nSectors, nSectorsLabor, nYears, nBeta, mInitialMigration, mInitialLaborStock)\n\n mGrossOutput = np.copy(mGrossOutputOrigin)\n\n mThetas = mThetasOrigin\n # dispersion of productivity - non-tradables = 8.22\n # Need Checks that dispersion of productivity\n mThetas = np.hstack((1. / mThetas, np.ones([(nSectors - nTradebleSectors)], dtype=float) * 1 / 8.22)).reshape(nSectors, 1)\n # reformatting theta vector\n mLinearThetas = np.ones([nSectors * nCountries, 1], dtype=float)\n for j in range(nSectors):\n for n in range(nCountries):\n mLinearThetas[j * nCountries + n, :] = mThetas[j]\n\n # Calculating expenditures\n mTauPrev = mTau[0:nSectors*nCountries ,:]\n mTauActual= mTau[nSectors*nCountries:2*nSectors*nCountries ,:]\n xbilat = np.vstack((mTrade, np.zeros([(nSectors - nTradebleSectors) * nCountries, nCountries]))) * mTauPrev\n # Domestic sales\n x = np.zeros([nSectors, nCountries])\n xbilat_domestic = xbilat / mTauPrev\n for i in range(nSectors):\n # Computing sum of partial columns (0 a 30, 31 sectors) of exports\n # Adding as rows\n x[i, :] = sum(xbilat_domestic[i * nCountries: (i + 1) * nCountries, :])\n\n # Checking MAX between Exports and Domestic Product\n mGrossOutput = np.maximum(mGrossOutput, x)\n domsales = mGrossOutput - x\n # Bilateral trade matrix\n domsales_aux = domsales.T\n aux2 = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n for i in range(nSectors):\n aux2[i * nCountries: ((i + 1) * nCountries), :] = np.diag(domsales_aux[:, i])\n\n xbilat = aux2 + xbilat\n # Calculating Expenditures shares\n A = sum(xbilat.T)\n XO = np.zeros([nSectors, nCountries])\n for j in range(nSectors):\n XO[j, :] = A[j * nCountries: (j + 1) * nCountries]\n\n # Calculating expenditures shares\n Xjn = sum(xbilat.T).T.reshape(nSectors * nCountries, 1).dot(np.ones([1, nCountries], dtype=float))\n Din = xbilat / Xjn\n # Calculating superavits\n xbilattau = xbilat / mTauPrev\n M = np.zeros([nSectors, nCountries])\n E = np.zeros([nSectors, nCountries])\n for j in range(nSectors):\n # Imports\n M[j, :] = sum(xbilattau[j * nCountries: (j + 1) * nCountries, :].T).T\n for n in range(nCountries):\n # Exports\n E[j, n] = sum(xbilattau[j * nCountries: (j + 1) * nCountries, n]).T\n\n Sn = (sum(E).T - sum(M).T).reshape(nCountries, 1)\n # Calculating Value Added\n VAjn = mGrossOutput * mShareVA\n VAn = sum(VAjn).T.reshape(nCountries, 1)\n VA_Br = np.ones([nSectors, 1], dtype= float)\n for j in range(nSectors):\n VA_Br[j, 0] = VAjn[j, nPositionBR]\n\n Csi_teste = Csi_total\n Cap = VAjn * Csi_teste\n rem_cap = sum(Cap).T.reshape(nCountries, 1)\n Qui = sum(rem_cap)\n mIota = (rem_cap - Sn) / Qui\n num = np.zeros([nSectors, nCountries])\n for n in range(nCountries):\n num[:, n] = XO[:, n] - mIO[n * nSectors:(n + 1) * nSectors, :].dot((1 - mShareVA[:, n]) * E[:, n])\n\n F = np.zeros([nSectors, nCountries])\n for j in range(nSectors):\n F[j, :] = sum((Din[j * nCountries: (j + 1) * nCountries:1, :] / mTauPrev[j * nCountries: (j + 1) * nCountries:1, :]).T)\n\n mAlphas = num / (np.ones([nSectors, 1], dtype=float)).dot((VAn + sum(XO * (1 - F)).T.reshape(nCountries, 1) - Sn).T)\n for j in range(nSectors):\n for n in range(nCountries):\n if mAlphas[j, n] < 0:\n mAlphas[j, n] = 0\n\n mAlphas = mAlphas / np.ones([nSectors, 1]).dot(sum(mAlphas).reshape(1, nCountries))\n ##############################\n # Main program conterfactuals\n ##############################\n VAn = VAn / 100\n Sn = Sn / 100\n VA_Br = VA_Br / 100\n VABrasil = np.ones([nYears, nSectors], dtype=float)\n w_Brasil = np.ones([nYears, nSectors], dtype=float)\n P_Brasil = np.ones([nYears, nSectors], dtype=float)\n PBr = np.ones([nYears, 1], dtype=float)\n xbilat_total = np.zeros([nYears * nSectors * nCountries, nCountries], dtype=float)\n mGrossOutputTotal = np.zeros([nYears * nSectors, nCountries], dtype=float)\n mAllPrice = np.zeros([nYears * nSectors, nCountries], dtype=float)\n # ============================================================================================\n # Routine that repeat for nYears years\n # ============================================================================================\n for nActualYear in range(nYears):\n\n LG = np.ones([nSectors, 1], dtype=float)\n for j in range(nSectors):\n LG[j, 0] = mGrowthLabor[nActualYear, j + 1]\n\n if (nActualYear>0):\n mTauPrev = mTau[nActualYear * nSectors * nCountries : (nActualYear+1) * nSectors * nCountries, :]\n mTauActual = mTau[(nActualYear+1) * nSectors * nCountries : (nActualYear+2)* nSectors * nCountries, :]\n\n mTauHat = mTauActual / mTauPrev\n\n mWages, mPriceFactor, PQ, mWeightedTariffs, mTradeShare, ZW, Snp2, mCost, DP, PF, mWagesBrasil \\\n = equilibrium_LC(mTauHat, mTauActual, mAlphas, mLinearThetas, mThetas, mShareVA, mIO, Din, nSectors,\n nCountries, nMaxIterations, nTolerance, VAn, Sn, vFactor, LG, VA_Br, nBeta,\n nPositionBR, nActualYear, w_aux, wbr_aux, mCsiBrasil, Csi_teste, mIota)\n\n w_aux = np.ones([nCountries, nYears], dtype=float)\n wbr_aux = np.ones([nSectors, nYears], dtype=float)\n for n in range(nCountries):\n w_aux[n, nActualYear] = mWages[n, 0]\n\n for j in range(nSectors):\n wbr_aux[j, nActualYear] = mWagesBrasil[j, 0]\n\n PQ_vec = PQ.T.reshape(nSectors * nCountries, 1, order='F').copy() # expenditures Xji in long vector: PQ_vec=(X11 X12 X13...)'\n Dinp_om = mTradeShare / mTauActual\n xbilattau = (PQ_vec.dot(np.ones((1, nCountries)))) * Dinp_om\n xbilatp = xbilattau * mTauActual\n for j in range(nSectors):\n mGrossOutput[j, :] = sum(xbilattau[j * nCountries: (j + 1) * nCountries, :])\n\n VAjn = mGrossOutput * mShareVA\n VAn = sum(VAjn).T.reshape(nCountries, 1)\n # dif no VA_Br 2/5/2018 00:51\n VA_Br = VAjn[:, nPositionBR].reshape(nSectors, 1)\n Din = mTradeShare\n for j in range(nSectors):\n VABrasil[nActualYear, j] = VA_Br[j, 0]\n w_Brasil[nActualYear, j] = mWagesBrasil[j, 0]\n P_Brasil[nActualYear, j] = mPriceFactor[j, nPositionBR]\n\n # pf0_all = mPriceFactor. / (mAlphas);\n # P = prod(pf0_all. ^ (mAlphas));\n # PBr(nActualYear, 1) = P(1, nPositionBR);\n # pf0_all = mPriceFactor./(mAlphas);\n P = np.prod(mPriceFactor ** mAlphas, axis=0)\n PBr[nActualYear, 0] = P[nPositionBR]\n # xbilatp_old = xbilatp.copy()\n # for j in range(nSectors):\n # for n in range(nCountries):\n # xbilatp_old[n + j * nCountries, n] = 0\n sidx = np.arange(nSectors)\n cidx = np.arange(nCountries)\n xbilatp[cidx + sidx[:,None] * nCountries, cidx] = 0\n # assert np.array_equal(xbilatp, xbilatp_old)\n\n\n # xbilat_total_old = xbilat_total.copy()\n # for i in range(nCountries * nSectors):\n # for n in range(nCountries):\n # xbilat_total_old[nActualYear * nCountries * nSectors + i, n] = xbilatp[i, n]\n n = nCountries * nSectors\n xbilat_total[nActualYear*n:(nActualYear+1)*n] = xbilatp\n # assert np.array_equal(xbilat_total, xbilat_total_old)\n\n # mGrossOutputTotal_old = mGrossOutputTotal.copy()\n # mAllPrice_old = mAllPrice.copy()\n # for j in range(nSectors):\n # for n in range(nCountries):\n # mGrossOutputTotal_old[nActualYear * nSectors + j, n] = mGrossOutput[j, n]\n # mAllPrice_old[nActualYear * nSectors + j, n] = mPriceFactor[j, n]\n mGrossOutputTotal[nActualYear*nSectors:(nActualYear+1)*nSectors] = mGrossOutput\n mAllPrice[nActualYear*nSectors:(nActualYear+1)*nSectors] = mPriceFactor\n # assert np.array_equal(mGrossOutputTotal, mGrossOutputTotal_old)\n # assert np.array_equal(mAllPrice, mAllPrice_old)\n\n# Y_aux = mY\n Y_aux = np.ones([nYears, nSectorsLabor], dtype=float)\n for i in range(nYears - 1, 0, -1):\n Y_aux[i - 1, 0] = np.dot(mMigration[(i - 1) * nSectorsLabor, :], (Y_aux[i, :] ** nBeta).T.reshape(nSectorsLabor, 1))\n for j in range(nSectors):\n Y_aux[i - 1, j + 1] = np.dot(((w_Brasil[i - 1, j] / PBr[i - 1]) ** (1 / nValIntertemp)),\n np.dot(mMigration[(i - 1) * nSectorsLabor + j + 1, :], (Y_aux[i, :] ** nBeta).T))\n\n Y1_ant = mY\n Y1 = Y_aux\n Y_aux2 = sum(abs(Y1 - mY))\n vYmax = np.zeros([1, 1], dtype=float)\n vYmax[0, 0] = sum(Y_aux2.T)\n Ymax = vYmax[0, 0]\n\n nEndInteration = time.perf_counter()\n nElapsedTimeInteration = (nEndInteration - nBeginInteration)\n nTimeEndinteration = time.localtime()\n\n print(\"End \", sNameScenario, \"int = \", nIteration, \" between \", time.strftime(\"%d/%b/%Y - %H:%M:%S\", nTimeBeginInteration),\n \" and \", time.strftime(\"%d/%b/%Y - %H:%M:%S\", nTimeEndinteration ), \" Spent: %.2f segs \" % nElapsedTimeInteration,\n \" Ymax = \", Ymax )\n\n Y2 = mY - nAdjust * (mY - Y1)\n if isNormal:\n lDataToSave = ['Y1', 'w_aux', 'wbr_aux', 'Y1_ant', 'YmaxV']\n else:\n lDataToSave = ['Y1_C', 'w_aux_C', 'wbr_aux_C', 'Y1_ant_C', 'YmaxV_C']\n\n lData = [Y1, w_aux, wbr_aux, Y1_ant, vYmax]\n Support.write_data_csv(lDataToSave, lData, sDirectoryOutput)\n mY = Y2\n nIteration +=1\n\n return VABrasil, w_Brasil, P_Brasil, mY, mGrowthLabor, PBr, xbilat_total, mGrossOutputTotal, mAllPrice, mMigration,\\\n sDirectoryInputScenario, mTau, mAlphas\n"
},
{
"alpha_fraction": 0.4528301954269409,
"alphanum_fraction": 0.45317959785461426,
"avg_line_length": 45.5284538269043,
"blob_id": "642d1f0bc704ab436a8ba896f716c01fb5ab644f",
"content_id": "c4cb1211ee0c5a760b8cba6de45b35c972faf35b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5763,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 123,
"path": "/SupportFunctions.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# Support Functions of Input/output\n# ============================================================================================\n\nimport numpy as np\nimport pandas as pd\nimport xlrd\nimport numpy.core.multiarray\nfrom pandas import ExcelWriter\nfrom pandas import ExcelFile\n# ============================================================================================\n# Função que lê dados de um arquivo txt e retorna uma matriz\n# lê de uma pasta input e pode ler vários ao mesmo tempo\n# ============================================================================================\n\n\ndef read_data_txt(lDataToRead, sDirectory):\n lDataContainer = []\n for each in lDataToRead:\n temp = np.loadtxt(sDirectory+each+'.txt')\n lDataContainer.append(temp)\n return lDataContainer\n# ============================================================================================\n# Função que lê dados de um arquivo txt e retorna uma matriz\n# lê de uma pasta input\n# ============================================================================================\n\n\ndef read_file_txt(sFileName, sDirectory):\n sFileName = sDirectory + sFileName + \".txt\"\n temp: numpy.core.multiarray.ndarray = np.loadtxt(sFileName, dtype=np.float64)\n return temp\n# ============================================================================================\n# Função que lê dados de um arquivo csv e retorna uma matriz\n# lê de uma pasta input se não for informada outra\n# ============================================================================================\n\n\ndef read_file_csv(sFileName, sDirectory):\n sFileName = sDirectory + sFileName\n temp: numpy.core.multiarray.ndarray = np.genfromtxt(sFileName+'.csv', delimiter=',')\n return temp\n# ============================================================================================\n# Função que lê dados de um arquivo csv e retorna uma matriz\n# lê de uma pasta input e pode ler vários ao mesmo tempo\n# ============================================================================================\n\n\ndef read_data_csv(lDataToRead, sDirectory):\n lDataContainer = []\n for each in lDataToRead:\n temp: numpy.core.multiarray.ndarray=np.genfromtxt(sDirectory+each+'.csv', delimiter=',')\n lDataContainer.append(temp)\n return lDataContainer\n# ============================================================================================\n# Função que grava dados em um arquivo csv\n# Grava em uma pasta output e pode gravar vários ao mesmo tempo\n# ============================================================================================\n\n\ndef write_data_csv(lDataToWrite, lData, sDirectory):\n for each in range(len(lDataToWrite)):\n np.savetxt(sDirectory + lDataToWrite[each] + '.csv', lData[each], delimiter=',')\n# ============================================================================================\n# Função que grava dados em um arquivo csv\n# Grava em uma pasta output\n# ============================================================================================\n\n\ndef write_file_csv(data_to_save, Data):\n np.savetxt('./Output/' + data_to_save + '.csv', Data, delimiter=',')\n\n# ============================================================================================\n# Função que grava dados em um arquivo excel\n# Grava em uma pasta output e pode gravar várias planilhas em um mesmo arquivo\n# ============================================================================================\ndef write_data_excel(sDirectory, FileName, lSheetName, lDataSheet):\n Writer = pd.ExcelWriter(sDirectory + FileName, engine='xlsxwriter')\n df=[]\n for each in range(len(lSheetName)):\n df.append(pd.DataFrame(lDataSheet[each], dtype=float))\n df[each].to_excel(Writer, lSheetName[each], header=False, index=False)\n Writer.save()\n\n# ============================================================================================\n# Função que grava dados em um arquivo excel\n# Grava em uma pasta output e pode gravar uma só planilha em um mesmo arquivo\n# ============================================================================================\n\ndef write_file_excel(sDirectory, sFileName, sSheet, mData):\n Writer = pd.ExcelWriter(sDirectory + sFileName, engine='xlsxwriter')\n df = pd.DataFrame(mData, dtype=float)\n df.to_excel(Writer, sheet_name=sSheet, header=False, index=False)\n Writer.save()\n\n# ============================================================================================\n# Função que lê dados de um arquivo excel\n# lê de uma pasta (default input) e pode ler várias planilhas em um mesmo arquivo\n# ============================================================================================\n\ndef read_data_excel(sDirectory, sFileName, vSheet):\n data = []\n for each in range(len(vSheet)):\n df = pd.read_excel(sDirectory + sFileName, sheet_name=vSheet[each], header=None, index_col=None)\n data.append(df.values)\n\n return data\n# ============================================================================================\n# Função que lê dados de um arquivo excel\n# lê de uma pasta (default input) e pode ler uma planilhas arquivo\n# ============================================================================================\n\n\ndef read_file_excel(vSheet,sDirectory):\n if sDirectory == None:\n sDirectory = './Input/'\n data=[]\n for each in range(len(vSheet)):\n sFileName = sDirectory + vSheet[each]+\".xlsx\"\n df = pd.read_excel(sFileName, sheet_name=vSheet[each], header=None, index_col=None)\n data.append(df.values)\n\n return data\n\n"
},
{
"alpha_fraction": 0.7005347609519958,
"alphanum_fraction": 0.7112299203872681,
"avg_line_length": 11.466666221618652,
"blob_id": "516a7409176d0c4b7a9c389ad39ec0cce83739b2",
"content_id": "4501564c093a88161c86b0c8be7041e6135d616e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 187,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 15,
"path": "/readme.md",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# Setup for Cython functions\n\n```\n# Install cython\npip3 install cython\n\n# Built cython extensions\npython setup.py build_ext --inplace\n```\n\n# Setup for config\n\n```\npip3 install pyyaml\n```\n"
},
{
"alpha_fraction": 0.5856353640556335,
"alphanum_fraction": 0.5932320356369019,
"avg_line_length": 51.33734893798828,
"blob_id": "f514fd39a4dc70547130a9665d67c2b19c197fec",
"content_id": "979020ebbc14fffff853500af5635be842626306",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4344,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 83,
"path": "/LC.py",
"repo_name": "JoaoMariaOliveira/DynamicModel_v1",
"src_encoding": "UTF-8",
"text": "# ============================================================================================\n# EquiliBrium_LC function\n# ported to Python by João Maria\n# ============================================================================================\nimport numpy as np\nfrom LMC import LMC\nfrom Dinprime import Dinprime\nfrom cfuncs import PH, Expenditure\n\ndef equilibrium_LC(mTauHat, mTauActual, mAlphas, mLinearThetas, mThetas, mShareVA, mIO, Din, nSectors, nCountries,\n nMaxIteracions, nTolerance, VAn, Sn, vfactor, LG, VA_Br, nBeta, nPositionBR, nActualYear,\n w_aux, wbr_aux, mCsiBrasil, Csi_teste, mIota):\n mWages = w_aux[:, nActualYear].reshape(nCountries, 1)\n mWagesBrasil = wbr_aux[:, nActualYear].reshape(nSectors, 1)\n mPriceFactor = np.ones([nSectors, nCountries], dtype=float)\n PQ = 1000 * np.ones([nCountries, nSectors], dtype=float)\n nInterations = 1\n wfmax = 1.0\n while (nInterations <=nMaxIteracions) and (wfmax > nTolerance):\n\n mPriceFactor, mCost = PH(mWages, mTauHat, mLinearThetas, mThetas, mShareVA, mIO, Din, nSectors, nCountries,\n nMaxIteracions, nTolerance, mWagesBrasil, nPositionBR, mPriceFactor, LG, mCsiBrasil)\n\n # Calculating trade shares\n mTradeShare = Dinprime(Din, mTauHat, mCost, mLinearThetas, mThetas, nSectors, nCountries)\n mTradeShareOM = mTradeShare / mTauActual\n idxs = np.arange(0, nCountries) + (np.arange(nSectors) * nCountries)[:,None]\n mWeightedTariffs = np.sum((mTradeShare[idxs,:]/mTauActual[idxs,:]).T, axis=0).T\n # mWeightedTariffs_old = np.zeros([nSectors, nCountries], dtype=float)\n # for j in range(nSectors):\n # mWeightedTariffs_old[j, :] = sum((mTradeShare[j * nCountries: (j + 1) * nCountries: 1, :] / mTauActual[j * nCountries: (j + 1) * nCountries: 1, :]).T)\n # assert np.array_equal(mWeightedTariffs, mWeightedTarrifs_old)\n\n # Expenditure matrix\n PQ = Expenditure(mAlphas, mShareVA, mIO, mTradeShare, mTauActual, mWeightedTariffs, VAn, mWages, Sn, nSectors, nCountries,\n LG, VA_Br, mWagesBrasil, nPositionBR, PQ, nTolerance)\n # Iterating using LMC\n mWagesAux, mWagesBrasilAux = LMC(PQ, mTradeShareOM, nSectors, nCountries, mShareVA, VAn, VA_Br, nPositionBR, LG)\n # Excess function\n # ZW = (mWagesAux.reshape(N,1) - mWages.reshape(N,1))\n # ZW_T = sum(abs(mWages - mWagesAux));\n # ZW_Br = sum(abs(mWagesBrasil - mWagesBrasilAux))\n ZW = (mWagesBrasilAux - mWagesBrasil)\n PQ_vec = PQ.T.reshape(nSectors * nCountries, 1, order='F').copy()\n DP = mTradeShareOM * PQ_vec\n # DP_old = np.zeros([nSectors * nCountries, nCountries], dtype=float)\n # for n in range(nCountries):\n # DP_old[:, n] = mTradeShareOM[:, n] * PQ_vec[:, 0]\n # assert np.array_equal(DP, DP_old)\n\n # Exports\n LHS = sum(DP).reshape(nCountries, 1)\n # calculating RHS (Imports) trade balance\n PF = PQ * mWeightedTariffs\n # Imports\n RHS = sum(PF).reshape(nCountries, 1)\n # Sn_pos = -(RHS - LHS)\n xbilattau = (PQ_vec * np.ones([1, nCountries], dtype=float)) * mTradeShareOM\n idxs = np.arange(0, nCountries) + (np.arange(nSectors) * nCountries)[:,None]\n GO = np.sum(xbilattau[idxs,:], axis=1)\n # GO_old = np.ones([nSectors, nCountries], dtype=float)\n # for j in range(nSectors):\n # GO_old[j, :] = sum(xbilattau[j * nCountries: (j + 1) * nCountries, :])\n # assert np.array_equal(GO, GO_old)\n\n VAjn_pos = GO * mShareVA\n Cap_pos = VAjn_pos * Csi_teste\n rem_cap_pos = sum(Cap_pos).reshape(nCountries, 1)\n Qui_pos = sum(rem_cap_pos)\n iota_pos = (rem_cap_pos - Sn) / Qui_pos\n ZW2 = iota_pos - mIota\n # Excess function (trade balance)\n Snp = (RHS - LHS) + Sn\n ZW2 = -(RHS - LHS + Sn) / VAn\n # Itaration factor prices\n mWagesAux = mWages * (1 - vfactor * ZW2 / mWages)\n mWagesBrasilTemp = mWagesBrasil * (1 - vfactor * ZW / mWagesBrasil)\n wfmax = sum(abs(ZW2))\n mWages = mWagesAux\n mWagesBrasil = mWagesBrasilTemp\n nInterations += 1\n\n return mWages, mPriceFactor, PQ, mWeightedTariffs, mTradeShare, ZW, Snp, mCost, DP, PF, mWagesBrasil\n"
}
] | 9 |
kimnnguyen/DSO-499
|
https://github.com/kimnnguyen/DSO-499
|
29ef009c1497208b14e72c497a935abd170e8c4e
|
eda234e51047f914c86877c2b4cef708f16de863
|
639a51416232e146c1e70cbbe95373d45e25eff2
|
refs/heads/main
| 2023-03-13T01:31:22.423906 | 2021-03-01T02:20:58 | 2021-03-01T02:20:58 | 343,265,722 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.576606273651123,
"alphanum_fraction": 0.5799011588096619,
"avg_line_length": 22.68000030517578,
"blob_id": "dccaefb6af5901fd0f7a8bc1a861e151e8e25b5f",
"content_id": "0ff35b4ef96253658a09644abc857f57d5d6518a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 607,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 25,
"path": "/inheritance/Being.py",
"repo_name": "kimnnguyen/DSO-499",
"src_encoding": "UTF-8",
"text": "class Being(object):\n def __init__(self, name, quarts):\n self.__name = name\n self.__quarts = quarts\n\n # get and set method for name\n def getName(self):\n return self.__name\n\n def setName(self,newName):\n self.__name = newName\n\n # get and set method for quarts\n def getQuarts(self):\n return self.__quarts\n\n def setQuarts(self,newQuarts):\n self.__quarts = newQuarts\n\n # increase and decrease quarts of blood by one\n def increaseQuarts(self):\n self.__quarts += 1\n\n def decreaseQuarts(self):\n self.__quarts -= 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6022727489471436,
"alphanum_fraction": 0.60537189245224,
"avg_line_length": 34.814815521240234,
"blob_id": "1f24a549d60fb005d928416ac8ff02f9b7df487a",
"content_id": "869efb005026e42c0cfc6d46d7d0910944485362",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 968,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 27,
"path": "/inheritance/Human.py",
"repo_name": "kimnnguyen/DSO-499",
"src_encoding": "UTF-8",
"text": "from Being import Being\n\nclass Human(Being):\n def __init__(self, name, quarts, bloodType):\n super().__init__(name, quarts)\n self.__bloodType = bloodType\n\n # getter and setter for blood type\n def getBloodType(self):\n return self.__bloodType\n \n def setBloodType(self,newBloodType):\n self.__bloodType = newBloodType\n\n # check if human is alive. If number of quarts of blood is 0, the human is dead, so return false.\n # if human number of quarts of blood is greater than zero, human is alive, so return true.\n def isAlive(self):\n if self.getQuarts() > 0 :\n return True\n elif self.getQuarts() == 0:\n return False\n\n # strings together name, number of quarts of blood, and blood type of the human\n def __str__(self):\n msg = \"Human \" + self.getName() + \" has \" + str(self.getQuarts()) + \\\n \" quarts of type \" + self.__bloodType + \" blood.\"\n return msg\n\n"
},
{
"alpha_fraction": 0.6331557631492615,
"alphanum_fraction": 0.6344873309135437,
"avg_line_length": 37.487178802490234,
"blob_id": "2b1c50abae107c523f025947cc4a1d914f02868b",
"content_id": "8c7e013919a552092d0343a0ea193b8af7419af2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1502,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 39,
"path": "/inheritance/Vampire.py",
"repo_name": "kimnnguyen/DSO-499",
"src_encoding": "UTF-8",
"text": "from Being import Being\n\nclass Vampire(Being):\n def __init__(self, name, quarts, animalForm):\n super().__init__(name, quarts)\n self.__maxBlood = 5\n self.__hungerLevels = [\"starving\",\"hangry\",\"hungry\",\"content\",\"full\",\"stuffed\"]\n self.__animalForm = animalForm\n\n # get and set method for animal form\n def getAnimalForm(self):\n return self.__animalForm\n\n def setAnimalForm(self, newForm):\n self.__animalForm = newForm\n\n # use the vampire's current quart of blood as an index for the hungerlevels list to determine hunger level\n def getHunger(self):\n hunger = self.__hungerLevels # list of the hunger levels\n level = self.getQuarts() # this acts as the index\n return hunger[level]\n\n # gets the quarts of blood the vampire to determine his hunger levels\n def isStuffed(self):\n # if vampire's quarts of blood is equal to the max blood (5), then return True.\n # It is true that vampire is stuffed\n if self.getQuarts() == self.__maxBlood:\n return True\n # return false if the vampire's quarts of blood is not equal to the max.\n else:\n return False\n # simulates blood sucking. Increase vampire's quarts of blood by one and decrease human's quarts of blood by one.\n def suckBlood(self, human):\n human.decreaseQuarts()\n self.increaseQuarts()\n\n def __str__(self):\n msg = self.getName() + \" is \" + self.getHunger() + \".\"\n return msg\n\n"
},
{
"alpha_fraction": 0.624770998954773,
"alphanum_fraction": 0.6328325271606445,
"avg_line_length": 35.38666534423828,
"blob_id": "544e6e8ecbb11353f90cb426ca7b4d7b1ef12ab3",
"content_id": "9427be3609fbc6eced47bc46c4e020de10ca23f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2729,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 75,
"path": "/inheritance/Game.py",
"repo_name": "kimnnguyen/DSO-499",
"src_encoding": "UTF-8",
"text": "from Human import Human\nfrom Vampire import Vampire\n\ndef printHumans(humanList):\n print(\"----------------------------------------------\")\n listLength = len(humanList) #contains a LIST of all the indices of the humans.\n for num in range(listLength):\n print(num, \")\", humanList[num]) #humanList[num] is the human with the correspinding index\n print(\"----------------------------------------------\")\n\n\ndef performdFeeding(humanList, vamp):\n humanIndex = int(input(\"Please select a human from the list: \"))\n listLength = len(humanList)\n # used for error checking\n possibleValues = list(range(listLength)) # list of INTEGERS(the indices for how many humans are in the List)\n\n # error checking\n while humanIndex not in possibleValues:\n print(\"Invalid input. Please try again. \")\n humanIndex = input(\"Please select a human from the list: \")\n human = humanList[humanIndex]\n # determine if the vampire is able to suck blood from human\n # human cannot have less than 0 quarts of blood and vampire can't have more than 5 quarts of blood\n if human.isAlive() == False:\n print(human)\n print(human.getName(), \"is dead! Cannot suck blood.\")\n if vamp.isStuffed() == True:\n print(vamp, vamp.getName(), \"can not suck any more blood.\") # printing out vamp prints out the status of the vamp.\n elif human.getQuarts() > 0 and vamp.isStuffed() == False:\n vamp.suckBlood(human)\n print(human)\n print(vamp)\n\n\n\ndef main():\n\n # display menu\n print(\"Menu: \")\n print(\"1) Print all humans\")\n print(\"2) Suck Blood\")\n print(\"-1) quit\")\n\n option = input(\"Please select an option from the menu: \")\n # error checking\n possibleSelections = [\"1\",\"2\",\"-1\"]\n while option not in possibleSelections:\n print(\"Invalid input. Please try again.\")\n option = input(\"Please select an option from the menu: \")\n # Option1: print all humans\n if option == \"1\":\n printHumans(humanList)\n # Option 2: Vampire sucks blood.\n elif option == \"2\":\n printHumans(humanList)\n performdFeeding(humanList,vamp)\n # Option 3: vampire turns back into animal and program ends\n elif option == \"-1\":\n print(vamp.getName(), \"turned back into a\", vamp.getAnimalForm())\n quit()\n\n# creating 4 humans and putting them into a list\nAlice = Human(\"Alice\",10,\"A+\")\nJerry = Human(\"Jerry\", 3,\"B+\")\nTom = Human(\"Tom\", 5, \"O\")\nMary = Human(\"Mary\", 8, \"A-\")\nhumanList = [Alice, Jerry, Tom, Mary]\n# ask user for vampire name and animal form\nvampName = input(\"Enter the name of the vampire: \").title()\nanimal = input(\"Enter an animal: \")\n#create vampire\nvamp = Vampire(vampName, 0, animal)\nwhile True:\n main()\n"
}
] | 4 |
obdabobda/vk-requests
|
https://github.com/obdabobda/vk-requests
|
6a1e3f4d4a4cc5082b1294364afd96b796d21733
|
8905b7052e56c4c06d27a56d246f3ea765aa6810
|
28d48af41612c14121ef9cb595ce9748edb7bd2a
|
refs/heads/master
| 2021-01-20T15:58:52.025684 | 2016-07-06T14:24:56 | 2016-07-06T14:24:56 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6782407164573669,
"alphanum_fraction": 0.6905864477157593,
"avg_line_length": 40.80644989013672,
"blob_id": "f1e0c4b3b6a7023af60e54abd0897ad8e848214b",
"content_id": "b30883d229b68dff87fb94046eb6b07f93987255",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1296,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 31,
"path": "/vk_requests/__init__.py",
"repo_name": "obdabobda/vk-requests",
"src_encoding": "UTF-8",
"text": "\nfrom vk_requests.auth import InteractiveVKSession, VKSession\nfrom vk_requests.api import API\n\n\n__version__ = '0.9.6'\n\n\ndef create_api(app_id=None, login=None, password=None, phone_number=None,\n timeout=10, scope='offline', api_version=None,\n session_cls=VKSession, **method_default_args):\n \"\"\"Factory method to explicitly create API with app_id, login, password\n and phone_number parameters.\n\n If the app_id, login, password are not passed, then token-free session\n will be created automatically\n\n :param app_id: int: vk application id, more info: https://vk.com/dev/main\n :param login: str: vk login\n :param password: str: vk password\n :param phone_number: str: phone number with country code (+71234568990)\n :param timeout: int: api timeout in seconds\n :param scope: str or list of str: vk session scope\n :param api_version: str: vk api version\n :param session_cls: VKSession: session implementation class\n :param method_default_args: api kwargs\n :return: api instance\n :rtype : vk_requests.api.API\n \"\"\"\n session = session_cls(app_id, login, password, phone_number=phone_number,\n scope=scope, api_version=api_version)\n return API(session=session, timeout=timeout, **method_default_args)"
}
] | 1 |
shishi-muthoni/micropilot-entry-challenge
|
https://github.com/shishi-muthoni/micropilot-entry-challenge
|
d9030b981e991d9127ba5b8a1cb7a1ddeca87c60
|
f71fe212aaf7ed39044d297d7af90dfb40eb0529
|
21e6e4ef6c404abc085ed5879ee9063eb38234e8
|
refs/heads/main
| 2023-02-22T17:46:49.355532 | 2021-01-25T19:50:03 | 2021-01-25T19:50:03 | 332,857,216 | 0 | 0 | null | 2021-01-25T19:19:25 | 2021-01-25T06:09:19 | 2021-01-25T06:18:05 | null |
[
{
"alpha_fraction": 0.417558878660202,
"alphanum_fraction": 0.44967880845069885,
"avg_line_length": 21.190475463867188,
"blob_id": "21784bf21f867ea7cef4b45ba512e535b654c6f3",
"content_id": "2cc35ace00dede8a671829854dba313842b1658b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 467,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 21,
"path": "/shishi-muthoni.py",
"repo_name": "shishi-muthoni/micropilot-entry-challenge",
"src_encoding": "UTF-8",
"text": "\nprint(\"before\")\n\n#the formula is x = (-b+-((b*2)-(4ac))**(1/2)))/(2a)\na= float(input(\"Enter value of a: \"))\nb= float(input(\"Enter value of b: \"))\nc= float(input(\"Enter value of c: \"))\n\ndef getX ():\n y = ((-b)+((b**2)-(4*a*c))**(1/2))/(2*a)\n z = ((-b)-((b**2)-(4*a*c))**(1/2))/(2*a)\n if y>z:\n x = y\n return x\n elif z>y:\n x = z\n return x\n else :\n print(\"n/a\")\n\nprint( getX(), \"is the larger value of x\" )\nprint(\"end\")\n"
}
] | 1 |
resistor4u/QAD
|
https://github.com/resistor4u/QAD
|
782cf8804a91c2132a92b277b0c4be04e88f1de2
|
e96cfccb428d1ce7f79a039cc9622481092c6aab
|
ea4759d98fbc3881563acf7a873180967920b276
|
refs/heads/master
| 2021-01-15T10:51:52.317753 | 2016-01-28T09:39:11 | 2016-01-28T09:39:11 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5509114265441895,
"alphanum_fraction": 0.5528770089149475,
"avg_line_length": 50.0189208984375,
"blob_id": "c3cba12a55a37c722bc2b015a480abb02d54dbb3",
"content_id": "3f489e12d5faaecfb8c9733d56f810054cca5ec1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 53977,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 1057,
"path": "/qad_arc_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando ARC per disegnare un arco\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nimport math\n\n\nfrom qad_getpoint import *\nfrom qad_arc_maptool import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nimport qad_utils\nimport qad_layer\nimport qad_grip\n\n\n# Classe che gestisce il comando ARC\nclass QadARCCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadARCCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"ARC\")\n\n def getEnglishName(self):\n return \"ARC\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runARCCommand)\n \n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/arc.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_ARC\", \"Draws an arc by many methods.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.vertices = []\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_arc_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n \n def run(self, msgMapTool = False, msg = None):\n self.isValidPreviousInput = True # per gestire il comando anche in macro\n \n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n currLayer, errMsg = qad_layer.getCurrLayerEditable(self.plugIn.canvas, QGis.Line)\n if currLayer is None:\n self.showErr(errMsg)\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA PRIMO PUNTO o CENTRO\n if self.step == 0: # inizio del comando\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_START_PT) \n keyWords = QadMsg.translate(\"Command_ARC\", \"Center\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the start point of the arc or [{0}]:\").format(keyWords) \n \n englishKeyWords = \"Center\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo di modo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n self.step = 1\n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PRIMO PUNTO o CENTRO\n elif self.step == 1: # dopo aver atteso un punto o enter o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n if self.plugIn.lastPoint is not None:\n value = self.plugIn.lastPoint\n else:\n return True # fine comando\n\n if type(value) == QgsPoint: # se é stato inserito il punto iniziale dell'arco \n self.startPt = value\n self.plugIn.setLastPoint(value)\n \n # imposto il map tool\n self.getPointMapTool().arcStartPt = self.startPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_SECOND_PT)\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Center\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"End\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify second point of the arc or [{0}]:\").format(keyWords) \n \n englishKeyWords = \"Center\" + \"/\" + \"End\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n \n self.step = 2\n return False\n else: # si vuole inserire il centro dell'arco\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_CENTER_PT)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the center of the arc: \"))\n \n self.step = 13\n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO o CENTRO o FINE\n elif self.step == 2: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_ARC\", \"Center\") or value == \"Center\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_CENTER_PT)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the center of the arc: \"))\n self.step = 4 \n elif value == QadMsg.translate(\"Command_ARC\", \"End\") or value == \"End\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_END_PT)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc: \"))\n self.step = 8 \n elif type(value) == QgsPoint: # se é stato inserito il secondo punto dell'arco \n self.secondPt = value\n # imposto il map tool\n self.getPointMapTool().arcSecondPt = self.secondPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_SECOND_PT_KNOWN_ASK_FOR_END_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc: \"))\n self.step = 3\n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO FINALE DELL'ARCO (da step = 2)\n elif self.step == 3: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.endPt = value\n \n arc = QadArc() \n if arc.fromStartSecondEndPts(self.startPt, self.secondPt, self.endPt) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc: \"))\n self.isValidPreviousInput = False # per gestire il comando anche in macro \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA CENTRO DELL'ARCO (da step = 2)\n elif self.step == 4: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n \n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.centerPt = value\n self.plugIn.setLastPoint(value)\n \n # imposto il map tool\n self.getPointMapTool().arcCenterPt = self.centerPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_END_PT)\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"chord Length\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc or [{0}]: \").format(keyWords) \n \n englishKeyWords = \"Angle\" + \"/\" + \"chord Length\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, valori nulli non ammessi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n \n self.step = 5\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco o [Angolo/Lunghezza corda]: \" (da step = 4)\n elif self.step == 5: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode: \n if value == QadMsg.translate(\"Command_ARC\", \"Angle\") or value == \"Angle\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_ANGLE)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori nulli non ammessi\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.step = 6\n return False \n elif value == QadMsg.translate(\"Command_ARC\", \"chord Length\") or value == \"chord Length\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_CHORD)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the chord length: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 7\n return False \n elif type(value) == QgsPoint: # se é stato inserito il punto finale dell'arco\n self.endPt = value\n \n arc = QadArc() \n if arc.fromStartCenterEndPts(self.startPt, self.centerPt, self.endPt) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"chord Length\")\n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc or [{0}]: \").format(keyWords) \n\n englishKeyWords = \"Angle\" + \"/\" + \"chord Length\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, valori nulli non ammessi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n self.isValidPreviousInput = False # per gestire il comando anche in macro\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare angolo inscritto: \" (da step = 5)\n elif self.step == 6: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.angle = qad_utils.getAngleBy2Pts(self.centerPt, value) \n else:\n self.angle = value\n\n arc = QadArc() \n if arc.fromStartCenterPtsAngle(self.startPt, self.centerPt, self.angle) == True:\n self.plugIn.setLastPoint(arc.getEndPt()) \n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori nulli non ammessi\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.isValidPreviousInput = False # per gestire il comando anche in macro \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare lunghezza della corda: \" (da step = 5)\n elif self.step == 7: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.chord = qad_utils.getDistance(self.startPt, value) \n else:\n self.chord = value\n\n arc = QadArc() \n if arc.fromStartCenterPtsChord(self.startPt, self.centerPt, self.chord) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi ammessi\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the chord length: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.isValidPreviousInput = False # per gestire il comando anche in macro \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco: \" (da step = 1)\n elif self.step == 8: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.endPt = value\n self.plugIn.setLastPoint(self.endPt)\n\n # imposto il map tool\n self.getPointMapTool().arcEndPt = self.endPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_CENTER)\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"Direction\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"Radius\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the center point of the arc or [{0}]: \").format(keyWords) \n\n englishKeyWords = \"Angle\" + \"/\" + \"Direction\" + \"/\" + \"Radius\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, valori nulli non ammessi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n \n self.step = 9\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare centro dell'arco o [Angolo/Direzione/Raggio]: \" (da step = 8)\n elif self.step == 9: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_ARC\", \"Angle\") or value == \"Angle\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_ANGLE)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.step = 10\n return False \n elif value == QadMsg.translate(\"Command_ARC\", \"Direction\") or value == \"Direction\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_TAN)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the tangent direction for the start point of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.step = 11\n return False \n elif value == QadMsg.translate(\"Command_ARC\", \"Radius\") or value == \"Radius\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_RADIUS)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the radius of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 12\n return False \n elif type(value) == QgsPoint: # se é stato inserito il centro dell'arco\n self.centerPt = value\n\n arc = QadArc() \n if arc.fromStartCenterEndPts(self.startPt, self.centerPt, self.endPt) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"Direction\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"Radius\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the center point of the arc or [{0}]: \").format(keyWords) \n \n englishKeyWords = \"Angle\" + \"/\" + \"Direction\" + \"/\" + \"Radius\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n self.isValidPreviousInput = False # per gestire il comando anche in macro \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare angolo inscritto: \" (da step = 9)\n elif self.step == 10: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.angle = qad_utils.getAngleBy2Pts(self.startPt, value) \n else:\n self.angle = value\n \n arc = QadArc() \n if arc.fromStartEndPtsAngle(self.startPt, self.endPt, self.angle) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori non nulli\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.isValidPreviousInput = False # per gestire il comando anche in macro \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare direzione tangente per il punto iniziale dell'arco: \" (da step = 9)\n elif self.step == 11: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.angleTan = qad_utils.getAngleBy2Pts(self.startPt, value) \n else:\n self.angleTan = value\n\n arc = QadArc() \n if arc.fromStartEndPtsTan(self.startPt, self.endPt, self.angleTan) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the tangent direction for the start point of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.isValidPreviousInput = False # per gestire il comando anche in macro\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare raggio dell'arco: \" (da step = 9)\n elif self.step == 12: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.radius = qad_utils.getDistance(self.endPt, value) \n else:\n self.radius = value\n\n self.plugIn.setLastRadius(self.radius)\n \n arc = QadArc()\n if arc.fromStartEndPtsRadius(self.startPt, self.endPt, self.radius) == True:\n self.plugIn.setLastPoint(arc.getEndPt())\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnEndPt())\n else:\n self.plugIn.setLastSegmentAng(arc.getTanDirectionOnStartPt() + math.pi)\n \n qad_layer.addLineToLayer(self.plugIn, currLayer, points) \n return True # fine comando\n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_ARC\", \"Specify the radius of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.isValidPreviousInput = False # per gestire il comando anche in macro\n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA CENTRO DELL'ARCO (da step = 1)\n elif self.step == 13: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.centerPt = value\n self.plugIn.setLastPoint(value)\n\n # imposto il map tool\n self.getPointMapTool().arcCenterPt = self.centerPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.CENTER_PT_KNOWN_ASK_FOR_START_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_ARC\", \"Specify the start point of the arc: \"))\n self.step = 14\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO INIZIALE DELL'ARCO (da step = 13)\n elif self.step == 14: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.startPt = value\n self.plugIn.setLastPoint(value)\n\n # imposto il map tool\n self.getPointMapTool().arcStartPt = self.startPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_END_PT)\n \n keyWords = QadMsg.translate(\"Command_ARC\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_ARC\", \"chord Length\")\n \n prompt = QadMsg.translate(\"Command_ARC\", \"Specify the final point of the arc or [{0}]: \").format(keyWords) \n \n englishKeyWords = \"Angle\" + \"/\" + \"chord Length\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n \n self.step = 5\n return False\n\n\n#============================================================================\n# Classe che gestisce il comando per cambiare il raggio di un arco per i grip\n#============================================================================\nclass QadGRIPCHANGEARCRADIUSCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadGRIPCHANGEARCRADIUSCommandClass(self.plugIn)\n\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.entity = None\n self.skipToNextGripCommand = False\n self.copyEntities = False\n self.basePt = QgsPoint()\n self.nOperationsToUndo = 0\n\n \n def __del__(self):\n QadCommandClass.__del__(self)\n\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_gripChangeArcRadius_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n \n #============================================================================\n # setSelectedEntityGripPoints\n #============================================================================\n def setSelectedEntityGripPoints(self, entitySetGripPoints):\n # lista delle entityGripPoint con dei grip point selezionati\n # setta la prima entità con un grip selezionato\n self.entity = None\n for entityGripPoints in entitySetGripPoints.entityGripPoints:\n for gripPoint in entityGripPoints.gripPoints:\n # grip point selezionato\n if gripPoint.getStatus() == qad_grip.QadGripStatusEnum.SELECTED:\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entityGripPoints.entity.isDimensionComponent():\n return False\n if entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.ARC:\n return False\n \n self.entity = entityGripPoints.entity\n arc = entityGripPoints.entity.getQadGeom() # arco in map coordinate\n self.basePt.set(arc.center.x(), arc.center.y())\n return True\n return False\n \n\n #============================================================================\n # changeRadius\n #============================================================================\n def changeRadius(self, radius):\n # radius = nuovo raggio dell'arco\n if radius <= 0:\n return False\n arc = self.entity.getQadGeom()\n arc.radius = radius\n points = arc.asPolyline()\n if points is None:\n return False\n \n g = QgsGeometry.fromPolyline(points)\n f = self.entity.getFeature() \n f.setGeometry(g)\n \n self.plugIn.beginEditCommand(\"Feature stretched\", [self.entity.layer])\n \n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, self.entity.layer, f, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.setLastRadius(radius)\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n return True\n\n\n #============================================================================\n # waitForRadius\n #============================================================================\n def waitForRadius(self):\n keyWords = QadMsg.translate(\"Command_GRIP\", \"Base point\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Copy\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"eXit\")\n prompt = QadMsg.translate(\"Command_GRIPCHANGEARCRADIUS\", \"Specify the radius or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Base point\" + \"/\" + \"Copy\" + \"/\" + \"Undo\" + \"/\" \"eXit\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave\n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 1\n # imposto il map tool\n self.getPointMapTool().setEntity(self.entity) # setta basePt nel centro dell'arco\n self.getPointMapTool().basePt = self.basePt\n self.getPointMapTool().setMode(Qad_gripChangeArcRadius_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_RADIUS_PT)\n\n\n #============================================================================\n # waitForBasePt\n #============================================================================\n def waitForBasePt(self):\n self.step = 2 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_gripChangeArcRadius_maptool_ModeEnum.ASK_FOR_BASE_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_GRIP\", \"Specify base point: \"))\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI\n if self.step == 0: # inizio del comando\n if self.entity is None: # non ci sono oggetti da stirare\n return True\n self.showMsg(QadMsg.translate(\"Command_GRIPCHANGEARCRADIUS\", \"\\n** RADIUS **\\n\"))\n # si appresta ad attendere raggio\n self.waitForRadius()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL RAGGIO DI RACCORDO (da step = 1)\n elif self.step == 1:\n ctrlKey = False\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n ctrlKey = self.getPointMapTool().ctrlKey\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_GRIP\", \"Base point\") or value == \"Base point\":\n # si appresta ad attendere il punto base\n self.waitForBasePt()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Copy\") or value == \"Copy\":\n # Copia entità lasciando inalterate le originali\n self.copyEntities = True \n # si appresta ad attendere raggio\n self.waitForRadius()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n # si appresta ad attendere raggio\n self.waitForRadius()\n elif value == QadMsg.translate(\"Command_GRIP\", \"eXit\") or value == \"eXit\":\n return True # fine comando\n elif type(value) == QgsPoint or type(value) == float: # se é stato inserito il raggio\n if type(value) == QgsPoint: # se é stato inserito il raggio con un punto\n if value == self.basePt:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe value must be positive and not zero.\"))\n # si appresta ad attendere raggio\n self.waitForRadius()\n return False\n \n radius = qad_utils.getDistance(self.basePt, value)\n else:\n radius = value\n\n if ctrlKey:\n self.copyEntities = True\n \n self.changeRadius(radius)\n\n if self.copyEntities == False:\n return True\n # si appresta ad attendere raggio\n self.waitForRadius()\n else:\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n pass # opzione di default\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint: # se é stato inserito il punto base\n self.basePt.set(value.x(), value.y())\n # imposto il map tool\n self.getPointMapTool().basePt = self.basePt\n \n # si appresta ad attendere raggio\n self.waitForRadius()\n\n return False\n"
},
{
"alpha_fraction": 0.5962313413619995,
"alphanum_fraction": 0.5981156826019287,
"avg_line_length": 43.15925216674805,
"blob_id": "88ffe017c8fd1333d53f2cbf8bea6172d1988b5d",
"content_id": "f07702befb47bbae2a1d6d50a19eb6e355cdd9ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 30786,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 697,
"path": "/qad_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n map tool per lo stato di quiete\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nimport qad_utils\nfrom qad_variables import *\nfrom qad_rubberband import *\nfrom qad_getpoint import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_entity import *\nfrom qad_ssget_cmd import QadSSGetClass\nfrom qad_grip import *\nfrom qad_stretch_cmd import QadGRIPSTRETCHCommandClass\nfrom qad_move_cmd import QadGRIPMOVECommandClass\nfrom qad_rotate_cmd import QadGRIPROTATECommandClass\nfrom qad_scale_cmd import QadGRIPSCALECommandClass\nfrom qad_mirror_cmd import QadGRIPMIRRORCommandClass\nfrom qad_arc_cmd import QadGRIPCHANGEARCRADIUSCommandClass\nfrom qad_lengthen_cmd import QadGRIPLENGTHENCommandClass\nfrom qad_pedit_cmd import QadGRIPINSERTREMOVEVERTEXCommandClass, QadGRIPARCLINECONVERTCommandClass\n\nfrom qad_msg import QadMsg\n\n\n# Main Map Tool class.\nclass QadMapTool(QgsMapTool):\n \n def __init__(self, plugIn): \n QgsMapTool.__init__(self, plugIn.iface.mapCanvas())\n self.plugIn = plugIn\n self.iface = self.plugIn.iface\n self.canvas = self.plugIn.iface.mapCanvas() \n self.cursor = QCursor(Qt.BlankCursor)\n self.__csrRubberBand = QadCursorRubberBand(self.canvas, QadCursorTypeEnum.BOX | QadCursorTypeEnum.CROSS)\n self.entitySet = QadEntitySet()\n self.entitySetGripPoints = QadEntitySetGripPoints(plugIn)\n \n self.gripPopupMenu = None\n self.timerForGripMenu = QTimer()\n self.timerForGripMenu.setSingleShot(True)\n\n def __del__(self):\n self.removeItems()\n\n\n def removeItems(self): \n if self.__csrRubberBand is not None:\n self.__csrRubberBand.removeItems() # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__csrRubberBand\n __csrRubberBand = None\n self.entitySet.clear()\n self.entitySetGripPoints.removeItems()\n\n\n def UpdatedVariablesEvent(self):\n # aggiorna in base alle nuove impostazioni delle variabili\n self.removeItems() \n self.__csrRubberBand = QadCursorRubberBand(self.canvas, QadCursorTypeEnum.BOX | QadCursorTypeEnum.CROSS)\n\n\n def clearEntitySet(self):\n self.entitySet.deselectOnLayer()\n self.entitySet.clear()\n\n\n def clearEntityGripPoints(self):\n self.entitySetGripPoints.removeItems() # svuoto la lista\n\n\n def refreshEntityGripPoints(self, entitySet = None):\n if entitySet is None:\n entitySet = self.entitySet\n \n # cancello i grip delle entità che non sono in entitySet o che non sono in layer vettoriali modificabili\n i = self.entitySetGripPoints.count() - 1\n while i >= 0:\n entityGripPoint = self.entitySetGripPoints.entityGripPoints[i]\n if entitySet.containsEntity(entityGripPoint.entity) == False or \\\n entityGripPoint.entity.layer.type() != QgsMapLayer.VectorLayer or entityGripPoint.entity.layer.isEditable() == False:\n del self.entitySetGripPoints.entityGripPoints[i]\n i = i - 1\n \n entity = QadEntity()\n for layerEntitySet in entitySet.layerEntitySetList:\n # considero solo i layer vettoriali che sono modificabili\n layer = layerEntitySet.layer\n if layer.type() == QgsMapLayer.VectorLayer and layer.isEditable():\n for featureId in layerEntitySet.featureIds:\n entity.set(layer, featureId)\n self.entitySetGripPoints.addEntity(entity, QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPS\")))\n \n\n #============================================================================\n # INIZIO - eventi per il mouse\n #============================================================================\n\n \n def canvasPressEvent(self, event):\n # volevo mettere questo evento nel canvasReleaseEvent\n # ma il tasto destro non genera quel tipo di evento\n if event.button() == Qt.RightButton:\n self.displayPopupMenuOnQuiescentState(event.pos())\n elif event.button() == Qt.LeftButton:\n # verifico se tasto shift premuto\n shiftKey = True if event.modifiers() & Qt.ShiftModifier else False\n # posizione corrente del mouse\n point = self.toMapCoordinates(event.pos())\n # leggo il punto grip che si interseca alla posizione del mouse\n entityGripPoint = self.entitySetGripPoints.isIntersecting(point)\n if entityGripPoint is not None:\n if shiftKey == False: # lancio il comando\n selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints()\n # se non ci sono già grip selezionati\n if len(selectedEntityGripPoints) == 0:\n # seleziono il corrente\n if self.entitySetGripPoints.selectIntersectingGripPoints(point) > 0:\n selectedEntityGripPoints = self.entitySetGripPoints.getSelectedEntityGripPoints()\n\n # lancio il comando\n self.plugIn.runCommand(\"QadVirtualGripCommandsClass\", [QadVirtualGripCommandsEnum.STRECTH, self.entitySetGripPoints, point])\n else: # shift premuto\n # inverto lo stato ai grip che intersecano il punto \n self.entitySetGripPoints.toggleSelectIntersectingGripPoints(point)\n else:\n result = qad_utils.getEntSel(event.pos(), self)\n if result is not None:\n feature = result[0]\n layer = result[1]\n tmpEntity = QadEntity()\n tmpEntity.set(layer, feature.id())\n SSGetClass = QadSSGetClass(self.plugIn)\n SSGetClass.entitySet.set(self.entitySet)\n SSGetClass.elaborateEntity(tmpEntity, shiftKey)\n self.entitySet.set(SSGetClass.entitySet)\n del SSGetClass # che deseleziona gli oggetti\n self.entitySet.selectOnLayer(False)\n self.refreshEntityGripPoints(self.entitySet)\n else:\n self.plugIn.runCommand(\"QadVirtualSelCommandClass\", point)\n \n\n def canvasDoubleClickEvent(self,event):\n pass\n\n\n def canvasMoveEvent(self, event):\n self.timerForGripMenu.stop()\n point = self.toMapCoordinates(event.pos())\n self.__csrRubberBand.moveEvent(point)\n if self.entitySetGripPoints.hoverIntersectingGripPoints(point) == 1:\n for entityGripPoint in self.entitySetGripPoints.entityGripPoints:\n for gripPoint in entityGripPoint.gripPoints:\n if gripPoint.isIntersecting(point) and gripPoint.getStatus() == QadGripStatusEnum.HOVER:\n pos = QPoint(event.pos().x(), event.pos().y())\n shot = lambda: self.displayPopupMenuOnGrip(pos, entityGripPoint.entity, gripPoint)\n \n del self.timerForGripMenu\n self.timerForGripMenu = QTimer()\n self.timerForGripMenu.setSingleShot(True)\n self.timerForGripMenu.timeout.connect(shot)\n self.timerForGripMenu.start(1000)\n return\n \n # se non ci sono grip point selezionati\n if len(self.entitySetGripPoints.getSelectedEntityGripPoints()) == 0:\n # leggo il punto grip che si interseca alla posizione del mouse\n entityGripPoint = self.entitySetGripPoints.isIntersecting(point)\n if entityGripPoint is not None: \n # leggo il primo punto di grip che interseca point (in map coordinate)\n gripPoint = entityGripPoint.isIntersecting(point)\n \n\n def canvasReleaseEvent(self, event):\n pass\n\n \n #============================================================================\n # FINE - eventi per il mouse\n # INIZIO - eventi per la tastiera\n #============================================================================\n\n\n def keyPressEvent(self, event):\n self.plugIn.keyPressEvent(event)\n\n\n def keyReleaseEvent(self, event):\n pass\n\n\n #============================================================================\n # FINE - eventi per la tastiera\n # INIZIO - eventi per la rotella\n #============================================================================\n\n\n def wheelEvent(self, event):\n self.__csrRubberBand.moveEvent(self.toMapCoordinates(event.pos()))\n\n\n #============================================================================\n # FINE - eventi per la rotella\n #============================================================================\n\n \n def activate(self):\n self.canvas.setCursor(self.cursor)\n # posizione corrente del mouse\n self.__csrRubberBand.moveEvent(self.toMapCoordinates(self.canvas.mouseLastXY()))\n self.__csrRubberBand.show()\n self.entitySet.initByCurrentQgsSelectedFeatures(self.canvas.layers())\n self.refreshEntityGripPoints(self.entitySet)\n\n self.plugIn.QadCommands.continueCommandFromMapTool()\n \n def deactivate(self):\n self.__csrRubberBand.hide()\n self.timerForGripMenu.stop()\n \n def isTransient(self):\n return False # questo tool non fa zoom o pan\n\n def isEditTool(self):\n return False # questo tool non fa editing\n\n\n #============================================================================\n # displayPopupMenuOnQuiescentState\n #============================================================================\n def displayPopupMenuOnQuiescentState(self, pos):\n popupMenu = QMenu(self.canvas)\n history = self.plugIn.getHistoryfromTxtWindow()\n isLastCmdToInsert = True\n isRecentMenuToInsert = True\n \n historyLen = len(history)\n i = historyLen - 1\n cmdInputHistoryMax = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CMDINPUTHISTORYMAX\"))\n while i >= 0 and (historyLen - i) <= cmdInputHistoryMax:\n cmdName = history[i]\n i = i - 1\n cmd = self.plugIn.QadCommands.getCommandObj(cmdName)\n if cmd is not None:\n if isLastCmdToInsert:\n isLastCmdToInsert = False\n msg = QadMsg.translate(\"Popup_menu_graph_window\", \"Repeat \") + cmd.getName()\n icon = cmd.getIcon()\n if icon is None:\n lastCmdAction = QAction(msg, popupMenu)\n else:\n lastCmdAction = QAction(icon, msg, popupMenu)\n cmd.connectQAction(lastCmdAction) \n popupMenu.addAction(lastCmdAction) \n else:\n if isRecentMenuToInsert:\n isRecentMenuToInsert = False\n recentCmdsMenu = popupMenu.addMenu(QadMsg.translate(\"Popup_menu_graph_window\", \"Recent commands\"))\n\n icon = cmd.getIcon()\n if icon is None:\n recentCmdAction = QAction(cmd.getName(), recentCmdsMenu)\n else:\n recentCmdAction = QAction(icon, cmd.getName(), recentCmdsMenu) \n cmd.connectQAction(recentCmdAction) \n recentCmdsMenu.addAction(recentCmdAction)\n \n if isLastCmdToInsert == False: # menu non vuoto\n popupMenu.popup(self.canvas.mapToGlobal(pos))\n\n\n #============================================================================\n # runCmdFromPopupMenuOnGrip\n #============================================================================\n def runCmdFromPopupMenuOnGrip(self, virtualGripCommand, gripPoint):\n # seleziona il grip\n gripPoint.select()\n # lancio il comando\n self.plugIn.runCommand(\"QadVirtualGripCommandsClass\", [virtualGripCommand, self.entitySetGripPoints, gripPoint.getPoint()])\n\n\n #============================================================================\n # displayPopupMenuOnGrip\n #============================================================================\n def displayPopupMenuOnGrip(self, pos, entity, gripPoint):\n if self.gripPopupMenu is not None:\n self.gripPopupMenu.hide()\n del self.gripPopupMenu\n self.gripPopupMenu = None\n \n popupMenu = QadGripPopupMenu(self.canvas)\n \n found = False\n \n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.isDimensionComponent():\n pass\n else:\n entityType = entity.getEntityType(gripPoint.atGeom, gripPoint.atSubGeom)\n if entityType == QadEntityGeomTypeEnum.ARC:\n arc = entity.getQadGeom(gripPoint.atGeom, gripPoint.atSubGeom)\n \n # se punti finali\n if gripPoint.isIntersecting(arc.getStartPt()) or gripPoint.isIntersecting(arc.getEndPt()):\n found = True\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Stretch\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.STRECTH, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Lengthen\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.LENGTHEN, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n # se punto medio\n elif gripPoint.isIntersecting(entity.qadGeom.getMiddlePt()):\n found = True\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Stretch\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.STRECTH, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Radius\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.CHANGE_RADIUS, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Convert to line\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ARC_TO_LINE, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n elif entityType == QadEntityGeomTypeEnum.LINESTRING:\n linearObjectList = entity.getQadGeom(gripPoint.atGeom, gripPoint.atSubGeom)\n isClosed = linearObjectList.isClosed()\n nVertex = 0\n found = False\n while nVertex < linearObjectList.qty():\n linearObject = linearObjectList.getLinearObjectAt(nVertex)\n\n if gripPoint.isIntersecting(linearObject.getStartPt()):\n found = True\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Stretch vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.STRECTH, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n # punto iniziale\n if isClosed == False and nVertex == 0:\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Lengthen\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.LENGTHEN, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex before\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX_BEFORE, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n break\n \n # punto medio\n if gripPoint.isIntersecting(linearObject.getMiddlePt()):\n found = True\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Stretch\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.STRECTH, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex before\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX_BEFORE, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n if linearObject.isSegment(): # linea\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Convert to arc\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.LINE_TO_ARC, gripPoint)\n else: # arco\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Convert to line\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ARC_TO_LINE, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n break\n \n nVertex = nVertex + 1\n \n linearObject = linearObjectList.getLinearObjectAt(-1) # ultima parte\n if not found and isClosed == False:\n # punto finale\n if gripPoint.isIntersecting(linearObject.getEndPt()):\n found = True\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Stretch vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.STRECTH, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Lengthen\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.LENGTHEN, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Add vertex before\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.ADD_VERTEX_BEFORE, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n\n if isClosed == False: # polyline\n # ci devono essere almeno 2 parti\n if linearObjectList.qty() >= 2:\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Remove vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.REMOVE_VERTEX, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n else: # polygon\n # ci devono essere almeno 4 parti\n if linearObjectList.qty() >= 4:\n msg = QadMsg.translate(\"Popup_menu_grip_window\", \"Remove vertex\")\n action = QAction(msg, popupMenu)\n f = lambda : self.runCmdFromPopupMenuOnGrip(QadVirtualGripCommandsEnum.REMOVE_VERTEX, gripPoint)\n QObject.connect(action, SIGNAL(\"triggered()\"), f)\n popupMenu.addAction(action)\n \n if found: # menu non vuoto\n popupMenu.popup(self.canvas.mapToGlobal(pos))\n self.gripPopupMenu = popupMenu\n \n return None\n\n\nclass QadGripPopupMenu(QMenu):\n def __init__(self, parent):\n QMenu.__init__(self, parent)\n self.offset = 0\n\n def popup(self, pos, action = None):\n newPos = QPoint(pos.x() + self.offset, pos.y() + self.offset)\n QMenu.popup(self, newPos, action)\n \n# def leaveEvent(self, event):\n# if event.pos().x() < -1 * self.offset or event.pos().y() < -1 * self.offset:\n# self.hide()\n #self.hide()\n\n def mouseMoveEvent(self, event):\n x = event.pos().x()\n y = event.pos().y()\n if x < -1 * self.offset or y < -1 * self.offset or \\\n x > self.width() or y > self.height():\n self.hide()\n else:\n QMenu.mouseMoveEvent(self, event)\n\n# newPos = self.parentWidget().mapFromGlobal(event.globalPos())\n# newMouseEvent = QMouseEvent(QEvent.MouseMove, newPos, Qt.NoButton, event.buttons(), event.modifiers())\n# self.parentWidget().mouseMoveEvent(newMouseEvent)\n\n\n# Classe che gestisce il comando di selezione quando QAD è in stato di quiete\nclass QadVirtualSelCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadVirtualSelCommandClass(self.plugIn)\n \n def getName(self):\n return \"QadVirtualSelCommandClass\"\n\n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.SSGetClass = QadSSGetClass(plugIn)\n self.SSGetClass.entitySet.set(plugIn.tool.entitySet) # da usare solo con QadMapTool\n self.SSGetClass.exitAfterSelection = True\n self.SSGetClass.step = 1\n \n def __del__(self):\n QadCommandClass.__del__(self)\n del self.SSGetClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n return self.SSGetClass.getPointMapTool(drawMode)\n\n def run(self, msgMapTool = False, msg = None):\n res = self.SSGetClass.run(msgMapTool, msg)\n if res == True:\n self.plugIn.tool.entitySet.set(self.SSGetClass.entitySet) # da usare solo con QadMapTool\n self.plugIn.tool.entitySet.selectOnLayer()\n return res\n\n\n#===============================================================================\n# QadVirtualGripCommandsEnum class. \n#===============================================================================\nclass QadVirtualGripCommandsEnum():\n NONE = 0\n STRECTH = 1\n MOVE = 2\n ROTATE = 3\n SCALE = 4\n MIRROR = 5\n LENGTHEN = 6\n ADD_VERTEX = 7\n REMOVE_VERTEX = 8\n LINE_TO_ARC = 9\n ARC_TO_LINE = 10\n CHANGE_RADIUS = 11\n ADD_VERTEX_BEFORE = 12\n\n\n# Classe che gestisce i comando disponibili sui grip quando QAD è in stato di quiete\nclass QadVirtualGripCommandsClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadVirtualGripCommandsClass(self.plugIn)\n \n def getName(self):\n return \"QadVirtualGripCommandsClass\"\n\n def __init__(self, plugIn): \n QadCommandClass.__init__(self, plugIn)\n self.commandNum = QadVirtualGripCommandsEnum.NONE\n self.currentCommand = None\n self.entitySetGripPoints = None\n self.basePt = QgsPoint()\n \n def __del__(self):\n QadCommandClass.__del__(self)\n del self.currentCommand\n\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.currentCommand is not None: \n return self.currentCommand.getPointMapTool(drawMode)\n else:\n return None\n\n def getCommand(self):\n if self.commandNum == QadVirtualGripCommandsEnum.STRECTH:\n return QadGRIPSTRETCHCommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.MOVE:\n return QadGRIPMOVECommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.ROTATE:\n return QadGRIPROTATECommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.SCALE:\n return QadGRIPSCALECommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.MIRROR:\n return QadGRIPMIRRORCommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.CHANGE_RADIUS:\n return QadGRIPCHANGEARCRADIUSCommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.LENGTHEN:\n return QadGRIPLENGTHENCommandClass(self.plugIn)\n elif self.commandNum == QadVirtualGripCommandsEnum.ADD_VERTEX:\n cmd = QadGRIPINSERTREMOVEVERTEXCommandClass(self.plugIn)\n cmd.setInsertVertexAfter_Mode()\n return cmd\n elif self.commandNum == QadVirtualGripCommandsEnum.ADD_VERTEX_BEFORE:\n cmd = QadGRIPINSERTREMOVEVERTEXCommandClass(self.plugIn)\n cmd.setInsertVertexBefore_Mode()\n return cmd\n elif self.commandNum == QadVirtualGripCommandsEnum.REMOVE_VERTEX:\n cmd = QadGRIPINSERTREMOVEVERTEXCommandClass(self.plugIn)\n cmd.setRemoveVertex_mode()\n return cmd\n elif self.commandNum == QadVirtualGripCommandsEnum.LINE_TO_ARC:\n cmd = QadGRIPARCLINECONVERTCommandClass(self.plugIn)\n cmd.setLineToArcConvert_Mode()\n return cmd\n elif self.commandNum == QadVirtualGripCommandsEnum.ARC_TO_LINE:\n cmd = QadGRIPARCLINECONVERTCommandClass(self.plugIn)\n cmd.setArcToLineConvert_Mode()\n return cmd\n \n return None\n\n\n def initStartCommand(self, commandNum):\n if self.currentCommand is not None:\n del self.currentCommand\n self.currentCommand = None\n \n self.commandNum = commandNum\n self.currentCommand = self.getCommand()\n\n if self.currentCommand is not None:\n self.currentCommand.basePt.set(self.basePt.x(), self.basePt.y())\n self.currentCommand.setSelectedEntityGripPoints(self.entitySetGripPoints)\n return True\n else:\n return False\n\n\n def initNextCommand(self):\n if self.currentCommand is not None:\n del self.currentCommand\n self.currentCommand = None\n \n if self.commandNum == QadVirtualGripCommandsEnum.STRECTH or \\\n self.commandNum == QadVirtualGripCommandsEnum.LENGTHEN or \\\n self.commandNum == QadVirtualGripCommandsEnum.ADD_VERTEX or \\\n self.commandNum == QadVirtualGripCommandsEnum.ADD_VERTEX_BEFORE or \\\n self.commandNum == QadVirtualGripCommandsEnum.REMOVE_VERTEX or \\\n self.commandNum == QadVirtualGripCommandsEnum.LINE_TO_ARC or \\\n self.commandNum == QadVirtualGripCommandsEnum.ARC_TO_LINE or \\\n self.commandNum == QadVirtualGripCommandsEnum.CHANGE_RADIUS:\n self.commandNum = QadVirtualGripCommandsEnum.MOVE\n elif self.commandNum == QadVirtualGripCommandsEnum.MOVE:\n self.commandNum = QadVirtualGripCommandsEnum.ROTATE\n elif self.commandNum == QadVirtualGripCommandsEnum.ROTATE:\n self.commandNum = QadVirtualGripCommandsEnum.SCALE\n elif self.commandNum == QadVirtualGripCommandsEnum.SCALE:\n self.commandNum = QadVirtualGripCommandsEnum.MIRROR\n elif self.commandNum == QadVirtualGripCommandsEnum.MIRROR:\n self.commandNum = QadVirtualGripCommandsEnum.MOVE\n\n self.currentCommand = self.getCommand()\n\n if self.currentCommand is not None:\n self.currentCommand.basePt.set(self.basePt.x(), self.basePt.y())\n self.currentCommand.setSelectedEntityGripPoints(self.entitySetGripPoints)\n return True\n else:\n return False\n \n \n def run(self, msgMapTool = False, msg = None):\n if self.currentCommand is None:\n return True\n res = self.currentCommand.run(msgMapTool, msg)\n if res == True:\n if self.currentCommand.skipToNextGripCommand == True:\n if self.initNextCommand(): # attivo comando successivo\n return self.currentCommand.run(msgMapTool, msg)\n else:\n # ridisegno i grip point nelle nuove posizioni resettando quelli selezionati\n self.plugIn.tool.clearEntityGripPoints()\n self.plugIn.tool.refreshEntityGripPoints()\n\n return res\n\n"
},
{
"alpha_fraction": 0.5233983993530273,
"alphanum_fraction": 0.5265682339668274,
"avg_line_length": 52.8786506652832,
"blob_id": "1cccf2876a4504a07947f9c5d00a751ba41411a7",
"content_id": "b63879396b99a75b6c3b4944c0a3ae566eaf374f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 23990,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 445,
"path": "/qad_trim_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando TRIM per tagliare o estendere oggetti grafici\n \n -------------------\n begin : 2013-07-15\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_getpoint import *\nfrom qad_textwindow import *\nfrom qad_pline_cmd import QadPLINECommandClass\nfrom qad_rectangle_cmd import QadRECTANGLECommandClass\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nimport qad_utils\nimport qad_layer\nfrom qad_ssget_cmd import QadSSGetClass\nfrom qad_dim import QadDimStyles\n\n\n# Classe che gestisce il comando TRIM\nclass QadTRIMCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadTRIMCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"TRIM\")\n\n def getEnglishName(self):\n return \"TRIM\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runTRIMCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/trim.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_TRIM\", \"Trims (or extends) objects to meet the edges of other objects.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.SSGetClass = QadSSGetClass(plugIn)\n self.PLINECommand = None \n self.RECTANGLECommand = None\n self.entitySet = QadEntitySet() # entità da tagliare o estendere\n self.limitEntitySet = QadEntitySet() # entità che fanno da limiti\n self.edgeMode = QadVariables.get(QadMsg.translate(\"Environment variables\", \"EDGEMODE\"))\n self.defaultValue = None # usato per gestire il tasto dx del mouse\n self.nOperationsToUndo = 0\n\n def __del__(self):\n QadCommandClass.__del__(self)\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 3: # quando si é in fase di disegno linea\n return self.PLINECommand.getPointMapTool(drawMode)\n elif self.step == 4: # quando si é in fase di disegno rettangolo \n return self.RECTANGLECommand.getPointMapTool(drawMode) \n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n\n #============================================================================\n # trimFeatures\n #============================================================================\n def trimFeatures(self, geom, toExtend):\n # geom è in map coordinates\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n LineTempLayer = None\n self.plugIn.beginEditCommand(\"Feature extended\" if toExtend else \"Feature trimmed\", \\\n self.entitySet.getLayerList())\n \n for layerEntitySet in self.entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n\n for featureId in layerEntitySet.featureIds:\n f = qad_utils.getFeatureById(layer, featureId)\n if f is None:\n continue\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n f_geom = self.layerToMapCoordinates(layer, f.geometry())\n \n if geom.type() == QGis.Point:\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(geom.asPoint(), f_geom)\n if dummy[1] is not None:\n intPts = [dummy[1]]\n else:\n intPts = qad_utils.getIntersectionPoints(geom, f_geom)\n \n for intPt in intPts: \n if toExtend:\n newGeom = qad_utils.extendQgsGeometry(self.plugIn.canvas.mapRenderer().destinationCrs(), f_geom, intPt, \\\n self.limitEntitySet, self.edgeMode, \\\n tolerance2ApproxCurve)\n if newGeom is not None:\n # aggiorno la feature con la geometria estesa\n extendedFeature = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n extendedFeature.setGeometry(self.mapToLayerCoordinates(layer, newGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, extendedFeature, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else: # trim\n result = qad_utils.trimQgsGeometry(self.plugIn.canvas.mapRenderer().destinationCrs(), f_geom, intPt, \\\n self.limitEntitySet, self.edgeMode, \\\n tolerance2ApproxCurve) \n if result is not None:\n line1 = result[0]\n line2 = result[1]\n atSubGeom = result[2]\n if layer.geometryType() == QGis.Line:\n updGeom = qad_utils.setSubGeom(f_geom, line1, atSubGeom)\n if updGeom is None:\n self.plugIn.destroyEditCommand()\n return\n trimmedFeature1 = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n trimmedFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, trimmedFeature1, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n if line2 is not None:\n trimmedFeature2 = QgsFeature(f) \n # trasformo la geometria nel crs del layer\n trimmedFeature2.setGeometry(self.mapToLayerCoordinates(layer, line2))\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, trimmedFeature2, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return \n else:\n # aggiungo le linee nei layer temporanei di QAD\n if LineTempLayer is None:\n LineTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Line)\n self.plugIn.addLayerToLastEditCommand(\"Feature trimmed\", LineTempLayer)\n \n lineGeoms = [line1]\n if line2 is not None:\n lineGeoms.append(line2)\n\n # trasformo la geometria in quella dei layer temporanei\n # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh\n if qad_layer.addGeometriesToQADTempLayers(self.plugIn, None, lineGeoms, None, None, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n updGeom = qad_utils.delSubGeom(f_geom, atSubGeom)\n \n if updGeom is None or updGeom.isGeosEmpty(): # da cancellare\n # plugIn, layer, feature id, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, layer, f.id(), False) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n trimmedFeature1 = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n trimmedFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, trimmedFeature1, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n \n #============================================================================\n # waitForObjectSel\n #============================================================================\n def waitForObjectSel(self): \n self.step = 2 \n # imposto il map tool\n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC)\n # solo layer lineari editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line and layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.getPointMapTool().layersToCheck = layerList\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.getPointMapTool().onlyEditableLayers = True\n \n keyWords = QadMsg.translate(\"Command_TRIM\", \"Fence\") + \"/\" + \\\n QadMsg.translate(\"Command_TRIM\", \"Crossing\") + \"/\" + \\\n QadMsg.translate(\"Command_TRIM\", \"Edge\") + \"/\" + \\\n QadMsg.translate(\"Command_TRIM\", \"Undo\") \n prompt = QadMsg.translate(\"Command_TRIM\", \"Select the object to trim or shift-select to extend or [{0}]: \").format(keyWords) \n \n englishKeyWords = \"Fence\" + \"/\" + \"Crossing\" + \"/\" + \"Edge\" + \"/\" + \"Undo\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI LIMITI\n if self.step == 0: # inizio del comando\n CurrSettingsMsg = QadMsg.translate(\"QAD\", \"\\nCurrent settings: \")\n if self.edgeMode == 0: # 0 = nessuna estensione\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_TRIM\", \"Edge = No extend\")\n else:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_TRIM\", \"Edge = Extend\")\n \n self.showMsg(CurrSettingsMsg) \n self.showMsg(QadMsg.translate(\"Command_TRIM\", \"\\nSelect trim limits...\"))\n \n if self.SSGetClass.run(msgMapTool, msg) == True:\n # selezione terminata\n self.step = 1\n return self.run(msgMapTool, msg) \n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI LIMITI\n elif self.step == 1:\n self.limitEntitySet.set(self.SSGetClass.entitySet)\n \n if self.limitEntitySet.count() == 0:\n return True # fine comando\n\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI DA ESTENDERE\n elif self.step == 2:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_TRIM\", \"Fence\") or value == \"Fence\":\n # Seleziona tutti gli oggetti che intersecano una polilinea\n self.PLINECommand = QadPLINECommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.PLINECommand.virtualCmd = True \n self.PLINECommand.run(msgMapTool, msg)\n self.step = 3\n return False \n elif value == QadMsg.translate(\"Command_TRIM\", \"Crossing\") or value == \"Crossing\":\n # Seleziona tutti gli oggetti che intersecano un rettangolo \n self.RECTANGLECommand = QadRECTANGLECommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.RECTANGLECommand.virtualCmd = True \n self.RECTANGLECommand.run(msgMapTool, msg)\n self.step = 4\n return False \n elif value == QadMsg.translate(\"Command_TRIM\", \"Edge\") or value == \"Edge\":\n # Per estendere un oggetto usando anche le estensioni degli oggetti di riferimento\n # vedi variabile EDGEMODE\n keyWords = QadMsg.translate(\"Command_TRIM\", \"Extend\") + \"/\" + \\\n QadMsg.translate(\"Command_TRIM\", \"No extend\")\n if self.edgeMode == 0: # 0 = nessuna estensione\n self.defaultValue = QadMsg.translate(\"Command_TRIM\", \"No\")\n else: \n self.defaultValue = QadMsg.translate(\"Command_TRIM\", \"Extend\")\n prompt = QadMsg.translate(\"Command_TRIM\", \"Specify an extension mode [{0}] <{1}>: \").format(keyWords, self.defaultValue) \n \n englishKeyWords = \"Extend\" + \"/\" + \"No extend\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.KEYWORDS, \\\n self.defaultValue, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 5 \n return False \n elif value == QadMsg.translate(\"Command_TRIM\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\"))\n elif type(value) == QgsPoint: # se é stato selezionato un punto\n self.entitySet.clear()\n if self.getPointMapTool().entity.isInitialized():\n self.entitySet.addEntity(self.getPointMapTool().entity)\n ToExtend = True if self.getPointMapTool().shiftKey == True else False\n self.trimFeatures(QgsGeometry.fromPoint(value), ToExtend)\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line and layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n feature = result[0]\n layer = result[1]\n point = result[2]\n self.entitySet.addEntity(QadEntity().set(layer, feature.id()))\n self.trimFeatures(QgsGeometry.fromPoint(point), False)\n else:\n return True # fine comando\n \n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel()\n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' INTERCETTA (da step = 2)\n elif self.step == 3: # dopo aver atteso un punto si riavvia il comando\n if self.PLINECommand.run(msgMapTool, msg) == True:\n if len(self.PLINECommand.vertices) > 1:\n if msgMapTool == True: # se la polilinea arriva da una selezione grafica\n ToExtend = True if self.getPointMapTool().shiftKey == True else False\n else:\n ToExtend = False\n\n # cerco tutte le geometrie passanti per la polilinea saltando i layer punto e poligono\n # e considerando solo layer editabili \n self.entitySet = qad_utils.getSelSet(\"F\", self.getPointMapTool(), self.PLINECommand.vertices, \\\n None, False, True, False, \\\n True) \n self.trimFeatures(QgsGeometry.fromPolyline(self.PLINECommand.vertices), ToExtend)\n del self.PLINECommand\n self.PLINECommand = None\n\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel()\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di pline \n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' INTERSECA (da step = 2)\n elif self.step == 4: # dopo aver atteso un punto si riavvia il comando\n if self.RECTANGLECommand.run(msgMapTool, msg) == True: \n if len(self.RECTANGLECommand.vertices) > 1:\n if msgMapTool == True: # se la polilinea arriva da una selezione grafica\n ToExtend = True if self.getPointMapTool().shiftKey == True else False\n else:\n ToExtend = False\n \n # cerco tutte le geometrie passanti per la polilinea saltando i layer punto e poligono\n # e considerando solo layer editabili \n self.entitySet = qad_utils.getSelSet(\"F\", self.getPointMapTool(), self.RECTANGLECommand.vertices, \\\n None, False, True, False, \\\n True) \n self.trimFeatures(QgsGeometry.fromPolyline(self.RECTANGLECommand.vertices), ToExtend)\n del self.RECTANGLECommand\n self.RECTANGLECommand = None\n\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel() \n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di rectangle \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DI TIPO DI ESTENSIONE (da step = 2)\n elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.defaultValue \n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else: # il valore arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_TRIM\", \"No\") or value == \"No\":\n self.edgeMode = 0\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"EDGEMODE\"), self.edgeMode)\n QadVariables.save()\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel()\n elif value == QadMsg.translate(\"Command_TRIM\", \"Extend\") or value == \"Extend\":\n self.edgeMode = 1\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"EDGEMODE\"), self.edgeMode)\n QadVariables.save()\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSel()\n \n return False\n"
},
{
"alpha_fraction": 0.5497404336929321,
"alphanum_fraction": 0.5551856160163879,
"avg_line_length": 48.85232162475586,
"blob_id": "7c85722a3c9fba06898e0400f99b9d821f82240a",
"content_id": "fb06a88ef3380dbb0a202d6a102b4ea12c3d0a32",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 35467,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 711,
"path": "/qad_fillet_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando FILLET per raccordare due oggetti grafici\n \n -------------------\n begin : 2014-01-30\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_getdist_cmd import QadGetDistClass\nfrom qad_snapper import *\nfrom qad_fillet_maptool import *\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nimport qad_utils\nimport qad_layer\nfrom qad_variables import *\nfrom qad_dim import QadDimStyles\n\n\n# Classe che gestisce il comando FILLET\nclass QadFILLETCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadFILLETCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"FILLET\")\n\n def getEnglishName(self):\n return \"FILLET\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runFILLETCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/fillet.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_FILLET\", \"Rounds and fillets the edges of objects.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn) \n self.GetDistClass = None\n\n self.entity1 = QadEntity()\n self.atSubGeom1 = None\n self.linearObjectList1 = qad_utils.QadLinearObjectList()\n self.partAt1 = 0\n self.pointAt1 = None\n \n self.entity2 = QadEntity()\n self.atSubGeom2 = None\n self.linearObjectList2 = qad_utils.QadLinearObjectList()\n self.partAt2 = 0\n self.pointAt2 = None\n\n self.filletMode = plugIn.filletMode # modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n self.radius = QadVariables.get(QadMsg.translate(\"Environment variables\", \"FILLETRAD\"))\n self.multi = False\n self.nOperationsToUndo = 0\n \n \n def __del__(self):\n QadCommandClass.__del__(self)\n if self.GetDistClass is not None:\n del self.GetDistClass\n self.entity1.deselectOnLayer()\n self.entity2.deselectOnLayer()\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n # quando si é in fase di richiesta distanza\n if self.step == 3 or self.step == 5 or self.step == 7:\n return self.GetDistClass.getPointMapTool()\n elif (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_fillet_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n #============================================================================\n # setEntityInfo\n #============================================================================\n def setEntityInfo(self, firstObj, layer, featureId, point):\n \"\"\"\n Setta self.entity, self.atSubGeom, self.linearObjectList, self.partAt, self.pointAt\n di primo o del secondo oggetto da raccordare (vedi <firstObj>)\n \"\"\"\n if firstObj:\n e = self.entity1\n l = self.linearObjectList1\n else:\n e = self.entity2\n l = self.linearObjectList2\n \n e.set(layer, featureId)\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, e.getGeometry())\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n if firstObj:\n subGeom, self.atSubGeom1 = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n else:\n subGeom, self.atSubGeom2 = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n \n l.fromPolyline(subGeom.asPolyline())\n e.selectOnLayer(False) # non incrementale \n \n # la funzione ritorna una lista con (<minima distanza al quadrato>,\n # <punto più vicino>\n # <indice della parte più vicina> \n # <\"a sinistra di\">)\n dummy = l.closestPartWithContext(point)\n \n if firstObj: \n self.partAt1 = dummy[2]\n self.pointAt1 = dummy[1]\n else:\n self.partAt2 = dummy[2]\n self.pointAt2 = dummy[1]\n\n return True\n else:\n e.deselectOnLayer()\n return False\n\n\n #============================================================================\n # filletPolyline\n #============================================================================\n def filletPolyline(self): \n layer = self.entity1.layer\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity1.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.getGeometry())\n\n self.linearObjectList1.fillet(self.radius)\n \n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList1.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom1)\n if updGeom is None:\n return False\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n return True\n \n\n #============================================================================\n # fillet\n #============================================================================\n def fillet(self):\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n \n # stessa entità e stessa parte\n if self.entity1.layer.id() == self.entity2.layer.id() and \\\n self.entity1.featureId == self.entity2.featureId and \\\n self.partAt1 == self.partAt2:\n return False\n \n # uso il crs del canvas per lavorare con coordinate piane xy\n epsg = self.plugIn.canvas.mapRenderer().destinationCrs().authid()\n res = qad_utils.getFilletLinearObjectList(self.linearObjectList1, self.partAt1, self.pointAt1, \\\n self.linearObjectList2, self.partAt2, self.pointAt2,\\\n self.filletMode, self.radius, epsg)\n if res is None: # raccordo non possibile\n msg = QadMsg.translate(\"Command_FILLET\", \"\\nFillet with radius <{0}> impossible.\")\n #showMsg\n self.showMsg(msg.format(str(self.radius)))\n return False\n \n filletLinearObjectList = res[0]\n whatToDoPoly1 = res[1]\n whatToDoPoly2 = res[2]\n\n self.plugIn.beginEditCommand(\"Feature edited\", [self.entity1.layer, self.entity2.layer])\n\n if whatToDoPoly1 == 1: # 1=modificare \n f = self.entity1.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity1.layer, f.geometry())\n updSubGeom = QgsGeometry.fromPolyline(filletLinearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom1)\n if updGeom is None:\n self.plugIn.destroyEditCommand()\n return False\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(self.entity1.layer, updGeom))\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity1.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n elif whatToDoPoly1 == 2: # 2=cancellare \n # plugIn, layer, featureId, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, self.entity1.layer, \\\n self.entity1.featureId, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n if whatToDoPoly2 == 1: # 1=modificare\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n f = self.entity2.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity2.layer, f.geometry())\n updSubGeom = QgsGeometry.fromPolyline(filletLinearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom2)\n if updGeom is None:\n self.plugIn.destroyEditCommand()\n return False\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(self.entity2.layer, updGeom))\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity2.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n elif whatToDoPoly2 == 2: # 2=cancellare \n # plugIn, layer, featureId, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, self.entity2.layer, \\\n self.entity2.featureId, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n if whatToDoPoly1 == 0 and whatToDoPoly2 == 0: # 0=niente \n geom = QgsGeometry.fromPolyline(filletLinearObjectList.asPolyline(tolerance2ApproxCurve))\n # trasformo la geometria nel crs del layer\n geom = self.mapToLayerCoordinates(self.entity1.layer, geom)\n\n # plugIn, layer, geom, coordTransform, refresh, check_validity\n if qad_layer.addGeomToLayer(self.plugIn, self.entity1.layer, geom, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n return True\n \n\n #============================================================================\n # waitForFirstEntSel\n #============================================================================\n def waitForFirstEntSel(self): \n self.step = 1\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_fillet_maptool_ModeEnum.ASK_FOR_FIRST_LINESTRING)\n\n # l'opzione Radius viene tradotta in italiano in \"RAggio\" nel contesto \"waitForFirstEntSel\"\n keyWords = QadMsg.translate(\"Command_FILLET\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_FILLET\", \"Polyline\") + \"/\" + \\\n QadMsg.translate(\"Command_FILLET\", \"Radius\", \"waitForFirstEntSel\") + \"/\" + \\\n QadMsg.translate(\"Command_FILLET\", \"Trim\") + \"/\" + \\\n QadMsg.translate(\"Command_FILLET\", \"Multiple\")\n prompt = QadMsg.translate(\"Command_FILLET\", \"Select first object or [{0}]: \").format(keyWords)\n \n englishKeyWords = \"Undo\" + \"/\" + \"Polyline\" + \"/\" + \"Radius\" + \"/\" + \"Trim\" + \"/\" + \"Multiple\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, valore nullo non permesso\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL) \n \n\n #============================================================================\n # WaitForPolyline\n #============================================================================\n def WaitForPolyline(self):\n self.step = 2\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_fillet_maptool_ModeEnum.ASK_FOR_POLYLINE)\n self.getPointMapTool().radius = self.radius \n\n # l'opzione Radius viene tradotta in italiano in \"Raggio\" nel contesto \"WaitForPolyline\"\n keyWords = QadMsg.translate(\"Command_FILLET\", \"Radius\", \"WaitForPolyline\")\n prompt = QadMsg.translate(\"Command_FILLET\", \"Select polyline or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Radius\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, valore nullo non permesso\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL) \n \n \n #============================================================================\n # waitForFilletMode\n #============================================================================\n def waitForFilletMode(self): \n self.step = 4\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_fillet_maptool_ModeEnum.NONE)\n\n keyWords = QadMsg.translate(\"Command_FILLET\", \"Trim-extend\") + \"/\" + \\\n QadMsg.translate(\"Command_FILLET\", \"No trim-extend\")\n\n if self.filletMode == 1:\n default = QadMsg.translate(\"Command_FILLET\", \"Trim-extend\")\n elif self.filletMode == 2:\n default = QadMsg.translate(\"Command_FILLET\", \"No trim-extend\") \n \n prompt = QadMsg.translate(\"Command_FILLET\", \"Specify trim mode [{0}] <{1}>: \").format(keyWords, default)\n\n englishKeyWords = \"Trim-extend\" + \"/\" + \"No trim-extend\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave o un numero reale \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, QadInputTypeEnum.KEYWORDS, default, \\\n keyWords) \n\n\n #============================================================================\n # waitForSecondEntSel\n #============================================================================\n def waitForSecondEntSel(self): \n self.step = 6 \n # imposto il map tool\n self.getPointMapTool().filletMode = self.filletMode\n self.getPointMapTool().radius = self.radius\n self.getPointMapTool().setEntityInfo(self.entity1.layer, self.entity1.featureId, self.linearObjectList1, \\\n self.partAt1, self.pointAt1) \n self.getPointMapTool().setMode(Qad_fillet_maptool_ModeEnum.ASK_FOR_SECOND_LINESTRING)\n\n # l'opzione Radius viene tradotta in italiano in \"RAggio\" nel contesto \"waitForSecondEntSel\"\n keyWords = QadMsg.translate(\"Command_FILLET\", \"Radius\", \"waitForSecondEntSel\") \n prompt = QadMsg.translate(\"Command_FILLET\", \"Select second object or shift-select to apply corner or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Radius\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, valore nullo non permesso\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL) \n\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n if self.step == 0:\n CurrSettingsMsg = QadMsg.translate(\"QAD\", \"\\nCurrent settings: \")\n if self.filletMode == 1:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_FILLET\", \"Mode = Trim-extend\")\n else:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_FILLET\", \"Mode = No trim-extend\")\n \n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_FILLET\", \", Radius = \") + str(self.radius)\n self.showMsg(CurrSettingsMsg) \n \n self.waitForFirstEntSel()\n return False # continua\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE PRIMO OGGETTO\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_FILLET\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\"))\n \n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n elif value == QadMsg.translate(\"Command_FILLET\", \"Polyline\") or value == \"Polyline\":\n self.WaitForPolyline()\n # l'opzione Radius viene tradotta in italiano in \"RAggio\" nel contesto \"waitForFirstEntSel\"\n elif value == QadMsg.translate(\"Command_FILLET\", \"Radius\", \"waitForFirstEntSel\") or value == \"Radius\":\n if self.GetDistClass is not None:\n del self.GetDistClass\n self.GetDistClass = QadGetDistClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_FILLET\", \"Specify fillet radius <{0}>: \")\n self.GetDistClass.msg = prompt.format(str(self.radius))\n self.GetDistClass.dist = self.radius\n self.GetDistClass.inputMode = QadInputModeEnum.NOT_NEGATIVE\n self.step = 3\n self.GetDistClass.run(msgMapTool, msg)\n elif value == QadMsg.translate(\"Command_FILLET\", \"Trim\") or value == \"Trim\":\n self.waitForFilletMode()\n elif value == QadMsg.translate(\"Command_FILLET\", \"Multiple\") or value == \"Multiple\":\n self.multi = True\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n \n elif type(value) == QgsPoint: # se é stato selezionato un punto\n self.entity1.clear()\n self.linearObjectList1.removeAll() \n if self.getPointMapTool().entity.isInitialized():\n if self.setEntityInfo(True, self.getPointMapTool().entity.layer, \\\n self.getPointMapTool().entity.featureId, value) == True:\n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto\n return False\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n # result[0] = feature, result[1] = layer, result[0] = point\n if self.setEntityInfo(True, result[1], result[0].id(), result[2]) == True:\n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto\n return False\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto \n else:\n return True # fine comando\n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UNA POLILINEA (da step = 1)\n elif self.step == 2:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n # l'opzione Radius viene tradotta in italiano in \"Raggio\" nel contesto \"WaitForPolyline\"\n if value == QadMsg.translate(\"Command_FILLET\", \"Radius\", \"WaitForPolyline\") or value == \"Radius\":\n if self.GetDistClass is not None:\n del self.GetDistClass\n self.GetDistClass = QadGetDistClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_FILLET\", \"Specify fillet radius <{0}>: \")\n self.GetDistClass.msg = prompt.format(str(self.radius))\n self.GetDistClass.dist = self.radius\n self.GetDistClass.inputMode = QadInputModeEnum.NOT_NEGATIVE\n self.step = 5\n self.GetDistClass.run(msgMapTool, msg) \n return False\n elif type(value) == QgsPoint: # se é stato selezionato un punto\n self.entity1.clear()\n self.linearObjectList1.removeAll() \n if self.getPointMapTool().entity.isInitialized():\n if self.setEntityInfo(True, self.getPointMapTool().entity.layer, \\\n self.getPointMapTool().entity.featureId, value) == True:\n if self.filletPolyline() == False or self.multi:\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n return False\n else:\n return True\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n\n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n # result[0] = feature, result[1] = layer, result[0] = point\n if self.setEntityInfo(True, result[1], result[0].id(), result[2]) == True:\n if self.filletPolyline() == False or self.multi:\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n return False\n else:\n return True\n else:\n return True # fine comando\n\n self.WaitForPolyline()\n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL RAGGIO DI RACCORDO (da step = 1)\n elif self.step == 3:\n if self.GetDistClass.run(msgMapTool, msg) == True:\n if self.GetDistClass.dist is not None:\n self.radius = self.GetDistClass.dist\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"FILLETRAD\"), self.radius)\n QadVariables.save()\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di distanza \n return False # fine comando\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI TAGLIO (da step = 1)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.filletMode\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_FILLET\", \"Trim-extend\") or value == \"Trim-extend\":\n self.filletMode = 1\n elif value == QadMsg.translate(\"Command_FILLET\", \"No trim-extend\") or value == \"No trim-extend\":\n self.filletMode = 2\n self.plugIn.setFilletMode(self.filletMode)\n \n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL RAGGIO DI RACCORDO (da step = 3)\n elif self.step == 5:\n if self.GetDistClass.run(msgMapTool, msg) == True:\n if self.GetDistClass.dist is not None:\n self.radius = self.GetDistClass.dist\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"FILLETRAD\"), self.radius)\n QadVariables.save()\n self.WaitForPolyline()\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di distanza \n return False # fine comando\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE SECONDO OGGETTO\n elif self.step == 6:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n # l'opzione Radius viene tradotta in italiano in \"RAggio\" nel contesto \"waitForSecondEntSel\"\n if value == QadMsg.translate(\"Command_FILLET\", \"Radius\", \"waitForSecondEntSel\") or value == \"Radius\":\n if self.GetDistClass is not None:\n del self.GetDistClass\n self.GetDistClass = QadGetDistClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_FILLET\", \"Specify fillet radius <{0}>: \")\n self.GetDistClass.msg = prompt.format(str(self.radius))\n self.GetDistClass.dist = self.radius\n self.GetDistClass.inputMode = QadInputModeEnum.NOT_NEGATIVE\n self.step = 7\n self.GetDistClass.run(msgMapTool, msg)\n return False\n \n elif type(value) == QgsPoint: # se é stato selezionato un punto\n self.entity2.clear()\n self.linearObjectList2.removeAll() \n\n if self.getPointMapTool().entity.isInitialized():\n if self.setEntityInfo(False, self.getPointMapTool().entity.layer, \\\n self.getPointMapTool().entity.featureId, value) == True:\n if self.getPointMapTool().shiftKey == True:\n dummyRadius = self.radius\n self.radius = 0\n dummyFilletMode = self.filletMode\n self.filletMode = 1 # modalità di raccordo; 1=Taglia-estendi\n result = self.fillet()\n self.radius = dummyRadius\n self.filletMode = dummyFilletMode\n else:\n result = self.fillet()\n \n if result == False:\n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto \n return False \n \n if self.multi:\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n return False\n else:\n return True\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n\n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n # result[0] = feature, result[1] = layer, result[0] = point\n if self.setEntityInfo(False, result[1], result[0].id(), result[2]) == True:\n if self.fillet() == False:\n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto \n return False \n \n if self.multi:\n self.waitForFirstEntSel() # si appresta ad attendere la selezione del primo oggetto\n return False\n else:\n return True\n else:\n return True # fine comando\n \n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL RAGGIO DI RACCORDO (da step = 6)\n elif self.step == 7:\n if self.GetDistClass.run(msgMapTool, msg) == True:\n if self.GetDistClass.dist is not None:\n self.radius = self.GetDistClass.dist\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"FILLETRAD\"), self.radius)\n QadVariables.save() \n self.waitForSecondEntSel() # si appresta ad attendere la selezione del secondo oggetto\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di distanza \n return False # fine comando"
},
{
"alpha_fraction": 0.5877901315689087,
"alphanum_fraction": 0.5952320694923401,
"avg_line_length": 41.37700653076172,
"blob_id": "722ecd5044fcc002618d9399fe3fe6f56b0614b8",
"content_id": "3b22948d2233a0d82bb3a9237f0e709046c2c715",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15864,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 374,
"path": "/qad_rubberband.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n Classe per gestire rubber band di oggetti geometricamente non omogenei\n \n -------------------\n begin : 2013-12-12\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_entity import *\nfrom qad_variables import *\n\n\n#===============================================================================\n# QadCursorTypeEnum class.\n#===============================================================================\nclass QadCursorTypeEnum():\n BOX = 1 # un quadratino usato per selezionare entità\n CROSS = 2 # una croce usata per selezionare un punto\n\n\n#===============================================================================\n# createCursorRubberBand\n#===============================================================================\n# Classe che gestisce rubber band per disegnare il cursore a croce e il quadratino di pickbox\nclass QadCursorRubberBand():\n def __init__(self, mapCanvas, cursorType):\n self.mapCanvas = mapCanvas\n self.cursorType = cursorType\n \n if cursorType & QadCursorTypeEnum.BOX:\n self.__boxRubberBand = QgsRubberBand(mapCanvas, QGis.Line)\n self.__boxRubberBand.setColor(QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOXCOLOR\"))))\n self.__pickSize = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\"))\n else:\n self.__boxRubberBand = None\n \n if cursorType & QadCursorTypeEnum.CROSS:\n csrColor = QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"CURSORCOLOR\")))\n csrSize = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CURSORSIZE\"))\n self.__crosshairRubberBandSx = QgsRubberBand(mapCanvas, QGis.Line)\n self.__crosshairRubberBandSx.setColor(csrColor)\n self.__crosshairRubberBandDx = QgsRubberBand(mapCanvas, QGis.Line)\n self.__crosshairRubberBandDx.setColor(csrColor)\n self.__crosshairRubberBandDw = QgsRubberBand(mapCanvas, QGis.Line)\n self.__crosshairRubberBandDw.setColor(csrColor)\n self.__crosshairRubberBandUp = QgsRubberBand(mapCanvas, QGis.Line)\n self.__crosshairRubberBandUp.setColor(csrColor)\n screenRect = QApplication.desktop().screenGeometry(mapCanvas)\n self.__halfScreenSize = max(screenRect.height(), screenRect.width())\n if csrSize < 100:\n self.__halfScreenSize = self.__halfScreenSize / 2\n self.__halfScreenSize = self.__halfScreenSize * QadVariables.get(QadMsg.translate(\"Environment variables\", \"CURSORSIZE\")) / 100\n else:\n self.__crosshairRubberBandSx = None\n self.__crosshairRubberBandDx = None\n self.__crosshairRubberBandDw = None\n self.__crosshairRubberBandUp = None\n\n def __del__(self):\n self.removeItems()\n \n def removeItems(self): \n if self.__boxRubberBand is not None:\n self.mapCanvas.scene().removeItem(self.__boxRubberBand)\n del self.__boxRubberBand\n self.__boxRubberBand = None\n \n if self.__crosshairRubberBandSx is not None:\n self.mapCanvas.scene().removeItem(self.__crosshairRubberBandSx)\n self.mapCanvas.scene().removeItem(self.__crosshairRubberBandDx)\n self.mapCanvas.scene().removeItem(self.__crosshairRubberBandDw)\n self.mapCanvas.scene().removeItem(self.__crosshairRubberBandUp)\n del self.__crosshairRubberBandSx\n self.__crosshairRubberBandSx = None\n del self.__crosshairRubberBandDx\n self.__crosshairRubberBandDx = None\n del self.__crosshairRubberBandDw\n self.__crosshairRubberBandDw = None\n del self.__crosshairRubberBandUp\n self.__crosshairRubberBandUp = None\n\n def moveEvent(self, point):\n # point è risultato di toMapCoordinates \n if self.cursorType & QadCursorTypeEnum.BOX:\n pickSize = self.__pickSize * self.mapCanvas.mapUnitsPerPixel()\n\n self.__boxRubberBand.reset(QGis.Line)\n \n point1 = QgsPoint(point.x() - pickSize / 2, point.y() - pickSize / 2)\n self.__boxRubberBand.addPoint(point1, False)\n point1.setX(point1.x() + pickSize)\n self.__boxRubberBand.addPoint(point1, False)\n point1.setY(point1.y() + pickSize)\n self.__boxRubberBand.addPoint(point1, False)\n point1.setX(point1.x() - pickSize)\n self.__boxRubberBand.addPoint(point1, False)\n point1.setY(point1.y() - pickSize)\n self.__boxRubberBand.addPoint(point1, True)\n\n if self.cursorType & QadCursorTypeEnum.CROSS:\n halfScreenSize = self.__halfScreenSize * self.mapCanvas.mapUnitsPerPixel()\n \n self.__crosshairRubberBandSx.reset(QGis.Line)\n self.__crosshairRubberBandDx.reset(QGis.Line)\n self.__crosshairRubberBandDw.reset(QGis.Line)\n self.__crosshairRubberBandUp.reset(QGis.Line)\n \n if self.cursorType & QadCursorTypeEnum.BOX:\n halfPickSize = pickSize / 2\n point1 = QgsPoint(point.x() - halfScreenSize, point.y())\n point2 = QgsPoint(point.x() - halfPickSize, point.y())\n self.__crosshairRubberBandSx.addPoint(point1, False)\n self.__crosshairRubberBandSx.addPoint(point2, True)\n\n point1.setX(point.x() + halfScreenSize)\n point2.setX(point.x() + halfPickSize)\n self.__crosshairRubberBandDx.addPoint(point1, False)\n self.__crosshairRubberBandDx.addPoint(point2, True)\n \n point1.set(point.x(), point.y() - halfScreenSize)\n point2.set(point.x(), point.y() - halfPickSize)\n self.__crosshairRubberBandDw.addPoint(point1, False)\n self.__crosshairRubberBandDw.addPoint(point2, True)\n \n point1.setY(point.y() + halfScreenSize)\n point2.setY(point.y() + halfPickSize) \n self.__crosshairRubberBandUp.addPoint(point1, False)\n self.__crosshairRubberBandUp.addPoint(point2, True) \n else:\n point1 = QgsPoint(point.x() - halfScreenSize, point.y())\n self.__crosshairRubberBandSx.addPoint(point, False)\n self.__crosshairRubberBandSx.addPoint(point1, True)\n \n point1.setX(point.x() + halfScreenSize)\n self.__crosshairRubberBandDx.addPoint(point, False)\n self.__crosshairRubberBandDx.addPoint(point1, True)\n \n point1.set(point.x(), point.y() - halfScreenSize)\n self.__crosshairRubberBandDw.addPoint(point, False)\n self.__crosshairRubberBandDw.addPoint(point1, True)\n \n point1.setY(point.y() + halfScreenSize)\n self.__crosshairRubberBandUp.addPoint(point, False)\n self.__crosshairRubberBandUp.addPoint(point1, True)\n\n def hide(self):\n if self.__boxRubberBand is not None:\n self.__boxRubberBand.hide()\n \n if self.__crosshairRubberBandSx is not None:\n self.__crosshairRubberBandSx.hide()\n self.__crosshairRubberBandDx.hide()\n self.__crosshairRubberBandDw.hide()\n self.__crosshairRubberBandUp.hide()\n \n def show(self):\n if self.__boxRubberBand is not None:\n self.__boxRubberBand.show()\n \n if self.__crosshairRubberBandSx is not None:\n self.__crosshairRubberBandSx.show()\n self.__crosshairRubberBandDx.show()\n self.__crosshairRubberBandDw.show()\n self.__crosshairRubberBandUp.show()\n\n\n#===============================================================================\n# getQGISColorForRubberBand\n#===============================================================================\ndef getQGISColorForRubberBand(geometryType = QGis.Line, alternativeBand = False):\n \"\"\"\n La funzione legge il colore impostato da QGIS per il rubber band di tipo <geometryType>.\n Se <alternativeBand> = True, il rubber band sarà impostato con più trasparenza\n \"\"\"\n settings = QSettings()\n color = QColor(int(settings.value( \"/qgis/digitizing/line_color_red\", 1)), \\\n int(settings.value( \"/qgis/digitizing/line_color_green\", 1)), \\\n int(settings.value( \"/qgis/digitizing/line_color_blue\", 1)))\n alpha = float(int(settings.value( \"/qgis/digitizing/line_color_alpha\", 200)) / 255.0)\n \n if alternativeBand:\n alpha = alpha * float(settings.value( \"/qgis/digitizing/line_color_alpha_scale\", 0.75))\n \n if geometryType == QGis.Polygon:\n color.setAlphaF(alpha)\n\n color.setAlphaF(alpha)\n return color\n\n\n#===============================================================================\n# getColorForWindowSelectionArea\n#===============================================================================\ndef getColorForWindowSelectionArea():\n \"\"\"\n La funzione legge il colore (RGB) dell'area di selezione degli oggetti nel modo finestra.\n \"\"\"\n if QadVariables.get(QadMsg.translate(\"Environment variables\", \"SELECTIONAREA\")) == 0:\n color = QColor()\n color.setAlphaF(0) # trasparente \n else:\n color = QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"WINDOWAREACOLOR\")))\n opacity = QadVariables.get(QadMsg.translate(\"Environment variables\", \"SELECTIONAREAOPACITY\")) # 0 = trasparente [0-100] \n color.setAlphaF(opacity / 100.0) # trasformo da 0-100 a 0-1\n \n return color\n\n\n#===============================================================================\n# getColorForCrossingSelectionArea\n#===============================================================================\ndef getColorForCrossingSelectionArea():\n \"\"\"\n La funzione legge il colore (RGB) dell'area di selezione degli oggetti nel modo intersezione.\n \"\"\"\n if QadVariables.get(QadMsg.translate(\"Environment variables\", \"SELECTIONAREA\")) == 0:\n color = QColor()\n color.setAlphaF(0) # trasparente \n else:\n color = QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"CROSSINGAREACOLOR\")))\n opacity = QadVariables.get(QadMsg.translate(\"Environment variables\", \"SELECTIONAREAOPACITY\")) # 0 = trasparente [0-100] \n color.setAlphaF(opacity / 100.0) # trasformo da 0-100 a 0-1\n \n return color\n\n\n#===============================================================================\n# createRubberBand\n#===============================================================================\ndef createRubberBand(mapCanvas, geometryType = QGis.Line, alternativeBand = False, borderColor = None, fillColor = None):\n \"\"\"\n la funzione crea un rubber band di tipo <geometryType> con le impostazioni di QGIS.\n Se <alternativeBand> = True, il rubber band sarà impostato con più trasparenza e tipolinea punteggiato \n \"\"\"\n settings = QSettings()\n width = int(settings.value( \"/qgis/digitizing/line_width\", 1))\n\n rb = QgsRubberBand(mapCanvas, geometryType)\n \n if alternativeBand:\n rb.setLineStyle(Qt.DotLine)\n\n if borderColor is None:\n borderColor = getQGISColorForRubberBand(geometryType, alternativeBand)\n rb.setBorderColor(borderColor)\n\n if fillColor is None:\n rb.setFillColor(borderColor)\n else:\n rb.setFillColor(fillColor)\n\n rb.setWidth(width)\n \n return rb\n\n\n# Classe che gestisce rubber band di oggetti geometricamente non omogenei\nclass QadRubberBand():\n def __init__(self, mapCanvas, alternativeBand = False, borderColor = None, fillColor = None):\n \"\"\"\n Se <alternativeBand> = True, il rubber band sarà impostato con più trasparenza e tipolinea punteggiato \n \"\"\"\n self.mapCanvas = mapCanvas\n self.__rubberBandPoint = createRubberBand(self.mapCanvas, QGis.Point, alternativeBand, borderColor, fillColor)\n self.__rubberBandLine = createRubberBand(self.mapCanvas, QGis.Line, alternativeBand, borderColor, fillColor)\n self.__rubberBandPolygon = createRubberBand(self.mapCanvas, QGis.Polygon, alternativeBand, borderColor, fillColor)\n\n def __del__(self):\n self.hide()\n \n self.mapCanvas.scene().removeItem(self.__rubberBandPoint)\n del self.__rubberBandPoint\n \n self.mapCanvas.scene().removeItem(self.__rubberBandLine)\n del self.__rubberBandLine\n \n self.mapCanvas.scene().removeItem(self.__rubberBandPolygon)\n del self.__rubberBandPolygon \n \n def hide(self):\n self.__rubberBandPoint.hide()\n self.__rubberBandLine.hide()\n self.__rubberBandPolygon.hide() \n\n def show(self):\n self.__rubberBandPoint.show()\n self.__rubberBandLine.show()\n self.__rubberBandPolygon.show()\n \n def addGeometry(self, geom, layer):\n # uso la geometria del layer per risolvere il caso ambiguo in cui\n # si vuole inserire una linea chiusa in un layer poligono \n geomType = layer.geometryType()\n #geomType = geom.type()\n if geomType == QGis.Point:\n self.__rubberBandPoint.addGeometry(geom, layer)\n elif geomType == QGis.Line:\n self.__rubberBandLine.addGeometry(geom, layer)\n elif geomType == QGis.Polygon:\n self.__rubberBandPolygon.addGeometry(geom, layer)\n \n def addGeometries(self, geoms, layer):\n for g in geoms:\n self.addGeometry(g, layer)\n \n \n def setLine(self, points):\n self.__rubberBandLine.reset(QGis.Line)\n tot = len(points) - 1\n i = 0\n while i <= tot:\n if i < tot:\n self.__rubberBandLine.addPoint(points[i], False)\n else: # ultimo punto\n self.__rubberBandLine.addPoint(points[i], True)\n i = i + 1\n\n def setPolygon(self, points):\n self.__rubberBandPolygon.reset(QGis.Polygon)\n tot = len(points) - 1\n i = 0\n while i <= tot:\n if i < tot:\n self.__rubberBandPolygon.addPoint(points[i], False)\n else: # ultimo punto\n self.__rubberBandPolygon.addPoint(points[i], True)\n i = i + 1\n\n def addLinePoint(self, point, doUpdate = True, geometryIndex = 0):\n self.__rubberBandLine.addPoint(point, doUpdate, geometryIndex)\n\n def addPolygonPoint(self, point, doUpdate = True, geometryIndex = 0):\n self.__rubberBandPolygon.addPoint(point, doUpdate, geometryIndex)\n\n def reset(self):\n self.__rubberBandPoint.reset(QGis.Point)\n self.__rubberBandLine.reset(QGis.Line)\n self.__rubberBandPolygon.reset(QGis.Polygon) \n \n def setLineStyle(self, penStyle): \n self.__rubberBandLine.setLineStyle(penStyle)\n self.__rubberBandPolygon.setLineStyle(penStyle)\n \n def setBorderColor(self, color):\n self.__rubberBandPoint.setBorderColor(color)\n self.__rubberBandLine.setBorderColor(color)\n self.__rubberBandPolygon.setBorderColor(color)\n \n def setFillColor(self, color):\n self.__rubberBandPolygon.setFillColor(color)\n \n"
},
{
"alpha_fraction": 0.6461856365203857,
"alphanum_fraction": 0.650789201259613,
"avg_line_length": 43.53556442260742,
"blob_id": "506dde149f85101e11667f1e03cf81f922cc2873",
"content_id": "0003e97732f9ccee551448c105ea13c3ca4348f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10644,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 239,
"path": "/qad_dsettings_dlg.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando DSETTINGS per impostazione disegno\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\nfrom qgis.utils import *\n\n\nimport qad_dsettings_ui\n\n\nfrom qad_variables import *\nfrom qad_snapper import *\nfrom qad_msg import QadMsg, qadShowPluginHelp\nimport qad_utils\n\n\n#######################################################################################\n# Classe che gestisce l'interfaccia grafica del comando DSETTINGS\nclass QadDSETTINGSDialog(QDialog, QObject, qad_dsettings_ui.Ui_DSettings_Dialog):\n def __init__(self, plugIn):\n self.plugIn = plugIn\n self.iface = self.plugIn.iface.mainWindow()\n QDialog.__init__(self, self.iface)\n self.setupUi(self)\n \n # Inizializzazione del TAB che riguarda gli SNAP ad oggetto\n self.init_osnap_tab()\n \n # Inizializzazione del TAB che riguarda il puntamento polare\n self.init_polar_tab()\n \n self.tabWidget.setCurrentIndex(0)\n \n\n def init_osnap_tab(self):\n # Inizializzazione del TAB che riguarda gli SNAP ad oggetto\n \n # Memorizzo il valore dell'OSMODE per determinare gli osnap impostati\n OsMode = QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\"))\n self.checkBox_CENP.setChecked(OsMode & QadSnapTypeEnum.CEN)\n self.checkBox_ENDP.setChecked(OsMode & QadSnapTypeEnum.END)\n self.checkBox_END_PLINE.setChecked(OsMode & QadSnapTypeEnum.END_PLINE)\n self.checkBox_EXTP.setChecked(OsMode & QadSnapTypeEnum.EXT)\n self.checkBox_INTP.setChecked(OsMode & QadSnapTypeEnum.INT)\n self.checkBox_MIDP.setChecked(OsMode & QadSnapTypeEnum.MID)\n self.checkBox_NODP.setChecked(OsMode & QadSnapTypeEnum.NOD)\n self.checkBox_QUADP.setChecked(OsMode & QadSnapTypeEnum.QUA)\n #self.checkBox_INSP.setChecked(OsMode & QadSnapTypeEnum.INS)\n #self.checkBox_INTAPP.setChecked(OsMode & QadSnapTypeEnum.APP)\n self.checkBox_NEARP.setChecked(OsMode & QadSnapTypeEnum.NEA)\n self.checkBox_PERP.setChecked(OsMode & QadSnapTypeEnum.PER)\n self.checkBox_PARALP.setChecked(OsMode & QadSnapTypeEnum.PAR)\n self.checkBox_PROGRESP.setChecked(OsMode & QadSnapTypeEnum.PR)\n self.checkBox_TANP.setChecked(OsMode & QadSnapTypeEnum.TAN)\n self.checkBox_EXT_INT.setChecked(OsMode & QadSnapTypeEnum.EXT_INT)\n self.checkBox_TANP.setChecked(OsMode & QadSnapTypeEnum.TAN)\n self.checkBox_IsOsnapON.setChecked(not(OsMode & QadSnapTypeEnum.DISABLE))\n\n ProgrDistance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSPROGRDISTANCE\"))\n stringA = str(ProgrDistance)\n self.lineEdit_ProgrDistance.setText(stringA)\n self.lineEdit_ProgrDistance.setValidator(QDoubleValidator(self.lineEdit_ProgrDistance))\n self.lineEdit_ProgrDistance.installEventFilter(self)\n \n\n def init_polar_tab(self):\n # Inizializzazione del TAB che riguarda il puntamento polare\n UserAngle = QadVariables.get(QadMsg.translate(\"Environment variables\", \"POLARANG\"))\n angoliDef = [\"90\", \"45\", \"30\", \"22.5\", \"18\", \"15\", \"10\", \"5\"]\n self.comboBox_increment_angle.addItems(angoliDef)\n stringA = str(UserAngle)\n self.comboBox_increment_angle.lineEdit().setText(stringA)\n self.comboBox_increment_angle.installEventFilter(self)\n \n AutoSnap = QadVariables.get(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"))\n self.checkBox_PolarPickPoint.setChecked(AutoSnap & 8)\n\n\n def eventFilter(self, obj, event):\n if event is not None:\n if event.type() == QEvent.FocusOut:\n if obj == self.lineEdit_ProgrDistance:\n return not self.lineEdit_ProgrDistance_Validation()\n elif obj == self.comboBox_increment_angle:\n return not self.comboBox_increment_angle_Validation() \n\n # standard event processing\n return QObject.eventFilter(self, obj, event);\n\n def ButtonSelectALL_Pressed(self):\n self.checkBox_CENP.setChecked(True)\n self.checkBox_ENDP.setChecked(True)\n self.checkBox_END_PLINE.setChecked(True)\n self.checkBox_EXTP.setChecked(True)\n self.checkBox_INTP.setChecked(True)\n self.checkBox_MIDP.setChecked(True)\n self.checkBox_NODP.setChecked(True)\n self.checkBox_QUADP.setChecked(True)\n #self.checkBox_INSP.setChecked(True)\n #self.checkBox_INTAPP.setChecked(True)\n self.checkBox_NEARP.setChecked(True)\n self.checkBox_PARALP.setChecked(True)\n self.checkBox_PERP.setChecked(True)\n self.checkBox_PROGRESP.setChecked(True)\n self.checkBox_TANP.setChecked(True)\n self.checkBox_EXT_INT.setChecked(True)\n return True\n \n\n def ButtonDeselectALL_Pressed(self):\n self.checkBox_CENP.setChecked(False)\n self.checkBox_ENDP.setChecked(False)\n self.checkBox_END_PLINE.setChecked(False)\n self.checkBox_EXTP.setChecked(False)\n self.checkBox_INTP.setChecked(False)\n self.checkBox_MIDP.setChecked(False)\n self.checkBox_NODP.setChecked(False)\n self.checkBox_QUADP.setChecked(False)\n #self.checkBox_INSP.setChecked(False)\n #self.checkBox_INTAPP.setChecked(False)\n self.checkBox_NEARP.setChecked(False)\n self.checkBox_PARALP.setChecked(False)\n self.checkBox_PERP.setChecked(False)\n self.checkBox_PROGRESP.setChecked(False)\n self.checkBox_TANP.setChecked(False)\n self.checkBox_EXT_INT.setChecked(False)\n return True\n \n def ButtonBOX_Accepted(self):\n newOSMODE = 0\n if self.checkBox_CENP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.CEN\n if self.checkBox_ENDP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.END\n if self.checkBox_END_PLINE.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.END_PLINE\n if self.checkBox_EXTP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.EXT\n if self.checkBox_INTP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.INT\n if self.checkBox_MIDP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.MID\n if self.checkBox_NODP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.NOD\n if self.checkBox_QUADP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.QUA\n #if self.checkBox_INSP.checkState() == Qt.Checked:\n # newOSMODE = newOSMODE | QadSnapTypeEnum.INS\n #if self.checkBox_INTAPP.checkState() == Qt.Checked:\n # newOSMODE = newOSMODE | QadSnapTypeEnum.APP\n if self.checkBox_NEARP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.NEA\n if self.checkBox_PARALP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.PAR\n if self.checkBox_PERP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.PER\n if self.checkBox_PROGRESP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.PR\n if self.checkBox_TANP.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.TAN\n if self.checkBox_EXT_INT.checkState() == Qt.Checked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.EXT_INT\n if self.checkBox_IsOsnapON.checkState() == Qt.Unchecked:\n newOSMODE = newOSMODE | QadSnapTypeEnum.DISABLE\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"OSMODE\"), newOSMODE)\n \n AutoSnap = QadVariables.get(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\")) \n if self.checkBox_PolarPickPoint.checkState() == Qt.Checked:\n AutoSnap = AutoSnap | 8\n elif AutoSnap & 8: \n AutoSnap = AutoSnap - 8\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"), AutoSnap)\n \n # Memorizzo il valore di PolarANG\n SUserAngle = self.comboBox_increment_angle.currentText()\n UserAngle = qad_utils.str2float(SUserAngle)\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"POLARANG\"), UserAngle)\n \n SProgrDist = self.lineEdit_ProgrDistance.text()\n ProgrDist = qad_utils.str2float(SProgrDist)\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"OSPROGRDISTANCE\"), ProgrDist)\n\n QadVariables.save()\n\n \n self.close()\n return True\n\n\n def lineEdit_ProgrDistance_Validation(self):\n string = self.lineEdit_ProgrDistance.text()\n if qad_utils.str2float(string) is None or qad_utils.str2float(string) == 0:\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Invalid progressive distance object snap: enter a number not zero.\")\n QMessageBox.critical(self, \"QAD\", msg)\n self.lineEdit_ProgrDistance.setFocus()\n self.lineEdit_ProgrDistance.selectAll()\n return False\n return True\n \n \n def comboBox_increment_angle_Validation(self):\n string = self.comboBox_increment_angle.lineEdit().text()\n if qad_utils.str2float(string) is None or qad_utils.str2float(string) <= 0 or qad_utils.str2float(string) >= 360:\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Invalid increment angle: enter a number greater than zero and less than 360 degree.\")\n QMessageBox.critical(self, \"QAD\", msg) \n self.comboBox_increment_angle.lineEdit().setFocus()\n self.comboBox_increment_angle.lineEdit().selectAll()\n return False\n return True\n\n\n def ButtonHELP_Pressed(self):\n qadShowPluginHelp(QadMsg.translate(\"Help\", \"DSETTINGS\"))\n"
},
{
"alpha_fraction": 0.5625474452972412,
"alphanum_fraction": 0.5652040839195251,
"avg_line_length": 46.239044189453125,
"blob_id": "862c8cda2bfb9569a11f8d99915120c3ae118e13",
"content_id": "628e791f0eb414bbad6cb080ec8d273ab671b983",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 94916,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 2008,
"path": "/qad_pedit_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando PEDIT per editare una polilinea o un poligono esistente\n \n -------------------\n begin : 2014-01-13\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_snapper import *\nfrom qad_pedit_maptool import *\nfrom qad_ssget_cmd import QadSSGetClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nimport qad_utils\nimport qad_layer\nfrom qad_variables import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_dim import QadDimStyles\nimport qad_grip\n\n\n# Classe che gestisce il comando PEDIT\nclass QadPEDITCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadPEDITCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"PEDIT\")\n \n def getEnglishName(self):\n return \"PEDIT\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runPEDITCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/pedit.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_PEDIT\", \"Modifies existing polylines or polygon.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.SSGetClass = QadSSGetClass(plugIn)\n self.SSGetClass.onlyEditableLayers = True\n self.SSGetClass.checkPointLayer = False # scarto i punto\n self.SSGetClass.checkLineLayer = True\n self.SSGetClass.checkDimLayers = False # scarto le quote\n \n self.entitySet = QadEntitySet()\n self.entity = QadEntity()\n self.atSubGeom = None\n self.linearObjectList = qad_utils.QadLinearObjectList()\n self.joinToleranceDist = plugIn.joinToleranceDist\n self.joinMode = plugIn.joinMode\n\n self.editVertexMode = None\n self.nOperationsToUndo = 0\n \n self.firstPt = QgsPoint()\n self.vertexAt = 0\n self.secondVertexAt = 0\n self.after = True\n self.snapPointsDisplayManager = QadSnapPointsDisplayManager(self.plugIn.canvas)\n self.snapPointsDisplayManager.setIconSize(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSSIZE\")))\n self.snapPointsDisplayManager.setColor(QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSCOLOR\"))))\n \n def __del__(self):\n QadCommandClass.__del__(self)\n del self.SSGetClass\n self.entity.deselectOnLayer()\n self.entitySet.deselectOnLayer()\n del self.snapPointsDisplayManager\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 2: # quando si é in fase di selezione entità\n return self.SSGetClass.getPointMapTool() \n else:\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_pedit_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n #============================================================================\n # setEntityInfo\n #============================================================================\n def setEntityInfo(self, layer, featureId, point):\n \"\"\"\n Setta self.entity, self.atSubGeom, self.linearObjectList\n \"\"\" \n self.entity.set(layer, featureId)\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, self.atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n if self.linearObjectList.getCircle() is not None:\n self.entity.deselectOnLayer()\n return False\n else:\n self.entity.selectOnLayer(False) # non incrementale\n return True\n else:\n self.entity.deselectOnLayer()\n return False\n\n\n #============================================================================\n # getNextVertex\n #============================================================================\n def getNextVertex(self, vertexAt):\n \"\"\"\n Ritorna la posizione del vertice successivo rispetto vertexAt\n \"\"\"\n tot = self.linearObjectList.qty()\n if vertexAt == tot - 1: # se penultimo punto\n return 0 if self.linearObjectList.isClosed() else vertexAt + 1\n elif vertexAt < tot: # se non é ultimo punto\n return vertexAt + 1\n else:\n return vertexAt\n\n\n #============================================================================\n # getPrevVertex\n #============================================================================\n def getPrevVertex(self, vertexAt):\n \"\"\"\n Ritorna la posizione del vertice precedente rispetto vertexAt\n \"\"\"\n if vertexAt == 0: # se primo punto\n if self.linearObjectList.isClosed():\n return self.linearObjectList.qty() - 1\n else:\n return vertexAt\n else:\n return vertexAt - 1\n\n\n #============================================================================\n # displayVertexMarker\n #============================================================================\n def displayVertexMarker(self, vertexAt):\n if vertexAt == self.linearObjectList.qty():\n pt = self.linearObjectList.getLinearObjectAt(-1).getEndPt()\n else:\n pt = self.linearObjectList.getLinearObjectAt(vertexAt).getStartPt()\n \n # visualizzo il punto di snap\n snapPoint = dict()\n snapPoint[QadSnapTypeEnum.END] = [pt]\n self.snapPointsDisplayManager.show(snapPoint)\n \n\n #============================================================================\n # setClose\n #============================================================================\n def setClose(self, toClose):\n if self.entity.isInitialized(): # selezionato solo un oggetto\n layer = self.entity.layer\n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n geom = f.geometry()\n \n self.linearObjectList.setClose(toClose)\n pts = self.linearObjectList.asPolyline(tolerance2ApproxCurve)\n \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n \n if layer.geometryType() == QGis.Line:\n updGeom = qad_utils.setSubGeom(geom, QgsGeometry.fromPolyline(pts), self.atSubGeom)\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else: # layer di tipo poligono\n if toClose == False: # apri\n # aggiungo le linee nei layer temporanei di QAD\n LineTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Line)\n self.plugIn.addLayerToLastEditCommand(\"Feature edited\", LineTempLayer)\n \n lineGeoms = [QgsGeometry.fromPolyline(pts)]\n \n # trasformo la geometria in quella dei layer temporanei\n # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh\n if qad_layer.addGeometriesToQADTempLayers(self.plugIn, None, lineGeoms, None, \\\n None, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n updGeom = qad_utils.delSubGeom(geom, atSubGeom)\n\n if updGeom is None or updGeom.isGeosEmpty(): # da cancellare\n # plugIn, layer, feature id, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, layer, f.id(), False) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n editedFeature = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n editedFeature.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, editedFeature, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else: \n self.plugIn.beginEditCommand(\"Feature edited\", self.entitySet.getLayerList())\n for layerEntitySet in self.entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n \n updObjects = []\n for featureId in layerEntitySet.featureIds:\n f = layerEntitySet.getFeature(featureId)\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n updGeom = qad_utils.closeQgsGeometry(self.mapToLayerCoordinates(layer, f.geometry()), toClose, tolerance2ApproxCurve)\n if updGeom is not None:\n updFeature = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n updFeature.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n updObjects.append(updFeature) \n \n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(self.plugIn, layer, updObjects, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n\n #============================================================================\n # reverse\n #============================================================================\n def reverse(self):\n if self.entity.isInitialized(): # selezionato solo un oggetto\n layer = self.entity.layer\n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n\n self.linearObjectList.reverse()\n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is not None:\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n self.plugIn.beginEditCommand(\"Feature edited\", self.entitySet.getLayerList())\n\n for layerEntitySet in self.entitySet.layerEntitySetList:\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n \n updObjects = []\n for featureId in layerEntitySet.featureIds:\n f = layerEntitySet.getFeature(featureId)\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layerEntitySet.layer, f.geometry()) \n updGeom = qad_utils.reverseQgsGeometry(geom, tolerance2ApproxCurve)\n if updGeom is not None:\n updFeature = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n updFeature.setGeometry(self.mapToLayerCoordinates(layerEntitySet.layer, updGeom))\n updObjects.append(updFeature) \n \n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(self.plugIn, layerEntitySet.layer, updObjects, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n\n #============================================================================\n # join\n #============================================================================\n def join(self):\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n epsg = self.plugIn.canvas.currentLayer().crs().authid()\n # creo un layer temporaneo in memoria con campo numerico per \n # contenere la posizione dell'entità originale nella lista newIdFeatureList\n vectorLayer = QgsVectorLayer(\"LineString?crs=%s&index=yes\" % epsg, \"QAD_SelfJoinLines\", \"memory\")\n \n provider = vectorLayer.dataProvider()\n provider.addAttributes([QgsField('index', QVariant.Int, 'Int')])\n vectorLayer.updateFields()\n\n if vectorLayer.startEditing() == False:\n return\n\n # inserisco nel layer i vari oggetti lineari (WKBLineString)\n layerList = []\n newIdFeatureList = [] # lista ((newId - layer - feature) ...)\n i = 0\n \n if self.entity.isInitialized(): # selezionato solo un oggetto\n self.entitySet.removeEntity(self.entity) # elimino dal gruppo l'entità da unire\n \n # aggiungo l'entità a cui unirsi\n layer = self.entity.layer\n \n if layer.geometryType() != QGis.Line:\n return\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n \n f = self.entity.getFeature()\n if f.geometry().wkbType() != QGis.WKBLineString:\n return\n newFeature = QgsFeature()\n newFeature.initAttributes(1)\n newFeature.setAttribute(0, 0)\n \n geom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n newFeature.setGeometry(geom)\n i = i + 1\n \n if vectorLayer.addFeature(newFeature) == False:\n vectorLayer.destroyEditCommand()\n return\n newIdFeatureList.append([newFeature.id(), layer, f])\n \n \n for layerEntitySet in self.entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n \n if layer.geometryType() != QGis.Line:\n continue\n \n for f in layerEntitySet.getFeatureCollection():\n if f.geometry().wkbType() != QGis.WKBLineString:\n continue\n newFeature = QgsFeature()\n newFeature.initAttributes(1)\n newFeature.setAttribute(0, i)\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layerEntitySet.layer, f.geometry())\n newFeature.setGeometry(geom)\n i = i + 1\n \n if vectorLayer.addFeature(newFeature) == False:\n vectorLayer.destroyEditCommand()\n return\n newIdFeatureList.append([newFeature.id(), layer, f])\n \n vectorLayer.endEditCommand();\n vectorLayer.updateExtents()\n \n if provider.capabilities() & QgsVectorDataProvider.CreateSpatialIndex:\n provider.createSpatialIndex()\n\n deleteFeatures = []\n if self.entity.isInitialized(): # selezionato solo un oggetto\n featureIdToJoin = newIdFeatureList[0][0]\n # featureIdToJoin, vectorLayer, tolerance2ApproxCurve, toleranceDist, mode \n deleteFeatures.extend(qad_utils.joinFeatureInVectorLayer(featureIdToJoin, vectorLayer, \\\n tolerance2ApproxCurve, \\\n self.joinToleranceDist, self.joinMode))\n else: \n i = 0 \n tot = len(newIdFeatureList)\n while i < tot:\n featureIdToJoin = newIdFeatureList[i][0]\n # featureIdToJoin, vectorLayer, tolerance2ApproxCurve, toleranceDist, mode \n deleteFeatures.extend(qad_utils.joinFeatureInVectorLayer(featureIdToJoin, vectorLayer, \\\n tolerance2ApproxCurve, \\\n self.joinToleranceDist, self.joinMode))\n i = i + 1\n \n self.plugIn.beginEditCommand(\"Feature edited\", self.entitySet.getLayerList())\n\n if self.entity.isInitialized(): # selezionato solo un oggetto\n newFeature = qad_utils.getFeatureById(vectorLayer, newIdFeatureList[0][0])\n if newFeature is None:\n self.plugIn.destroyEditCommand()\n return\n \n layer = newIdFeatureList[0][1]\n f = newIdFeatureList[0][2]\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity.layer, f.geometry())\n\n updGeom = qad_utils.setSubGeom(geom, newFeature.geometry(), self.atSubGeom)\n\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(self.entity.layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else: \n # aggiorno la geometria delle features rimaste nel layer temporaneo\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for newFeature in vectorLayer.getFeatures(qad_utils.getFeatureRequest([], True, None, False)):\n layer = newIdFeatureList[newFeature['index']][1]\n f = newIdFeatureList[newFeature['index']][2]\n f.setGeometry(newFeature.geometry())\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n # cancello le features rimosse dal layer temporaneo\n for newFeature in deleteFeatures:\n layer = newIdFeatureList[newFeature['index']][1]\n f = newIdFeatureList[newFeature['index']][2] \n # plugIn, layer, feature id, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, layer, f.id(), False) == False:\n self.plugIn.destroyEditCommand()\n return \n \n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # curve\n #============================================================================\n def curve(self, toCurve):\n if self.entity.isInitialized(): # selezionato solo un oggetto\n layer = self.entity.layer\n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.geometry())\n\n self.linearObjectList.curve(toCurve)\n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is not None:\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n self.plugIn.beginEditCommand(\"Feature edited\", self.entitySet.getLayerList())\n\n for layerEntitySet in self.entitySet.layerEntitySetList:\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n \n updObjects = []\n for featureId in layerEntitySet.featureIds:\n f = layerEntitySet.getFeature(featureId)\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layerEntitySet.layer, f.geometry())\n \n updGeom = qad_utils.curveQgsGeometry(geom, toCurve, tolerance2ApproxCurve)\n if updGeom is not None:\n updFeature = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n updFeature.setGeometry(self.mapToLayerCoordinates(layerEntitySet.layer, updGeom))\n updObjects.append(updFeature) \n \n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(self.plugIn, layerEntitySet.layer, updObjects, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # insertVertexAt\n #============================================================================\n def insertVertexAt(self, pt): \n layer = self.entity.layer\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.geometry())\n\n if self.after: # dopo\n if self.vertexAt == self.linearObjectList.qty() and self.linearObjectList.isClosed():\n self.linearObjectList.insertPoint(0, pt)\n else:\n self.linearObjectList.insertPoint(self.vertexAt, pt)\n else: # prima\n if self.vertexAt == 0 and self.linearObjectList.isClosed():\n self.linearObjectList.insertPoint(self.linearObjectList.qty() - 1, pt)\n else:\n self.linearObjectList.insertPoint(self.vertexAt - 1, pt)\n \n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # moveVertexAt\n #============================================================================\n def moveVertexAt(self, pt): \n layer = self.entity.layer\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.geometry())\n\n self.linearObjectList.movePoint(self.vertexAt, pt)\n \n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # straightenFromVertexAtToSecondVertexAt\n #============================================================================\n def straightenFromVertexAtToSecondVertexAt(self):\n if self.vertexAt == self.secondVertexAt:\n return\n \n layer = self.entity.layer\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.geometry())\n\n if self.vertexAt < self.secondVertexAt:\n firstPt = self.linearObjectList.getPointAtVertex(self.vertexAt)\n secondPt = self.linearObjectList.getPointAtVertex(self.secondVertexAt)\n for i in xrange(self.vertexAt, self.secondVertexAt, 1):\n self.linearObjectList.remove(self.vertexAt)\n self.linearObjectList.insert(self.vertexAt, [firstPt, secondPt])\n elif self.vertexAt > self.secondVertexAt:\n if self.linearObjectList.isClosed():\n firstPt = self.linearObjectList.getPointAtVertex(self.vertexAt)\n secondPt = self.linearObjectList.getPointAtVertex(self.secondVertexAt)\n for i in xrange(self.vertexAt, self.linearObjectList.qty(), 1):\n self.linearObjectList.remove(self.vertexAt)\n for i in xrange(0, self.secondVertexAt, 1):\n self.linearObjectList.remove(0)\n \n self.linearObjectList.insert(self.vertexAt, [firstPt, secondPt])\n else:\n firstPt = self.linearObjectList.getPointAtVertex(self.secondVertexAt)\n secondPt = self.linearObjectList.getPointAtVertex(self.vertexAt)\n for i in xrange(self.secondVertexAt, self.vertexAt, 1):\n self.linearObjectList.remove(self.secondVertexAt)\n self.linearObjectList.insert(self.secondVertexAt, [firstPt, secondPt])\n \n updSubGeom = QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # breakFromVertexAtToSecondVertexAt\n #============================================================================\n def breakFromVertexAtToSecondVertexAt(self):\n layer = self.entity.layer\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n f = self.entity.getFeature()\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, f.geometry())\n\n firstPt = self.linearObjectList.getPointAtVertex(self.vertexAt)\n secondPt = self.linearObjectList.getPointAtVertex(self.secondVertexAt)\n\n result = qad_utils.breakQgsGeometry(QgsGeometry.fromPolyline(self.linearObjectList.asPolyline(tolerance2ApproxCurve)), \\\n firstPt, secondPt, \\\n tolerance2ApproxCurve) \n if result is None:\n return\n \n line1 = result[0]\n line2 = result[1]\n atSubGeom = result[2]\n \n updGeom = qad_utils.setSubGeom(geom, line1, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n\n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, self.entity.layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n if line2 is not None:\n brokenFeature2 = QgsFeature(f) \n brokenFeature2.setGeometry(line2)\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, brokenFeature2, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return \n\n self.linearObjectList.fromPolyline(line1.asPolyline())\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # waitForEntsel\n #============================================================================\n def waitForEntsel(self): \n # imposto il map tool\n self.step = 1\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_ENTITY_SEL)\n \n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Last\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Multiple\")\n prompt = QadMsg.translate(\"Command_PEDIT\", \"Select polyline or [{0}]: \").format(QadMsg.translate(\"Command_PEDIT\", \"Multiple\"))\n \n englishKeyWords = \"Last\" + \"/\" + \"Multiple\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, valore nullo non permesso\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL) \n \n\n #============================================================================\n # WaitForMainMenu\n #============================================================================\n def WaitForMainMenu(self):\n # verifico se ci sono layer di tipo linea\n line = False\n if self.entity.isInitialized(): # selezionato solo un oggetto\n if self.entity.layer.geometryType() == QGis.Line:\n line = True\n else: \n layerList = self.entitySet.getLayerList()\n for layer in layerList:\n if layer.geometryType() == QGis.Line:\n line = True\n break\n\n if line == True: # se ci sono dei layer linea\n if self.entity.isInitialized(): # selezionato solo un oggetto\n if self.linearObjectList.isClosed(): # se é chiusa\n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Open\") + \"/\"\n englishKeyWords = \"Open\"\n else:\n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Close\") + \"/\"\n englishKeyWords = \"Close\"\n else: # selezionati più oggetti\n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Close\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Open\") + \"/\"\n englishKeyWords = \"Close\" + \"/\" + \"Open\"\n \n keyWords = keyWords + QadMsg.translate(\"Command_PEDIT\", \"Join\") + \"/\"\n englishKeyWords = englishKeyWords + \"Join\"\n else: # se non ci sono dei layer linea\n keyWords = \"\"\n msg = \"\"\n englishKeyWords = \"\"\n\n if self.entity.isInitialized(): # selezionato solo un oggetto\n keyWords = keyWords + QadMsg.translate(\"Command_PEDIT\", \"Edit vertex\") + \"/\"\n englishKeyWords = englishKeyWords + \"Edit vertex\"\n \n keyWords = keyWords + QadMsg.translate(\"Command_PEDIT\", \"Fit\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Decurve\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Reverse\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Undo\") \n englishKeyWords = englishKeyWords + \"Fit\" + \"/\" + \"Decurve\" + \"/\" + \"Reverse\" + \"/\" + \"Undo\"\n prompt = QadMsg.translate(\"Command_PEDIT\", \"Enter an option [{0}]: \").format(keyWords)\n \n self.step = 3\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.NONE)\n\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n return False\n \n\n #============================================================================\n # WaitForJoin\n #============================================================================\n def WaitForJoin(self):\n CurrSettingsMsg = QadMsg.translate(\"QAD\", \"\\nCurrent settings: \")\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_PEDIT\", \"Join type = \")\n if self.joinMode == 1:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_PEDIT\", \"extends the segments\")\n elif self.joinMode == 2:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_PEDIT\", \"adds segments\")\n elif self.joinMode == 3:\n CurrSettingsMsg = CurrSettingsMsg + QadMsg.translate(\"Command_PEDIT\", \"extends and adds segments\")\n \n self.showMsg(CurrSettingsMsg)\n self.waitForDistance() \n \n\n #============================================================================\n # waitForDistance\n #============================================================================\n def waitForDistance(self): \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_FIRST_TOLERANCE_PT)\n\n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Join type\") \n prompt = QadMsg.translate(\"Command_PEDIT\", \"Specify gap tolerance or [{0}] <{1}>: \").format(keyWords, str(self.joinToleranceDist))\n\n englishKeyWords = \"Join type\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave o un numero reale \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT | QadInputTypeEnum.KEYWORDS, \\\n self.joinToleranceDist, \\\n keyWords, \\\n QadInputModeEnum.NOT_NEGATIVE) \n self.step = 4 \n \n \n #============================================================================\n # waitForJoinType\n #============================================================================\n def waitForJoinType(self): \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.NONE)\n\n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Extend\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Add\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Both\")\n englishKeyWords = \"Extend\" + \"/\" + \"Add\" + \"/\" + \"Both\"\n if self.joinMode == 1:\n default = QadMsg.translate(\"Command_PEDIT\", \"Extend\")\n elif self.joinMode == 2:\n default = QadMsg.translate(\"Command_PEDIT\", \"Add\")\n elif self.joinMode == 3:\n default = QadMsg.translate(\"Command_PEDIT\", \"Both\")\n prompt = QadMsg.translate(\"Command_PEDIT\", \"Specify join type [{0}] <{1}>: \").format(keyWords, default)\n\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave o un numero reale \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, QadInputTypeEnum.KEYWORDS, default, \\\n keyWords) \n self.step = 6\n\n\n #============================================================================\n # WaitForVertexEditingMenu\n #============================================================================\n def WaitForVertexEditingMenu(self):\n self.getPointMapTool().setLinearObjectList(self.linearObjectList, self.entity.layer)\n \n self.displayVertexMarker(self.vertexAt)\n \n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Next\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Previous\")\n englishKeyWords = \"Next\" + \"/\" + \"Previous\"\n \n if self.entity.layer.geometryType() == QGis.Line:\n keyWords = keyWords + \"/\" + QadMsg.translate(\"Command_PEDIT\", \"Break\")\n englishKeyWords = englishKeyWords + \"/\" + \"Break\"\n\n keyWords = keyWords + \"/\" + QadMsg.translate(\"Command_PEDIT\", \"Insert\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"INsert before\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Move\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Straighten\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"eXit\")\n englishKeyWords = englishKeyWords + \"/\" + \"Insert\" + \"/\" + \"INsert before\" + \"/\" + \\\n \"Move\" + \"/\" + \"Straighten\" + \"/\" + \"eXit\"\n\n prompt = QadMsg.translate(\"Command_PEDIT\", \"Enter a vertex editing option [{0}] <{1}>: \").format(keyWords, self.default)\n \n self.step = 8\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_VERTEX)\n\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n self.default, \\\n keyWords, QadInputModeEnum.NONE)\n return False\n\n\n #============================================================================\n # waitForNewVertex\n #============================================================================\n def waitForNewVertex(self): \n # imposto il map tool\n self.getPointMapTool().setVertexAt(self.vertexAt, self.after)\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_NEW_VERTEX)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PEDIT\", \"Specify the position of the new vertex: \"))\n self.step = 9 \n\n\n #============================================================================\n # waitForMoveVertex\n #============================================================================\n def waitForMoveVertex(self): \n # imposto il map tool\n self.getPointMapTool().setVertexAt(self.vertexAt) \n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_MOVE_VERTEX)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PEDIT\", \"Specify the new vertex position: \"))\n self.step = 10 \n\n\n #============================================================================\n # WaitForVertexEditingMenu\n #============================================================================\n def WaitForSecondVertex(self):\n self.displayVertexMarker(self.secondVertexAt)\n \n keyWords = QadMsg.translate(\"Command_PEDIT\", \"Next\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Previous\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"Go\") + \"/\" + \\\n QadMsg.translate(\"Command_PEDIT\", \"eXit\")\n englishKeyWords = \"Next\" + \"/\" + \"Previous\" + \"/\" + \"Go\" + \"/\" + \"eXit\"\n prompt = QadMsg.translate(\"Command_PEDIT\", \"Enter a selection option for the second vertex [{0}] <{1}>: \").format(keyWords, self.default1)\n \n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_VERTEX)\n \n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n self.default1, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 11\n \n return False\n\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n if self.step == 0: \n self.waitForEntsel()\n return False # continua\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PEDIT\", \"Multiple\") or value == \"Multiple\":\n self.SSGetClass.checkPolygonLayer = True \n self.SSGetClass.run(msgMapTool, msg)\n self.step = 2\n return False \n elif type(value) == QgsPoint: # se é stato selezionato un punto\n self.entity.clear()\n self.linearObjectList.removeAll() \n\n if self.getPointMapTool().entity.isInitialized():\n if self.setEntityInfo(self.getPointMapTool().entity.layer, \\\n self.getPointMapTool().entity.featureId, value) == True:\n self.WaitForMainMenu()\n return False\n else: \n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n # result[0] = feature, result[1] = layer, result[0] = point\n if self.setEntityInfo(result[1], result[0].id(), result[2]) == True:\n self.WaitForMainMenu()\n return False \n else:\n return True # fine comando\n \n # si appresta ad attendere la selezione degli oggetti\n self.waitForEntsel()\n return False \n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN GRUPPO OGGETTI\n elif self.step == 2:\n if self.SSGetClass.run(msgMapTool, msg) == True: \n self.entitySet.set(self.SSGetClass.entitySet)\n \n if self.entitySet.count() == 0:\n self.waitForEntsel()\n else:\n self.WaitForMainMenu()\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL MENU PRINCIPALE (da step = 1 e 2)\n elif self.step == 3: # dopo aver atteso una opzione si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n self.WaitForMainMenu()\n return False \n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value == QadMsg.translate(\"Command_PEDIT\", \"Close\") or value == \"Close\":\n self.setClose(True) \n elif value == QadMsg.translate(\"Command_PEDIT\", \"Open\") or value == \"Open\":\n self.setClose(False) \n elif value == QadMsg.translate(\"Command_PEDIT\", \"Edit vertex\") or value == \"Edit vertex\":\n self.vertexAt = 0\n self.default = QadMsg.translate(\"Command_PEDIT\", \"Next\")\n self.WaitForVertexEditingMenu()\n return False\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Join\") or value == \"Join\":\n if self.entity.isInitialized(): # selezionato solo un oggetto\n self.SSGetClass.checkPolygonLayer = False # scarto i poligoni\n self.SSGetClass.run(msgMapTool, msg)\n self.step = 7\n return False \n else:\n self.WaitForJoin()\n return False\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Fit\") or value == \"Fit\":\n self.curve(True)\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Decurve\") or value == \"Decurve\":\n self.curve(False)\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Reverse\") or value == \"Reverse\":\n self.reverse()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1 \n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n \n if self.entity.isInitialized(): # selezionato solo un oggetto\n if self.atSubGeom is not None:\n # ricarico la geometria ripristinata dall'annulla\n geom = self.entity.getGeometry()\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom = qad_utils.getSubGeomAt(geom, self.atSubGeom)\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n subGeom = self.layerToMapCoordinates(self.entity.layer, subGeom)\n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n else:\n return True # fine comando\n \n self.entity.deselectOnLayer()\n self.entitySet.deselectOnLayer()\n self.WaitForMainMenu()\n return False \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA DISTANZA DI APPROSSIMAZIONE (da step = 3)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.joinToleranceDist\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PEDIT\", \"Join type\") or value == \"Join type\":\n # si appresta ad attendere il tipo di unione\n self.waitForJoinType()\n elif type(value) == QgsPoint: # se é stato inserito il primo punto per il calcolo della distanza\n # imposto il map tool\n self.firstPt.set(value.x(), value.y())\n self.getPointMapTool().firstPt = self.firstPt\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.FIRST_TOLERANCE_PT_KNOWN_ASK_FOR_SECOND_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PEDIT\", \"Specify second point: \"))\n self.step = 5\n elif type(value) == float:\n self.joinToleranceDist = value\n self.plugIn.setJoinToleranceDist(self.joinToleranceDist)\n self.join()\n self.entity.deselectOnLayer()\n self.entitySet.deselectOnLayer()\n self.WaitForMainMenu()\n \n return False \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER DISTANZA DI APPROSSIMAZIONE (da step = 4)\n elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value == self.firstPt:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe value must be positive and not zero.\"))\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PEDIT\", \"Specify second point: \"))\n return False\n \n self.joinToleranceDist = qad_utils.getDistance(self.firstPt, value)\n self.plugIn.setJoinToleranceDist(self.joinToleranceDist)\n self.join()\n self.entity.deselectOnLayer()\n self.entitySet.deselectOnLayer()\n self.WaitForMainMenu()\n\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA MODALITA' DI UNIONE (da step = 4)\n elif self.step == 6: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PEDIT\", \"Extend\") or value == \"Extend\":\n self.joinMode = 1\n self.plugIn.setJoinMode(self.joinMode)\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Add\") or value == \"Add\":\n self.joinMode = 2\n self.plugIn.setJoinMode(self.joinMode)\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Both\") or value == \"Both\":\n self.joinMode = 3\n self.plugIn.setJoinMode(self.joinMode)\n \n self.WaitForJoin()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN GRUPPO OGGETTI DA UNIRE (da step = 3)\n elif self.step == 7:\n if self.SSGetClass.run(msgMapTool, msg) == True: \n self.entitySet.set(self.SSGetClass.entitySet)\n \n if self.entitySet.count() > 0:\n self.joinToleranceDist = 0.0\n self.join()\n\n self.entity.deselectOnLayer()\n self.entitySet.deselectOnLayer()\n self.WaitForMainMenu()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DI OPZIONI EDITAZIONE VERTICI (da step = 3)\n elif self.step == 8: # dopo aver atteso un punto o una opzione si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.default\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto o l'opzione arriva come parametro della funzione\n value = msg\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PEDIT\", \"Next\") or value == \"Next\":\n self.default = value\n self.vertexAt = self.getNextVertex(self.vertexAt) \n self.WaitForVertexEditingMenu()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Previous\") or value == \"Previous\":\n self.default = value\n self.vertexAt = self.getPrevVertex(self.vertexAt)\n self.WaitForVertexEditingMenu()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Break\") or value == \"Break\":\n self.editVertexMode = QadMsg.translate(\"Command_PEDIT\", \"Break\")\n self.secondVertexAt = self.vertexAt\n self.default1 = QadMsg.translate(\"Command_PEDIT\", \"Next\")\n self.WaitForSecondVertex()\n return False\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Insert\") or value == \"Insert\":\n self.after = True\n self.waitForNewVertex() \n elif value == QadMsg.translate(\"Command_PEDIT\", \"INsert before\") or value == \"INsert before\":\n self.after = False\n self.waitForNewVertex()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Move\") or value == \"Move\":\n self.waitForMoveVertex()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Straighten\") or value == \"Straighten\":\n self.editVertexMode = QadMsg.translate(\"Command_PEDIT\", \"Straighten\")\n self.secondVertexAt = self.vertexAt\n self.default1 = QadMsg.translate(\"Command_PEDIT\", \"Next\")\n self.WaitForSecondVertex()\n return False\n elif value == QadMsg.translate(\"Command_PEDIT\", \"eXit\") or value == \"eXit\":\n self.WaitForMainMenu()\n elif type(value) == QgsPoint: # se é stato inserito un punto\n # cerco il vertice più vicino al punto\n self.vertexAt = self.linearObjectList.closestVertexWithContext(value)\n self.WaitForVertexEditingMenu()\n \n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL NUOVO VERTICE DA INSERIRE (da step = 8)\n elif self.step == 9: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n self.insertVertexAt(value)\n self.vertexAt = self.vertexAt + (1 if self.after else -1)\n self.WaitForVertexEditingMenu()\n\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA POSIZIONE DEL VERTICE DA SPOSTARE (da step = 8)\n elif self.step == 10: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n self.moveVertexAt(value)\n self.WaitForVertexEditingMenu()\n\n return False\n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL SECONDO VERTICE (da step = 8)\n elif self.step == 11: # dopo aver atteso un punto o una opzione si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.default\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto o l'opzione arriva come parametro della funzione\n value = msg\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PEDIT\", \"Next\") or value == \"Next\":\n self.default1 = value\n self.secondVertexAt = self.getNextVertex(self.secondVertexAt) \n self.WaitForSecondVertex()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Previous\") or value == \"Previous\":\n self.default1 = value\n self.secondVertexAt = self.getPrevVertex(self.secondVertexAt)\n self.WaitForSecondVertex()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"Go\") or value == \"Go\":\n pt = self.linearObjectList.getPointAtVertex(self.vertexAt)\n \n if self.editVertexMode == QadMsg.translate(\"Command_PEDIT\", \"Break\"):\n self.breakFromVertexAtToSecondVertexAt()\n elif self.editVertexMode == QadMsg.translate(\"Command_PEDIT\", \"Straighten\"):\n self.straightenFromVertexAtToSecondVertexAt()\n \n self.vertexAt = self.linearObjectList.getVertexPosAtPt(pt)\n self.WaitForVertexEditingMenu()\n elif value == QadMsg.translate(\"Command_PEDIT\", \"eXit\") or value == \"eXit\":\n self.WaitForVertexEditingMenu()\n elif type(value) == QgsPoint: # se é stato inserito il primo punto\n # cerco il vertice più vicino al punto \n self.secondVertexAt = self.linearObjectList.closestVertexWithContext(value)\n self.WaitForSecondVertex()\n \n return False \n\n\n#============================================================================\n# Classe che gestisce il comando per inserire/cancellare un vertice per i grip\n#============================================================================\nclass QadGRIPINSERTREMOVEVERTEXCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadGRIPINSERTREMOVEVERTEXCommandClass(self.plugIn)\n\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.entity = None\n self.skipToNextGripCommand = False\n self.copyEntities = False\n self.basePt = QgsPoint()\n self.nOperationsToUndo = 0\n\n self.after = True\n self.insert_mode = True\n self.vertexAt = 0\n self.firstPt = QgsPoint()\n self.linearObjectList = qad_utils.QadLinearObjectList()\n\n def __del__(self):\n QadCommandClass.__del__(self)\n\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_pedit_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n def setInsertVertexAfter_Mode(self):\n self.after = True\n self.insert_mode = True\n \n def setInsertVertexBefore_Mode(self):\n self.after = False\n self.insert_mode = True\n\n def setRemoveVertex_mode(self):\n self.insert_mode = False\n \n \n #============================================================================\n # setSelectedEntityGripPoints\n #============================================================================\n def setSelectedEntityGripPoints(self, entitySetGripPoints):\n # lista delle entityGripPoint con dei grip point selezionati\n # setta la prima entità con un grip selezionato\n self.entity = None\n for entityGripPoints in entitySetGripPoints.entityGripPoints:\n for gripPoint in entityGripPoints.gripPoints:\n # grip point selezionato\n if gripPoint.getStatus() == qad_grip.QadGripStatusEnum.SELECTED:\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entityGripPoints.entity.isDimensionComponent():\n return False\n if entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.LINESTRING:\n return False\n \n # setta: self.entity, self.linearObjectList, self.atSubGeom\n self.entity = entityGripPoints.entity\n\n self.firstPt.set(gripPoint.getPoint().x(), gripPoint.getPoint().y())\n \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity.layer, self.entity.getGeometry())\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(self.firstPt, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, self.atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n # setto il n. di vertice\n self.vertexAt = gripPoint.nVertex\n \n self.getPointMapTool().setLinearObjectList(self.linearObjectList, self.entity.layer)\n return True\n\n return False\n\n\n #============================================================================\n # insertVertexAt\n #============================================================================\n def insertVertexAt(self, pt):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n \n # faccio una copia locale\n linearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n if self.after: # dopo\n if self.vertexAt == linearObjectList.qty() and linearObjectList.isClosed():\n linearObjectList.insertPoint(0, pt)\n else:\n linearObjectList.insertPoint(self.vertexAt, pt)\n else: # prima\n if self.vertexAt == 0 and linearObjectList.isClosed():\n linearObjectList.insertPoint(self.linearObjectList.qty() - 1, pt)\n else:\n linearObjectList.insertPoint(self.vertexAt - 1, pt)\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n \n updSubGeom = QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, f, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # removeVertexAt\n #============================================================================\n def removeVertexAt(self):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n\n # faccio una copia locale\n linearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n \n prevLinearObject, nextLinearObject = linearObjectList.getPrevNextLinearObjectsAtVertex(self.vertexAt)\n if prevLinearObject:\n firstPt = prevLinearObject.getStartPt()\n linearObjectList.remove(self.vertexAt - 1) # rimuovo la parte precedente\n \n if nextLinearObject:\n if prevLinearObject:\n # modifico la parte successiva\n secondPt = nextLinearObject.getEndPt()\n nextLinearObject.setSegment(firstPt, secondPt)\n else:\n linearObjectList.remove(self.vertexAt) # rimuovo la parte\n \n \n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n\n updSubGeom = QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n\n\n #============================================================================\n # waitForBasePt\n #============================================================================\n def waitForBasePt(self):\n self.step = 2 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_BASE_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_GRIP\", \"Specify base point: \"))\n\n\n #============================================================================\n # waitForNewVertex\n #============================================================================\n def waitForNewVertex(self):\n # imposto il map tool\n self.getPointMapTool().setVertexAt(self.vertexAt, self.after)\n if self.basePt is not None:\n self.getPointMapTool().firstPt = self.basePt\n self.getPointMapTool().setMode(Qad_pedit_maptool_ModeEnum.ASK_FOR_NEW_VERTEX)\n\n keyWords = QadMsg.translate(\"Command_GRIP\", \"Base point\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Copy\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"eXit\")\n prompt = QadMsg.translate(\"Command_GRIPINSERTREMOVEVERTEX\", \"Specify the position of the new vertex or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Base point\" + \"/\" + \"Copy\" + \"/\" + \"Undo\" + \"/\" \"eXit\"\n keyWords += \"_\" + englishKeyWords\n\n # si appresta ad attendere un punto o enter o una parola chiave\n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 1\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI\n if self.step == 0: # inizio del comando\n if self.entity is None: # non ci sono oggetti da stirare\n return True\n\n if self.insert_mode:\n self.showMsg(QadMsg.translate(\"Command_GRIPINSERTREMOVEVERTEX\", \"\\n** ADD VERTEX **\\n\"))\n # si appresta ad attendere un nuovo punto\n self.waitForNewVertex()\n else:\n self.showMsg(QadMsg.translate(\"Command_GRIPINSERTREMOVEVERTEX\", \"\\n** REMOVE VERTEX **\\n\"))\n self.removeVertexAt()\n return True\n \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL NUOVO VERTICE DA INSERIRE (da step = 1)\n elif self.step == 1:\n ctrlKey = False\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n ctrlKey = self.getPointMapTool().ctrlKey\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_GRIP\", \"Base point\") or value == \"Base point\":\n # si appresta ad attendere il punto base\n self.waitForBasePt()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Copy\") or value == \"Copy\":\n # Copia entità lasciando inalterate le originali\n self.copyEntities = True \n # si appresta ad attendere un nuovo punto\n self.waitForNewVertex()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n # si appresta ad attendere un nuovo punto\n self.waitForNewVertex()\n elif value == QadMsg.translate(\"Command_GRIP\", \"eXit\") or value == \"eXit\":\n return True # fine comando\n elif type(value) == QgsPoint:\n if ctrlKey:\n self.copyEntities = True\n \n offsetX = value.x() - self.basePt.x()\n offsetY = value.y() - self.basePt.y()\n value.set(self.firstPt.x() + offsetX, self.firstPt.y() + offsetY)\n self.insertVertexAt(value)\n\n if self.copyEntities == False:\n return True\n # si appresta ad attendere un nuovo punto\n self.waitForNewVertex()\n else:\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n pass # opzione di default\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint: # se é stato inserito il punto base\n self.basePt.set(value.x(), value.y())\n # imposto il map tool\n self.getPointMapTool().basePt = self.basePt\n self.getPointMapTool().firstPt = self.basePt\n \n # si appresta ad attendere un nuovo punto\n self.waitForNewVertex()\n\n return False\n \n\n#============================================================================\n# Classe che gestisce il comando per convertire in arco o in linea un segmento per i grip\n#============================================================================\nclass QadGRIPARCLINECONVERTCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadGRIPARCLINECONVERTCommandClass(self.plugIn)\n\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.entity = None\n self.skipToNextGripCommand = False\n self.copyEntities = False\n self.nOperationsToUndo = 0\n self.basePt = QgsPoint()\n\n self.lineToArc = True\n self.partAt = 0\n self.linearObjectList = qad_utils.QadLinearObjectList() # in map coordinate\n\n def __del__(self):\n QadCommandClass.__del__(self)\n\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_gripLineToArcConvert_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n def setLineToArcConvert_Mode(self):\n self.lineToArc = True\n \n def setArcToLineConvert_Mode(self):\n self.lineToArc = False\n\n\n #============================================================================\n # setSelectedEntityGripPoints\n #============================================================================\n def setSelectedEntityGripPoints(self, entitySetGripPoints):\n # lista delle entityGripPoint con dei grip point selezionati\n # setta la prima entità con un grip selezionato\n self.entity = None\n for entityGripPoints in entitySetGripPoints.entityGripPoints:\n for gripPoint in entityGripPoints.gripPoints:\n # grip point selezionato\n if gripPoint.getStatus() == qad_grip.QadGripStatusEnum.SELECTED and \\\n (gripPoint.gripType == qad_grip.QadGripPointTypeEnum.LINE_MID_POINT or \\\n gripPoint.gripType == qad_grip.QadGripPointTypeEnum.ARC_MID_POINT):\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entityGripPoints.entity.isDimensionComponent():\n return False\n if entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.LINESTRING and \\\n entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.ARC:\n return False\n \n # setta: self.entity, self.linearObjectList, self.atSubGeom\n self.entity = entityGripPoints.entity\n\n firstPt = QgsPoint(gripPoint.getPoint())\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity.layer, self.entity.getGeometry())\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(firstPt, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, self.atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n # setto il n. della parte\n self.partAt = gripPoint.nVertex\n \n self.getPointMapTool().setLinearObjectList(self.linearObjectList, self.entity.layer, self.partAt)\n \n return True\n\n return False\n\n\n #============================================================================\n # convertLineToArc\n #============================================================================\n def convertLineToArc(self, pt):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n \n # faccio una copia locale\n linearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n linearObject = linearObjectList.getLinearObjectAt(self.partAt)\n if linearObject.isArc(): # se è già arco\n return False\n \n startPt = linearObject.getStartPt()\n endPt = linearObject.getEndPt()\n arc = QadArc()\n if arc.fromStartSecondEndPts(startPt, pt, endPt) == False:\n return\n if qad_utils.ptNear(startPt, arc.getStartPt()):\n linearObject.setArc(arc, False) # arco non inverso\n else:\n linearObject.setArc(arc, True) # arco inverso\n \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n\n updSubGeom = QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, f, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # convertArcToLine\n #============================================================================\n def convertArcToLine(self):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n \n # faccio una copia locale\n linearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n linearObject = linearObjectList.getLinearObjectAt(self.partAt)\n if linearObject.isSegment(): # se è già segmento retto\n return False\n \n linearObject.setSegment(linearObject.getStartPt(), linearObject.getEndPt())\n \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n \n updSubGeom = QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, f, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n\n\n #============================================================================\n # waitForConvertToArc\n #============================================================================\n def waitForConvertToArc(self):\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_gripLineToArcConvert_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_SECOND_PT)\n\n keyWords = QadMsg.translate(\"Command_GRIP\", \"Copy\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"eXit\")\n prompt = QadMsg.translate(\"Command_GRIPARCLINECONVERT\", \"Specify the arc middle point or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Copy\" + \"/\" + \"Undo\" + \"/\" \"eXit\"\n keyWords += \"_\" + englishKeyWords\n\n # si appresta ad attendere un punto o enter o una parola chiave\n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 1\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI\n if self.step == 0: # inizio del comando\n if self.entity is None: # non ci sono oggetti da stirare\n return True\n\n if self.lineToArc:\n self.showMsg(QadMsg.translate(\"Command_GRIPINSERTREMOVEVERTEX\", \"\\n** CONVERT TO ARC **\\n\"))\n # si appresta ad attendere un punto per definire l'arco\n self.waitForConvertToArc()\n else:\n self.showMsg(QadMsg.translate(\"Command_GRIPINSERTREMOVEVERTEX\", \"\\n** CONVERT TO LINE **\\n\"))\n self.convertArcToLine()\n return True\n \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL NUOVO PUNTO PER DEFINIRE UN ARCO (da step = 1)\n elif self.step == 1:\n ctrlKey = False\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n ctrlKey = self.getPointMapTool().ctrlKey\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_GRIP\", \"Copy\") or value == \"Copy\":\n # Copia entità lasciando inalterate le originali\n self.copyEntities = True \n # si appresta ad attendere un punto per definire l'arco\n self.waitForConvertToArc()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n # si appresta ad attendere un punto per definire l'arco\n self.waitForConvertToArc()\n elif value == QadMsg.translate(\"Command_GRIP\", \"eXit\") or value == \"eXit\":\n return True # fine comando\n elif type(value) == QgsPoint:\n if ctrlKey:\n self.copyEntities = True\n \n self.convertLineToArc(value)\n\n if self.copyEntities == False:\n return True\n # si appresta ad attendere un punto per definire l'arco\n self.waitForConvertToArc()\n else:\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n\n return False\n"
},
{
"alpha_fraction": 0.5680149793624878,
"alphanum_fraction": 0.5719355940818787,
"avg_line_length": 52.564857482910156,
"blob_id": "013af34c96b40967a4abc36b49c13e8c3d73ea2e",
"content_id": "352c5a65b9e235b480ef42b0540fab1f903bd08e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 78119,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 1457,
"path": "/qad_pline_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando PLINE per disegnare una polilinea\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_entsel_cmd import QadEntSelClass\nfrom qad_getpoint import *\nfrom qad_arc_maptool import *\nfrom qad_arc import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nimport qad_utils\nimport qad_layer\nfrom qad_rubberband import createRubberBand\n\n\n# Classe che gestisce il comando PLINE\nclass QadPLINECommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadPLINECommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"PLINE\")\n\n def getEnglishName(self):\n return \"PLINE\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runPLINECommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/pline.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_PLINE\", \"Creates a polyline by many methods.\\n\\nA polyline is a single object that is composed of line,\\nand arc segments.\")\n \n def __init__(self, plugIn, asToolForMPolygon = False):\n QadCommandClass.__init__(self, plugIn)\n self.vertices = []\n self.realVerticesIndexes = [] # posizioni in vertices dei vertici reali \n # (l'arco è approssimato a tanti segmenti)\n self.firstVertex = True\n \n self.asToolForMPolygon = asToolForMPolygon\n if self.asToolForMPolygon:\n self.rubberBand = createRubberBand(self.plugIn.canvas, QGis.Polygon, True)\n else:\n self.rubberBand = createRubberBand(self.plugIn.canvas, QGis.Line)\n \n self.ArcPointMapTool = None\n self.mode = \"LINE\"\n self.EntSelClass = None\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.virtualCmd = False\n\n\n def __del__(self):\n QadCommandClass.__del__(self)\n self.rubberBand.hide()\n self.plugIn.canvas.scene().removeItem(self.rubberBand)\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 3: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n else:\n if self.mode == \"LINE\":\n return QadCommandClass.getPointMapTool(self, drawMode)\n elif self.mode == \"ARC\":\n return self.getArcPointMapTool()\n\n \n def setRubberBandColor(self, rubberBandBorderColor, rubberBandFillColor):\n if rubberBandBorderColor is not None:\n self.rubberBand.setBorderColor(rubberBandBorderColor)\n if rubberBandFillColor is not None:\n self.rubberBand.setFillColor(rubberBandFillColor)\n\n\n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_PLINE\", \"Select the object in the trace end point: \")\n # scarto la selezione di punti\n self.EntSelClass.checkPointLayer = False\n self.EntSelClass.checkLineLayer = True\n self.EntSelClass.checkPolygonLayer = True\n self.EntSelClass.onlyEditableLayers = False \n \n self.EntSelClass.getPointMapTool().setSnapType(QadSnapTypeEnum.END)\n self.EntSelClass.run(msgMapTool, msg)\n \n def getArcPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.ArcPointMapTool is None:\n self.ArcPointMapTool = Qad_arc_maptool(self.plugIn)\n return self.ArcPointMapTool\n else:\n return None\n\n def addRealVertex(self, point):\n self.realVerticesIndexes.append(len(self.vertices))\n self.vertices.append(point) \n self.addPointToRubberBand(point) \n self.plugIn.setLastPoint(self.vertices[-1]) \n self.plugIn.setLastSegmentAng(self.getLastSegmentAng())\n\n def delLastRealVertex(self):\n tot = len(self.realVerticesIndexes)\n if tot > 0:\n i = self.realVerticesIndexes[tot - 1]\n if tot > 1:\n iEnd = self.realVerticesIndexes[tot - 2]\n else:\n iEnd = -1\n \n del self.realVerticesIndexes[-1] # cancello ultimo vertice reale\n while i > iEnd:\n del self.vertices[-1] # cancello ultimo vertice\n self.removeLastPointToRubberBand()\n i = i - 1\n\n self.plugIn.setLastPoint(self.vertices[-1]) \n self.plugIn.setLastSegmentAng(self.getLastSegmentAng())\n\n def addArcVertices(self, points, inverse):\n tot = len(points)\n if inverse == False:\n i = 1 # salto il primo punto dell'arco che coincide con l'ultimo punto precedente\n while i < tot:\n self.vertices.append(points[i]) \n self.addPointToRubberBand(points[i])\n i = i + 1\n else:\n i = tot - 2 # salto l'ultimo punto dell'arco che coincide con l'ultimo punto precedente\n while i >= 0:\n self.vertices.append(points[i]) \n self.addPointToRubberBand(points[i])\n i = i - 1\n \n self.realVerticesIndexes.append(len(self.vertices) - 1)\n self.plugIn.setLastPoint(self.vertices[-1]) \n self.plugIn.setLastSegmentAng(self.getLastSegmentAng())\n\n\n def getLastSegmentAng(self):\n if len(self.vertices) < 2:\n result = self.plugIn.lastSegmentAng\n else:\n result = None\n lastVertex = self.vertices[-1] # ultimo vertice\n # verifico se ci sono archi\n arc = None\n arcList = QadArcList()\n if arcList.fromPoints(self.vertices) > 0:\n info = arcList.arcAt(len(self.vertices) - 1)\n if info is not None:\n arc = info[0]\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(lastVertex, arc.getStartPt()):\n result = arc.getTanDirectionOnStartPt() + math.pi\n else:\n result = arc.getTanDirectionOnEndPt()\n \n if result is None:\n secondLastVertex = self.vertices[-2] # penultimo vertice\n result = qad_utils.getAngleBy2Pts(secondLastVertex, lastVertex)\n \n return result\n\n #============================================================================\n # WaitForArcMenu\n #============================================================================\n def WaitForArcMenu(self):\n # l'opzione CEnter viene tradotta in italiano in \"CEntro\" nel contesto \"WaitForArcMenu\"\n # l'opzione Undo viene tradotta in italiano in \"ANNulla\" nel contesto \"WaitForArcMenu\"\n keyWords = QadMsg.translate(\"Command_PLINE\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"CEnter\", \"WaitForArcMenu\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Close\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Direction\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Line\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Radius\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Second point\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Undo\", \"WaitForArcMenu\")\n englishKeyWords = \"Angle\" + \"/\" + \"CEnter\" + \"/\" + \"Close\" + \"/\" + \\\n \"Direction\" + \"/\" + \"Line\" + \"/\" + \"Radius\" + \"/\" + \\\n \"Second point\" + \"/\" + \"Undo\"\n \n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n\n self.arcStartPt = self.vertices[-1] # ultimo vertice\n self.arcTanOnStartPt = self.getLastSegmentAng()\n \n # Il segmento di arco é tangente al precedente segmento della polilinea\n # uso il map tool per l'arco\n self.mode = \"ARC\"\n self.getPointMapTool().arcStartPt = self.arcStartPt\n self.getPointMapTool().arcTanOnStartPt = self.arcTanOnStartPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_TAN_KNOWN_ASK_FOR_END_PT)\n \n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 101\n return\n\n #============================================================================\n # WaitForLineMenu\n #============================================================================\n def WaitForLineMenu(self):\n # l'opzione Undo viene tradotta in italiano in \"ANnulla\" nel contesto \"WaitForLineMenu\"\n if self.firstVertex:\n keyWords = QadMsg.translate(\"Command_PLINE\", \"Arc\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Length\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Undo\", \"WaitForLineMenu\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Trace\")\n englishKeyWords = \"Arc\" + \"/\" + \"Length\"+ \"/\" + \"Undo\" + \"/\" + \"Trace\"\n else: \n keyWords = QadMsg.translate(\"Command_PLINE\", \"Arc\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Close\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Length\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Undo\", \"WaitForLineMenu\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Trace\")\n englishKeyWords = \"Arc\" + \"/\" + \"Close\" + \"/\" + \"Length\" + \"/\" + \"Undo\"+ \"/\" + \"Trace\"\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify next point or [{0}]: \").format(keyWords)\n \n self.step = 1 # MENU PRINCIPLE\n\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n\n #============================================================================\n # addPointToRubberBand\n #============================================================================\n def addPointToRubberBand(self, point, doUpdate = True):\n numberOfVertices = self.rubberBand.numberOfVertices()\n \n if numberOfVertices == 2:\n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n adjustedPoint = qad_utils.getAdjustedRubberBandVertex(self.rubberBand.getPoint(0, 0), point) \n self.rubberBand.addPoint(adjustedPoint, doUpdate)\n else:\n self.rubberBand.addPoint(point, doUpdate)\n \n \n #============================================================================\n # removeLastPointToRubberBand\n #============================================================================\n def removeLastPointToRubberBand(self):\n self.rubberBand.removeLastPoint()\n \n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n currLayer, errMsg = qad_layer.getCurrLayerEditable(self.plugIn.canvas, QGis.Line)\n if currLayer is None:\n self.showErr(errMsg)\n return True # fine comando\n \n # RICHIESTA PRIMO PUNTO \n if self.step == 0: # inizio del comando\n # imposto la linea elastica\n self.getPointMapTool(QadGetPointDrawModeEnum.ELASTIC_LINE)\n # si appresta ad attendere un punto o enter\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify start point: \"), \\\n QadInputTypeEnum.POINT2D, None, \"\", QadInputModeEnum.NONE)\n self.step = 1\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO OPPURE MENU PRINCIPALE\n elif self.step == 1: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if value is None:\n if self.firstVertex:\n if self.plugIn.lastPoint is not None:\n value = self.plugIn.lastPoint\n else:\n return True # fine comando\n else:\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n return True # fine comando\n \n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PLINE\", \"Arc\") or value == \"Arc\":\n self.WaitForArcMenu()\n return False\n elif value == QadMsg.translate(\"Command_PLINE\", \"Length\") or value == \"Length\":\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n # \"Specificare lunghezza della linea: \" \n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify line length: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 2\n return False\n # l'opzione Undo viene tradotta in italiano in \"ANnulla\" nel contesto \"WaitForLineMenu\"\n elif value == QadMsg.translate(\"Command_PLINE\", \"Undo\", \"WaitForLineMenu\") or value == \"Undo\":\n if len(self.vertices) >= 2:\n self.delLastRealVertex() # cancello ultimo vertice reale\n self.getPointMapTool().clear()\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().setStartPoint(self.vertices[-1])\n elif value == QadMsg.translate(\"Command_PLINE\", \"Close\") or value == \"Close\":\n newPt = self.vertices[0]\n self.addRealVertex(newPt) # aggiungo un nuovo vertice reale\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n return True # fine comando\n elif value == QadMsg.translate(\"Command_PLINE\", \"Trace\") or value == \"Trace\":\n self.step = 3\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n\n elif type(value) == QgsPoint:\n self.addRealVertex(value) # aggiungo un nuovo vertice reale\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().setStartPoint(value)\n \n self.WaitForLineMenu() \n if self.firstVertex:\n self.firstVertex = False\n \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Lunghezza\" (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n dist = qad_utils.getDistance(self.vertices[-1], value) \n else:\n dist = value\n\n newPt = qad_utils.getPolarPointByPtAngle(self.vertices[-1], self.getLastSegmentAng(), dist)\n self.addRealVertex(newPt) # aggiungo un nuovo vertice reale\n\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().setStartPoint(newPt)\n \n self.WaitForLineMenu() \n \n self.step = 1 # torno al MENU PRINCIPLE\n \n return False\n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Selezionare l'oggetto nel punto finale di ricalco: \" (da step = 1)\n elif self.step == 3:\n entSelected = False\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized() and self.EntSelClass.point is not None:\n entSelected = True\n layer = self.EntSelClass.entity.layer\n geom = self.EntSelClass.entity.getGeometry()\n ptEnd = qad_utils.closestVertexPtWithContext(self.mapToLayerCoordinates(layer, self.EntSelClass.point), \\\n geom)\n transformedPt1 = self.mapToLayerCoordinates(layer, self.vertices[-1])\n # leggo la parte di linea tra transformedPt1 e transformedPt2\n points = qad_utils.getLinePart(geom, transformedPt1, ptEnd) \n if points is not None:\n mapRenderer = self.EntSelClass.getPointMapTool().canvas.mapRenderer()\n # converto i punti della linea in map coordinates\n transformedPoints = []\n for point in points:\n transformedPoints.append(mapRenderer.layerToMapCoordinates(layer, point))\n \n self.addArcVertices(transformedPoints, False) # aggiungo i punti in ordine\n\n del self.EntSelClass\n self.EntSelClass = None\n\n self.WaitForLineMenu()\n if entSelected:\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità \n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().setStartPoint(self.vertices[-1])\n \n return False\n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco o [Angolo/CEntro/CHiudi/Direzione/LInea/Raggio/Secondo punto/ANNulla]: \" (da step = 1)\n elif self.step == 101: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n return True # fine comando\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PLINE\", \"Angle\") or value == \"Angle\":\n self.arcStartPt = self.vertices[-1]\n \n # imposto il map tool\n self.getPointMapTool().arcStartPt = self.arcStartPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_ANGLE)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.step = 102\n # l'opzione CEnter viene tradotta in italiano in \"CEntro\" nel contesto \"WaitForArcMenu\"\n elif value == QadMsg.translate(\"Command_PLINE\", \"CEnter\", \"WaitForArcMenu\") or value == \"CEnter\":\n self.arcStartPt = self.vertices[-1]\n \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_CENTER_PT)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the center of the arc: \"))\n self.step = 108\n elif value == QadMsg.translate(\"Command_PLINE\", \"Close\") or value == \"Close\":\n arc = QadArc()\n\n if arc.fromStartEndPtsTan(self.arcStartPt, self.vertices[0], self.arcTanOnStartPt) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n qad_layer.addLineToLayer(self.plugIn, currLayer, self.vertices)\n\n return True # fine comando\n elif value == QadMsg.translate(\"Command_PLINE\", \"Direction\") or value == \"Direction\":\n self.arcStartPt = self.vertices[-1]\n \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_SECOND_PT)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the tangent direction for the start point of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.step = 112\n elif value == QadMsg.translate(\"Command_PLINE\", \"Line\") or value == \"Line\":\n self.mode = \"LINE\"\n self.getPointMapTool().refreshSnapType() # riagggiorno lo snapType che può essere variato dal maptool dell'arco\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.getPointMapTool().setStartPoint(self.vertices[-1]) \n self.WaitForLineMenu() \n elif value == QadMsg.translate(\"Command_PLINE\", \"Radius\") or value == \"Radius\":\n self.arcStartPt = self.vertices[-1]\n \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_RADIUS)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the radius of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 114\n elif value == QadMsg.translate(\"Command_PLINE\", \"Second point\") or value == \"Second point\":\n self.arcStartPt = self.vertices[-1]\n \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_SECOND_PT)\n # si appresta ad attendere un punto \n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify second point of the arc: \"))\n self.step = 119\n # l'opzione Undo viene tradotta in italiano in \"ANNulla\" nel contesto \"WaitForArcMenu\"\n elif value == QadMsg.translate(\"Command_PLINE\", \"Undo\", \"WaitForArcMenu\") or value == \"Undo\":\n if len(self.vertices) >= 2:\n self.delLastRealVertex() # cancello ultimo vertice reale\n self.getPointMapTool().clear()\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.WaitForArcMenu()\n elif type(value) == QgsPoint: # é stato inserito il punto finale dell'arco\n arc = QadArc() \n if arc.fromStartEndPtsTan(self.arcStartPt, value, self.arcTanOnStartPt) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso\n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea \n \n self.WaitForArcMenu()\n \n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare angolo inscritto: \" (da step = 101)\n elif self.step == 102: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcAngle = qad_utils.getAngleBy2Pts(self.arcStartPt, value) \n else:\n self.arcAngle = value\n\n # imposto il map tool\n self.getPointMapTool().arcAngle = self.arcAngle\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_END_PT)\n\n # l'opzione CEnter viene tradotta in italiano in \"Centro\" nel contesto \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\"\n keyWords = QadMsg.translate(\"Command_PLINE\", \"CEnter\", \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Radius\")\n englishKeyWords = \"CEnter\" + \"/\" + \"Radius\"\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n \n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n self.step = 103\n\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco o [Centro/Raggio]: : \" (da step = 102)\n elif self.step == 103: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n # l'opzione CEnter viene tradotta in italiano in \"Centro\" nel contesto \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\"\n if value == QadMsg.translate(\"Command_PLINE\", \"CEnter\", \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\") or value == \"CEnter\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_CENTER_PT)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the center of the arc: \"))\n self.step = 104\n elif value == QadMsg.translate(\"Command_PLINE\", \"Radius\") or value == \"Radius\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_RADIUS)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the radius of the arc: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 105\n elif type(value) == QgsPoint: # é stato inserito il punto finale dell'arco\n arc = QadArc() \n if arc.fromStartEndPtsAngle(self.arcStartPt, value, self.arcAngle) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False\n\n # l'opzione CEnter viene tradotta in italiano in \"Centro\" nel contesto \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\"\n keyWords = QadMsg.translate(\"Command_PLINE\", \"CEnter\", \"START_PT_ANGLE_KNOWN_ASK_FOR_END_PT\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"Radius\")\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"CEnter\" + \"/\" + \"Radius\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA CENTRO DELL'ARCO (da step = 103)\n elif self.step == 104: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n arc = QadArc() \n if arc.fromStartCenterPtsAngle(self.arcStartPt, value, self.arcAngle) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the center of the arc: \"))\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA RAGGIO (da step = 103)\n elif self.step == 105: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcStartPtForRadius = value\n \n # imposto il map tool\n self.getPointMapTool().arcStartPtForRadius = self.arcStartPtForRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_SECONDPTRADIUS)\n \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify second point: \"))\n self.step = 106\n else:\n self.arcRadius = value\n self.plugIn.setLastRadius(self.arcRadius)\n\n # imposto il map tool\n self.getPointMapTool().arcRadius = self.arcRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n msg = QadMsg.translate(\"Command_PLINE\", \"Specify the direction for the chord of the arc <{0}>: \")\n self.waitFor(msg.format(str(self.getLastSegmentAng())), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.step = 107\n \n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO DEL RAGGIO (da step = 105)\n elif self.step == 106: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.arcRadius = qad_utils.getDistance(self.arcStartPtForRadius, value)\n self.plugIn.setLastRadius(self.arcRadius) \n\n # imposto il map tool\n self.getPointMapTool().arcRadius = self.arcRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n msg = QadMsg.translate(\"Command_PLINE\", \"Specify the direction for the chord of the arc <{0}>: \")\n self.waitFor(msg.format(str(self.getLastSegmentAng())), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.step = 107\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DIREZIONE DELLA CORDA DELL'ARCO (da step = 106 e 107)\n elif self.step == 107: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if type(value) == QgsPoint:\n self.arcChordDirection = qad_utils.getAngleBy2Pts(self.arcStartPt, value) \n else:\n self.arcChordDirection = value\n \n arc = QadArc()\n if arc.fromStartPtAngleRadiusChordDirection(self.arcStartPt, self.arcAngle, \\\n self.arcRadius, self.arcChordDirection) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n msg = QadMsg.translate(\"Command_PLINE\", \"Specify the direction for the chord of the arc <{0}>: \")\n self.waitFor(msg.format(str(self.getLastSegmentAng())), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA CENTRO DELL'ARCO (da step = 101)\n elif self.step == 108: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.arcCenterPt = value\n\n # imposto il map tool\n self.getPointMapTool().arcCenterPt = self.arcCenterPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_END_PT)\n\n keyWords = QadMsg.translate(\"Command_PLINE\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"chord Length\")\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n \n englishKeyWords = \"Angle\" + \"/\" + \"chord Length\"\n keyWords += \"_\" + englishKeyWords \n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n self.step = 109 \n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco o [Angolo/Lunghezza corda]: \" (da step = 108)\n elif self.step == 109: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode: \n if value == QadMsg.translate(\"Command_PLINE\", \"Angle\") or value == \"Angle\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_ANGLE)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori <> 0\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.step = 110\n return False\n elif value == QadMsg.translate(\"Command_PLINE\", \"chord Length\") or value == \"chord Length\":\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_CHORD)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the chord length: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n self.step = 111\n return False \n elif type(value) == QgsPoint: # se é stato inserito il punto finale dell'arco\n self.arcEndPt = value\n \n arc = QadArc() \n if arc.fromStartCenterEndPts(self.arcStartPt, self.arcCenterPt, self.arcEndPt) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n \n keyWords = QadMsg.translate(\"Command_PLINE\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_PLINE\", \"chord Length\")\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n \n englishKeyWords = \"Angle\" + \"/\" + \"chord Length\"\n keyWords += \"_\" + englishKeyWords \n # si appresta ad attendere un punto o una parola chiave \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NOT_NULL)\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare angolo inscritto: \" (da step = 109)\n elif self.step == 110: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcAngle = qad_utils.getAngleBy2Pts(self.arcCenterPt, value) \n else:\n self.arcAngle = value\n\n arc = QadArc() \n if arc.fromStartCenterPtsAngle(self.arcStartPt, self.arcCenterPt, self.arcAngle) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare lunghezza della corda: \" (da step = 109)\n elif self.step == 111: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcChord = qad_utils.getDistance(self.arcStartPt, value) \n else:\n self.arcChord = value\n\n arc = QadArc() \n if arc.fromStartCenterPtsChord(self.arcStartPt, self.arcCenterPt, self.arcChord) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the chord length: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.FLOAT, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n\n return False\n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare direzione tangente per il punto iniziale dell'arco: \" (da step = 101)\n elif self.step == 112: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcTanOnStartPt = qad_utils.getAngleBy2Pts(self.arcStartPt, value) \n else:\n self.arcTanOnStartPt = value\n\n # imposto il map tool\n self.getPointMapTool().arcTanOnStartPt = self.arcTanOnStartPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_TAN_KNOWN_ASK_FOR_END_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc: \"))\n self.step = 113\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO FINALE DELL'ARCO (da step = 112)\n elif self.step == 113: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n arc = QadArc()\n if arc.fromStartEndPtsTan(self.arcStartPt, value, self.arcTanOnStartPt) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc: \"))\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA RAGGIO (da step = 101)\n elif self.step == 114: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcStartPtForRadius = value\n \n # imposto il map tool\n self.getPointMapTool().arcStartPtForRadius = self.arcStartPtForRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_SECONDPTRADIUS)\n \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify second point: \"))\n self.step = 115\n else:\n self.arcRadius = value\n self.plugIn.setLastRadius(self.arcRadius)\n\n # imposto il map tool\n self.getPointMapTool().arcRadius = self.arcRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_RADIUS_KNOWN_ASK_FOR_END_PT)\n \n keyWords = QadMsg.translate(\"Command_PLINE\", \"Angle\")\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n englishKeyWords = \"Angle\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, keyWords, QadInputModeEnum.NOT_NULL)\n self.step = 116\n \n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO DEL RAGGIO (da step = 114)\n elif self.step == 115: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.arcRadius = qad_utils.getDistance(self.arcStartPtForRadius, value)\n self.plugIn.setLastRadius(self.arcRadius) \n\n # imposto il map tool\n self.getPointMapTool().arcRadius = self.arcRadius\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_RADIUS_KNOWN_ASK_FOR_END_PT)\n \n keyWords = QadMsg.translate(\"Command_PLINE\", \"Angle\")\n prompt = QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc or [{0}]: \").format(keyWords)\n englishKeyWords = \"Angle\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, keyWords, QadInputModeEnum.NOT_NULL)\n self.step = 116\n \n return False\n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare punto finale dell'arco o [Angolo]: \" (da step = 114 o 115)\n elif self.step == 116: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_PLINE\", \"Angle\") or value == \"Angle\": \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_ANGLE)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n self.waitFor(QadMsg.translate(\"Command_PLINE\", \"Specify the included angle: \"), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", \\\n QadInputModeEnum.NOT_NULL | QadInputModeEnum.NOT_ZERO)\n self.step = 117\n elif type(value) == QgsPoint: # é stato inserito il punto finale dell'arco\n arc = QadArc() \n if arc.fromStartEndPtsRadius(self.arcStartPt, value, self.arcRadius) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n \n return False \n \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA \"Specificare angolo inscritto: \" (da step = 116)\n elif self.step == 117: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint:\n self.arcAngle = qad_utils.getAngleBy2Pts(self.arcStartPt, value) \n else:\n self.arcAngle = value\n\n # imposto il map tool\n self.getPointMapTool().arcAngle = self.arcAngle\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n msg = QadMsg.translate(\"Command_PLINE\", \"Specify the direction for the chord of the arc <{0}>: \")\n self.waitFor(msg.format(str(self.getLastSegmentAng())), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n self.step = 118\n\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DIREZIONE DELLA CORDA DELL'ARCO (da step = 117)\n elif self.step == 118: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if type(value) == QgsPoint:\n self.arcChordDirection = qad_utils.getAngleBy2Pts(self.arcStartPt, value) \n else:\n self.arcChordDirection = value\n \n arc = QadArc()\n if arc.fromStartPtAngleRadiusChordDirection(self.arcStartPt, self.arcAngle, \\\n self.arcRadius, self.arcChordDirection) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION)\n # si appresta ad attendere un punto o un numero reale \n # msg, inputType, default, keyWords, isNullable\n msg = QadMsg.translate(\"Command_PLINE\", \"Specify the direction for the chord of the arc <{0}>: \")\n self.waitFor(msg.format(str(self.getLastSegmentAng())), \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.ANGLE, \\\n None, \"\", QadInputModeEnum.NOT_NULL)\n \n return False\n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO (da step = 101)\n elif self.step == 119: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.arcSecondPt = value\n # imposto il map tool\n self.getPointMapTool().arcSecondPt = self.arcSecondPt\n self.getPointMapTool().setMode(Qad_arc_maptool_ModeEnum.START_SECOND_PT_KNOWN_ASK_FOR_END_PT)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc: \"))\n self.step = 120\n \n return False\n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO FINALE DELL'ARCO (da step = 119)\n elif self.step == 120: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.arcEndPt = value\n \n arc = QadArc() \n if arc.fromStartSecondEndPts(self.arcStartPt, self.arcSecondPt, self.arcEndPt) == True:\n points = arc.asPolyline()\n if points is not None:\n # se i punti sono così vicini da essere considerati uguali\n if qad_utils.ptNear(self.arcStartPt, arc.getStartPt()):\n self.addArcVertices(points, False) # aggiungo i punti in ordine\n else:\n self.addArcVertices(points, True) # aggiungo i punti in ordine inverso \n self.getPointMapTool().setTmpGeometry(QgsGeometry.fromPolyline(self.vertices)) # per lo snap aggiungo questa geometria temporanea\n \n self.WaitForArcMenu()\n return False \n \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_PLINE\", \"Specify the final point of the arc: \")) \n return False "
},
{
"alpha_fraction": 0.6360414624214172,
"alphanum_fraction": 0.6383751034736633,
"avg_line_length": 43.75822067260742,
"blob_id": "657f56df08ee9aaefff01d8ee3071fcb762f3738",
"content_id": "f116dcca7521071c1ebd1c549c8e3192434231d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 69454,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 1551,
"path": "/qad.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comandi di editazione geometria stile CAD\n \n -------------------\n begin : 2014-11-03\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n# Initialize Qt resources from file qad_rc.py\nimport qad_rc\nimport math\n\n\nimport qad_utils\nfrom qad_maptool import QadMapTool\nfrom qad_variables import *\nfrom qad_textwindow import *\nfrom qad_commands import *\nfrom qad_entity import *\nfrom qad_dim import QadDimStyles\nimport qad_layer\nimport qad_undoredo\n\nclass Qad(QObject):\n \"\"\"\n Classe plug in di Qad\n \"\"\"\n\n # UI\n toolBar = None\n dimToolBar = None\n menu = None\n translator = None\n\n \n # Map Tool attivo. Quando non ci sono comandi che necessitano di input dalla finestra grafica\n # QadMapTool é quello attivo \n tool = None\n # Finestra grafica\n canvas = None\n # Finestra testuale\n TextWindow = None\n # Classe che gestisce i comandi\n QadCommands = None\n # Azione corrente\n currentAction = None\n # Finestra testuale già collegata\n __alreadyDockedTextWindow = False\n # ultimo punto selezionato\n lastPoint = None\n # coeff angolare ultimo segmento\n lastSegmentAng = 0.0\n # ultima rotazione\n lastRot = 0.0\n # ultima altezza testo\n lastHText = 1.0\n # ultimo angolo di riferimento (es. comando ruota)\n lastReferenceRot = 0.0\n # ultimo nuovo angolo di riferimento (es. comando ruota)\n lastNewReferenceRot = 0.0\n # ultimo raggio\n lastRadius = 1.0\n # ultimo punto di offset\n lastOffsetPt = QgsPoint(0, 0)\n # ultima lunghezza di riferimento (es. comando scala)\n lastReferenceLen = 1.0\n # ultima lunghezza di riferimento (es. comando scala)\n lastNewReferenceLen = 1.0\n # ultimo fattore di scala (es. comando scala)\n lastScale = 1.0\n # numero di segmenti per l'approssimazione delle curve (es. buffer)\n segments = 10\n # ultima entità inserita\n lastEntity = None\n # ultimo set di entità\n lastEntitySet = None\n # tipo di unione (es. editpl->unione)\n joinMode = 1 # 1=Estendi, 2=Aggiungi, 3=Entrambi\n # distanza di approssimazione nell'unione (es. editpl->unione)\n joinToleranceDist = 0.0\n # modalità di raccordo in comando raccordo\n filletMode = 1 # 1=Taglia-estendi, 2=Non taglia-estendi\n # ultimo numero di lati per poligono\n lastPolygonSideNumber = 4\n # ultima opzione di costruzione del poligono conoscendo il centro\n # \"Inscritto nel cerchio\", Circoscritto intorno al cerchio\", \"Area\"\n lastPolygonConstructionModeByCenter = QadMsg.translate(\"Command_POLYGON\", \"Inscribed in circle\")\n # ultimo delta usato nel comando lengthen\n lastDelta_lengthen = 0.0\n # ultimo delta angolo usato nel comando lengthen\n lastDeltaAngle_lengthen = 0.0\n # ultima percentuale usata nel comando lengthen\n lastPerc_lengthen = 100.0\n # ultima lunghezza totale usato nel comando lengthen\n lastTotal_lengthen = 1.0\n # ultimo angolo totale usato nel comando lengthen\n lastTotalAngle_lengthen = 0.0\n # ultima modalità operativa del comando lengthen\n lastOpMode_lengthen = \"DElta\"\n\n # flag per identificare se un comando di QAD é attivo oppure no\n isQadActive = False\n \n # Quotatura\n dimTextEntitySetRecodeOnSave = QadLayerEntitySet() # entity set dei testi delle quote da riallineare in salvataggio\n beforeCommitChangesDimLayer = None # layer da cui é scaturito il salvataggio delle quotature\n isSaveControlledByQAD = False\n\n def version(self):\n return \"2.8.005\"\n \n def setLastPointAndSegmentAng(self, point, segmentAng = None):\n # memorizzo il coeff angolare ultimo segmento e l'ultimo punto selezionato\n if segmentAng is None: \n if self.lastPoint is not None: \n self.setLastSegmentAng(qad_utils.getAngleBy2Pts(self.lastPoint, point))\n else:\n self.setLastSegmentAng(segmentAng) \n self.setLastPoint(point)\n\n def setLastPoint(self, point):\n # memorizzo l'ultimo punto selezionato \n self.lastPoint = point\n\n def setLastSegmentAng(self, segmentAng):\n # memorizzo il coeff angolare ultimo segmento\n self.lastSegmentAng = qad_utils.normalizeAngle(segmentAng) \n \n def setLastRot(self, rot):\n # memorizzo l'ultima rotazione in radianti\n self.lastRot = qad_utils.normalizeAngle(rot)\n \n def setLastHText(self, hText):\n # memorizzo l'ultima altezza testo\n if hText > 0:\n self.lastHText = hText\n\n def setLastReferenceRot(self, rot):\n # memorizzo l'ultimo angolo di riferimento (es. comando ruota) in radianti\n self.lastReferenceRot = qad_utils.normalizeAngle(rot)\n\n def setLastNewReferenceRot(self, rot):\n # memorizzo l'ultimo nuovo angolo di riferimento (es. comando ruota) in radianti\n self.lastNewReferenceRot = qad_utils.normalizeAngle(rot)\n \n def setLastRadius(self, radius):\n # memorizzo l'ultimo raggio\n if radius > 0:\n self.lastRadius = radius \n\n def setLastOffsetPt(self, offSetPt):\n # memorizzo l'ultimo punto di offset\n # la x del punto rappresenta l'offset X\n # la y del punto rappresenta l'offset Y\n self.lastOffsetPt.set(offSetPt.x(), offSetPt.y())\n\n def setLastReferenceLen(self, length):\n # memorizzo l'ultima lunghezza di riferimento (es. comando scale)\n self.lastReferenceLen = length\n\n def setLastNewReferenceRot(self, length):\n # memorizzo l'ultima nuova lunghezza di riferimento (es. comando scale)\n self.lastNewReferenceLen = length\n \n def setLastScale(self, scale):\n # memorizzo l'ultimo fattore di scala\n if scale > 0:\n self.lastScale = scale \n\n def setNSegmentsToApproxCurve(self, segments):\n # memorizzo il numero di segmenti per l'approssimazione delle curve (es. buffer)\n if segments > 1:\n self.segments = int(segments) \n\n def setLastEntity(self, layer, featureId):\n # memorizzo l'ultimo entità creata\n if self.lastEntity is None:\n self.lastEntity = QadEntity()\n self.lastEntity.set(layer, featureId)\n \n def getLastEntity(self):\n if self.lastEntity is None:\n return None\n else:\n if self.lastEntity.exists() == False: # non esiste più\n return None\n else:\n return self.lastEntity\n \n def setLastEntitySet(self, entitySet):\n # memorizzo l'ultimo set di entità\n if self.lastEntitySet is None:\n self.lastEntitySet = QadEntitySet()\n self.lastEntitySet.set(entitySet)\n\n def setJoinMode(self, joinMode):\n # memorizzo tipo di unione (es. editpl->unione); 1=Estendi, 2=Aggiungi, 3=Entrambi\n if joinMode == 1 or joinMode == 2 or joinMode == 3:\n self.joinMode = int(joinMode) \n\n def setJoinToleranceDist(self, joinToleranceDist):\n # memorizzo la distanza di approssimazione nell'unione (es. editpl->unione)\n if joinToleranceDist >= 0:\n self.joinToleranceDist = joinToleranceDist \n\n def setFilletMode(self, filletMode):\n # memorizzo modalità di raccordo in comando raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n if filletMode == 1 or filletMode == 2:\n self.filletMode = int(filletMode) \n\n def setLastPolygonSideNumber(self, polygonSideNumber):\n # memorizzo l'ultimo numero di lati del poligono\n if polygonSideNumber > 2:\n self.lastPolygonSideNumber = polygonSideNumber\n\n def setLastPolygonConstructionModeByCenter(self, mode):\n # memorizzo ultima opzione di costruzione del poligono conoscendo il centro\n # \"Inscritto nel cerchio\", Circoscritto intorno al cerchio\", \"Area\"\n self.lastPolygonConstructionModeByCenter = mode\n\n def setLastDelta_lengthen(self, lastDelta_lengthen):\n # ultimo delta usato nel comando lengthen\n self.lastDelta_lengthen = lastDelta_lengthen\n\n def setLastDeltaAngle_lengthen(self, lastDeltaAngle_lengthen):\n # ultimo delta angolo usato nel comando lengthen\n self.lastDeltaAngle_lengthen = qad_utils.normalizeAngle(lastDeltaAngle_lengthen)\n\n def setLastPerc_lengthen(self, lastPerc_lengthen): \n # ultima percentuale usata nel comando lengthen\n if lastPerc_lengthen > 0:\n self.lastPerc_lengthen = lastPerc_lengthen\n\n def setLastTotal_lengthen(self, lastTotal_lengthen): \n # ultima lunghezza totale usato nel comando lengthen\n if lastTotal_lengthen > 0:\n self.lastTotal_lengthen = lastTotal_lengthen\n\n def setLastTotalAngle_lengthen(self, lastTotalAngle_lengthen): \n # ultimo angolo totale usato nel comando lengthen\n self.lastTotalAngle_lengthen = qad_utils.normalizeAngle(lastTotalAngle_lengthen)\n\n def setLastOpMode_lengthen(self, opMode):\n # memorizzo modalità operativa del comando lengthen: \"DElta\" o \"Percent\" o \"Total\" o \"DYnamic\"\n if opMode == \"DElta\" or opMode == \"Percent\" or opMode == \"Total\" or opMode == \"DYnamic\":\n self.lastOpMode_lengthen = opMode \n\n def loadDimStyles(self):\n global QadDimStyles\n # carico gli stili di quotatura\n QadDimStyles.load()\n # questa variabile non avrebbe senso perchè si dovrebbe usare la variabile globale QadDimStyles\n # per un motivo sconosciuto quando si generano gli eventi tipo beforeCommitChanges\n # la variabile globale QadDimStyles risulta essere None anche se QAD non lo hai mai posto a quel valore\n # se invece uso una variabile del plugin che punta a QadDimStyles questa non viene messa a None\n self.mQadDimStyle = QadDimStyles\n \n \n #============================================================================\n # __initLocalization\n #============================================================================\n # inizializza la localizzazione delle traduzioni e dell'help in linea\n def __initLocalization(self, locale): \n localePath = os.path.join(self.plugin_dir, 'i18n', 'qad_{}.qm'.format(locale))\n\n if os.path.exists(localePath):\n self.translator = QTranslator()\n self.translator.load(localePath)\n if qVersion() > '4.3.3':\n QCoreApplication.installTranslator(self.translator)\n return True\n else:\n return False\n \n \n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, iface):\n \n QObject.__init__(self) \n \n # Save reference to the QGIS interface\n self.iface = iface\n \n # initialize plugin directory\n self.plugin_dir = os.path.dirname(__file__)\n \n # initialize locale\n userLocaleList = QSettings().value(\"locale/userLocale\").split(\"_\")\n language = userLocaleList[0]\n region = userLocaleList[1] if len(userLocaleList) > 1 else \"\"\n # provo a caricare la lingua e la regione selezionate\n if self.__initLocalization(language + \"_\" + region) == False:\n # provo a caricare la lingua\n self.__initLocalization(language)\n \n self.canvas = self.iface.mapCanvas()\n self.tool = QadMapTool(self)\n \n # Lista dei comandi\n self.QadCommands = QadCommandsClass(self)\n \n # inizializzzione sul caricamento del progetto\n self.initOnProjectLoaded()\n \n def initOnProjectLoaded(self):\n # carico le variabili d'ambiente\n QadVariables.load()\n # carico gli stili di quotatura\n self.loadDimStyles()\n # Gestore di Undo/Redo\n self.undoStack = qad_undoredo.QadUndoStack()\n\n def initGui(self):\n # creo tutte le azioni e le collego ai comandi\n self.initActions()\n\n # Connect to signals\n QObject.connect(self.canvas, SIGNAL(\"mapToolSet(QgsMapTool*)\"), self.deactivate) \n \n # Add menu \n self.menu = QMenu(QadMsg.translate(\"QAD\", \"QAD\"))\n self.menu.addAction(self.mainAction)\n self.menu.addAction(self.help_action)\n\n self.menu.addAction(self.u_action)\n self.menu.addAction(self.undo_action)\n self.menu.addAction(self.redo_action)\n\n # crea il menu Draw\n self.drawMenu = self.createDrawMenu()\n self.menu.addMenu(self.drawMenu)\n\n # menu Edit \n self.editMenu = self.createEditMenu()\n self.menu.addMenu(self.editMenu)\n\n # menu Tools \n self.toolsMenu = self.createToolsMenu()\n self.menu.addMenu(self.toolsMenu)\n\n # menu Dim \n self.dimMenu = self.createDimMenu()\n self.menu.addMenu(self.dimMenu)\n \n # aggiunge il menu al menu vector di QGIS\n self.iface.vectorMenu().addMenu(self.menu)\n \n# menu_bar = self.iface.mainWindow().menuBar()\n# actions = menu_bar.actions()\n# lastAction = actions[ len( actions ) - 1 ]\n# menu_bar.insertMenu(lastAction, self.menu )\n \n # aggiunge le toolbar\n self.toolBar = self.iface.addToolBar(\"QAD\")\n self.toolBar.setObjectName(\"QAD\")\n self.toolBar.addAction(self.mainAction)\n self.toolBar.addAction(self.help_action)\n\n # aggiunge le toolbar per i comandi \n self.toolBar.addAction(self.setCurrLayerByGraph_action)\n self.toolBar.addAction(self.setCurrUpdateableLayerByGraph_action)\n self.toolBar.addAction(self.u_action)\n self.toolBar.addAction(self.redo_action)\n self.toolBar.addAction(self.line_action)\n self.toolBar.addAction(self.pline_action)\n # arco\n self.arcToolButton = self.createArcToolButton()\n self.toolBar.addWidget(self.arcToolButton)\n # cerchio\n self.circleToolButton = self.createCircleToolButton()\n self.toolBar.addWidget(self.circleToolButton)\n\n self.toolBar.addAction(self.rectangle_action)\n self.toolBar.addAction(self.polygon_action)\n self.toolBar.addAction(self.mpolygon_action)\n self.toolBar.addAction(self.mbuffer_action)\n self.toolBar.addAction(self.insert_action)\n self.toolBar.addAction(self.text_action)\n \n self.toolBar.addAction(self.erase_action)\n self.toolBar.addAction(self.rotate_action)\n self.toolBar.addAction(self.move_action)\n self.toolBar.addAction(self.scale_action)\n self.toolBar.addAction(self.copy_action)\n self.toolBar.addAction(self.offset_action)\n self.toolBar.addAction(self.extend_action)\n self.toolBar.addAction(self.trim_action)\n self.toolBar.addAction(self.mirror_action)\n self.toolBar.addAction(self.stretch_action)\n self.toolBar.addAction(self.lengthen_action)\n self.toolBar.addAction(self.break_action)\n self.toolBar.addAction(self.pedit_action)\n self.toolBar.addAction(self.fillet_action)\n self.toolBar.addAction(self.dsettings_action)\n self.enableUndoRedoButtons()\n\n # aggiunge la toolbar per la quotatura \n self.dimToolBar = self.createDimToolBar()\n \n # Inizializzo la finestra di testo\n self.TextWindow = QadTextWindow(self)\n self.TextWindow.initGui()\n\n # aggiungo i segnali di aggiunta e rimozione di layer per collegare ogni layer\n # all'evento <layerModified> per sapere se la modifica fatta su quel layer\n # é stata fatta da QAD o dall'esterno\n QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL(\"layerWasAdded(QgsMapLayer *)\"), self.layerAdded)\n QObject.connect(QgsMapLayerRegistry.instance(), SIGNAL(\"layerWillBeRemoved(QString)\"), self.removeLayer)\n QObject.connect(self.iface, SIGNAL(\"projectRead()\"), self.onProjectLoaded)\n\n self.showTextWindow(QadVariables.get(QadMsg.translate(\"Environment variables\", \"SHOWTEXTWINDOW\"), True))\n self.setStandardMapTool()\n\n\n def unload(self):\n self.abortCommand()\n # Disconnect to signals\n QObject.disconnect(self.canvas, SIGNAL(\"mapToolSet(QgsMapTool*)\"), self.deactivate) \n QObject.disconnect(QgsMapLayerRegistry.instance(), SIGNAL(\"layerWasAdded(QgsMapLayer *)\"), self.layerAdded)\n QObject.disconnect(QgsMapLayerRegistry.instance(), SIGNAL(\"layerWillBeRemoved(QString)\"), self.removeLayer)\n QObject.disconnect(self.iface, SIGNAL(\"projectRead()\"), self.onProjectLoaded)\n \n # Remove the plugin menu item and icon\n self.iface.removePluginVectorMenu(\"&QAD\", self.mainAction)\n self.iface.removeToolBarIcon(self.mainAction)\n \n # remove toolbars and menubars\n if self.toolBar is not None:\n del self.toolBar\n if self.dimToolBar is not None:\n del self.dimToolBar\n if self.menu is not None:\n del self.menu\n if self.TextWindow is not None:\n self.TextWindow.close()\n if self.tool:\n if self.canvas.mapTool() == self.tool:\n self.canvas.unsetMapTool(self.tool)\n elif self.QadCommands.actualCommand is not None:\n if self.canvas.mapTool() == self.QadCommands.actualCommand.getPointMapTool():\n self.canvas.unsetMapTool(self.QadCommands.actualCommand.getPointMapTool())\n \n self.tool.removeItems()\n del self.tool\n\n\n def onProjectLoaded(self):\n self.initOnProjectLoaded()\n self.showTextWindow(QadVariables.get(QadMsg.translate(\"Environment variables\", \"SHOWTEXTWINDOW\"), True))\n self.setStandardMapTool()\n\n\n #============================================================================\n # INIZIO - Gestione ACTION (da chiamare prima di creare MENU e TOOLBAR) \n #============================================================================\n def initActions(self):\n # Creo le azioni e le collego ai comandi\n \n self.mainAction = QAction(QIcon(\":/plugins/qad/icons/qad.png\"), \\\n QadMsg.translate(\"QAD\", \"QAD\"), self.iface.mainWindow())\n self.mainAction.setCheckable(True)\n QObject.connect(self.mainAction, SIGNAL(\"triggered()\"), self.run)\n \n # PLINE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"PLINE\"))\n self.pline_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.pline_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.pline_action)\n \n # SETCURRLAYERBYGRAPH\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"SETCURRLAYERBYGRAPH\"))\n self.setCurrLayerByGraph_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.setCurrLayerByGraph_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.setCurrLayerByGraph_action)\n # SETCURRUPDATEABLELAYERBYGRAPH\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"SETCURRUPDATEABLELAYERBYGRAPH\"))\n self.setCurrUpdateableLayerByGraph_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.setCurrUpdateableLayerByGraph_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.setCurrUpdateableLayerByGraph_action)\n \n # ARC\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"ARC\"))\n self.arc_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.arc_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.arc_action)\n # ARC BY 3 POINTS (MACRO)\n self.arcBy3Points_action = QAction(QIcon(\":/plugins/qad/icons/arcBy3Points.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc passing through 3 points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcBy3Points_action, SIGNAL(\"triggered()\"), self.runARCBY3POINTSCommand)\n # ARC BY START CENTER END POINTS (MACRO)\n self.arcByStartCenterEndPoints_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartCenterEndPoints.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, central and final points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartCenterEndPoints_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_CENTER_END_Command)\n # ARC BY START CENTER ANGLE (MACRO)\n self.arcByStartCenterAngle_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartCenterAngle.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, central points and angle\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartCenterAngle_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_CENTER_ANGLE_Command)\n # ARC BY START CENTER LENGTH (MACRO)\n self.arcByStartCenterLength_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartCenterLength.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, central points and cord length\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartCenterLength_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_CENTER_LENGTH_Command)\n # ARC BY START END ANGLE (MACRO)\n self.arcByStartEndAngle_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartEndAngle.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, final points and angle\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartEndAngle_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_END_ANGLE_Command)\n # ARC BY START END TAN (MACRO)\n self.arcByStartEndTan_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartEndTan.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, final points and tangent\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartEndTan_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_END_TAN_Command)\n # ARC BY START END RADIUS (MACRO)\n self.arcByStartEndRadius_action = QAction(QIcon(\":/plugins/qad/icons/arcByStartEndRadius.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by start, final points and radius\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByStartEndRadius_action, SIGNAL(\"triggered()\"), self.runARC_BY_START_END_RADIUS_Command)\n # ARC BY CENTER START END (MACRO)\n self.arcByCenterStartEnd_action = QAction(QIcon(\":/plugins/qad/icons/arcByCenterStartEnd.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by central, start and final points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByCenterStartEnd_action, SIGNAL(\"triggered()\"), self.runARC_BY_CENTER_START_END_Command)\n # ARC BY CENTER START ANGLE (MACRO)\n self.arcByCenterStartAngle_action = QAction(QIcon(\":/plugins/qad/icons/arcByCenterStartAngle.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by central, start points and angle\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByCenterStartAngle_action, SIGNAL(\"triggered()\"), self.runARC_BY_CENTER_START_ANGLE_Command)\n # ARC BY CENTER START LENGTH (MACRO)\n self.arcByCenterStartLength_action = QAction(QIcon(\":/plugins/qad/icons/arcByCenterStartLength.png\"), \\\n QadMsg.translate(\"Command_ARC\", \"Arc defined by central, start points and cord length\"), \\\n self.iface.mainWindow())\n QObject.connect(self.arcByCenterStartLength_action, SIGNAL(\"triggered()\"), self.runARC_BY_CENTER_START_LENGTH_Command)\n \n # CIRCLE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"CIRCLE\"))\n self.circle_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.circle_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.circle_action)\n # CIRCLE BY CENTER RADIUS (MACRO)\n self.circleByCenterRadius_action = QAction(QIcon(\":/plugins/qad/icons/circleByCenterRadius.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by central point and radius\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleByCenterRadius_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_CENTER_RADIUS_Command)\n # CIRCLE BY CENTER DIAMETER (MACRO)\n self.circleByCenterDiameter_action = QAction(QIcon(\":/plugins/qad/icons/circleByCenterDiameter.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by central point and diameter\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleByCenterDiameter_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_CENTER_DIAMETER_Command)\n # CIRCLE BY 2 POINTS (MACRO)\n self.circleBy2Points_action = QAction(QIcon(\":/plugins/qad/icons/circleBy2Points.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by 2 points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleBy2Points_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_2POINTS_Command)\n # CIRCLE BY 3 POINTS (MACRO)\n self.circleBy3Points_action = QAction(QIcon(\":/plugins/qad/icons/circleBy3Points.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by 3 points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleBy3Points_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_3POINTS_Command)\n # CIRCLE BY TANGEN TANGENT RADIUS (MACRO)\n self.circleBy2TansRadius_action = QAction(QIcon(\":/plugins/qad/icons/circleBy2TansRadius.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by 2 tangent points and radius\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleBy2TansRadius_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_2TANS_RADIUS_Command)\n # CIRCLE BY TANGEN TANGENT TANGENT (MACRO)\n self.circleBy3Tans_action = QAction(QIcon(\":/plugins/qad/icons/circleBy3Tans.png\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Circle defined by 3 tangent points\"), \\\n self.iface.mainWindow())\n QObject.connect(self.circleBy3Tans_action, SIGNAL(\"triggered()\"), self.runCIRCLE_BY_3TANS_Command)\n \n # DSETTINGS\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"DSETTINGS\"))\n self.dsettings_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.dsettings_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.dsettings_action)\n \n # LINE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"LINE\"))\n self.line_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.line_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.line_action)\n \n # ERASE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"ERASE\"))\n self.erase_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.erase_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.erase_action)\n \n # MPOLYGON\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"MPOLYGON\"))\n self.mpolygon_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.mpolygon_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.mpolygon_action)\n \n # MBUFFER\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"MBUFFER\"))\n self.mbuffer_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.mbuffer_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.mbuffer_action)\n \n # ROTATE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"ROTATE\"))\n self.rotate_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.rotate_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.rotate_action)\n \n # MOVE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"MOVE\"))\n self.move_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.move_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.move_action)\n \n # SCALE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"SCALE\"))\n self.scale_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.scale_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.scale_action)\n \n # COPY\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"COPY\"))\n self.copy_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.copy_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.copy_action)\n \n # OFFSET\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"OFFSET\"))\n self.offset_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.offset_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.offset_action)\n \n # EXTEND\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"EXTEND\"))\n self.extend_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.extend_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.extend_action)\n \n # TRIM\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"TRIM\"))\n self.trim_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.trim_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.trim_action)\n \n # RECTANGLE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"RECTANGLE\"))\n self.rectangle_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.rectangle_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.rectangle_action)\n \n # POLYGON\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"POLYGON\"))\n self.polygon_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.polygon_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.polygon_action)\n \n # MIRROR\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"MIRROR\"))\n self.mirror_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.mirror_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.mirror_action)\n \n # UNDO\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"UNDO\"))\n self.undo_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.undo_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.undo_action)\n # UNDO OF ONLY ONE OPERATION (MACRO)\n self.u_action = QAction(QIcon(\":/plugins/qad/icons/u.png\"), \\\n QadMsg.translate(\"Command_UNDO\", \"Undo last operation\"), \\\n self.iface.mainWindow())\n QObject.connect(self.u_action, SIGNAL(\"triggered()\"), self.runU_Command)\n \n # REDO\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"REDO\"))\n self.redo_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.redo_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.redo_action)\n \n # INSERT\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"INSERT\"))\n self.insert_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.insert_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.insert_action)\n \n # TEXT\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"TEXT\"))\n self.text_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.text_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.text_action)\n \n # STRETCH\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"STRETCH\"))\n self.stretch_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.stretch_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.stretch_action)\n \n # LENGTHEN\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"LENGTHEN\"))\n self.lengthen_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.lengthen_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.lengthen_action)\n \n # BREAK\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"BREAK\"))\n self.break_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.break_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.break_action)\n \n # PEDIT\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"PEDIT\"))\n self.pedit_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.pedit_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.pedit_action)\n \n # FILLET\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"FILLET\"))\n self.fillet_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.fillet_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.fillet_action)\n \n # DIMLINEAR\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"DIMLINEAR\"))\n self.dimLinear_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.dimLinear_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.dimLinear_action)\n # DIMALIGNED\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"DIMALIGNED\"))\n self.dimAligned_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.dimAligned_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.dimAligned_action)\n # DIMSTYLE\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"DIMSTYLE\"))\n self.dimStyle_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.dimStyle_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.dimStyle_action)\n\n # HELP\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"HELP\"))\n self.help_action = QAction(cmd.getIcon(), cmd.getName(), self.iface.mainWindow())\n self.help_action.setToolTip(cmd.getToolTipText())\n cmd.connectQAction(self.help_action)\n\n\n #============================================================================\n # FINE - Gestione ACTION\n #============================================================================\n\n\n def UpdatedVariablesEvent(self):\n # aggiorna in base alle nuove impostazioni delle variabili\n self.tool.UpdatedVariablesEvent()\n \n \n #============================================================================\n # INIZIO - Gestione MENU (da chiamare prima di creare TOOLBAR)\n #============================================================================\n def createArcMenu(self):\n # menu Draw \n arcMenu = QMenu(QadMsg.translate(\"Command_list\", \"ARC\"))\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"ARC\"))\n arcMenu.setIcon(cmd.getIcon())\n arcMenu.addAction(self.arcBy3Points_action)\n arcMenu.addSeparator() \n arcMenu.addAction(self.arcByStartCenterEndPoints_action) \n arcMenu.addAction(self.arcByStartCenterAngle_action) \n arcMenu.addAction(self.arcByStartCenterLength_action) \n arcMenu.addSeparator() \n arcMenu.addAction(self.arcByStartEndAngle_action) \n arcMenu.addAction(self.arcByStartEndTan_action) \n arcMenu.addAction(self.arcByStartEndRadius_action) \n arcMenu.addSeparator() \n arcMenu.addAction(self.arcByCenterStartEnd_action) \n arcMenu.addAction(self.arcByCenterStartAngle_action) \n arcMenu.addAction(self.arcByCenterStartLength_action) \n return arcMenu\n\n def createCircleMenu(self):\n # menu Draw \n circleMenu = QMenu(QadMsg.translate(\"Command_list\", \"CIRCLE\"))\n cmd = self.QadCommands.getCommandObj(QadMsg.translate(\"Command_list\", \"CIRCLE\"))\n circleMenu.setIcon(cmd.getIcon())\n circleMenu.addAction(self.circleByCenterRadius_action)\n circleMenu.addAction(self.circleByCenterDiameter_action)\n circleMenu.addSeparator() \n circleMenu.addAction(self.circleBy2Points_action)\n circleMenu.addAction(self.circleBy3Points_action)\n circleMenu.addSeparator() \n circleMenu.addAction(self.circleBy2TansRadius_action)\n circleMenu.addAction(self.circleBy3Tans_action)\n return circleMenu\n\n def createDrawMenu(self):\n # menu Draw \n drawMenu = QMenu(QadMsg.translate(\"QAD\", \"Draw\"))\n drawMenu.addAction(self.line_action)\n drawMenu.addAction(self.pline_action) \n \n # menu arco\n self.arcMenu = self.createArcMenu()\n drawMenu.addMenu(self.arcMenu)\n # menu cerchio\n self.circleMenu = self.createCircleMenu()\n drawMenu.addMenu(self.circleMenu)\n \n drawMenu.addAction(self.rectangle_action)\n drawMenu.addAction(self.polygon_action)\n drawMenu.addAction(self.mpolygon_action)\n drawMenu.addAction(self.mbuffer_action)\n drawMenu.addSeparator() \n drawMenu.addAction(self.insert_action)\n drawMenu.addAction(self.text_action) \n return drawMenu\n\n def createEditMenu(self):\n # menu Edit\n editMenu = QMenu(QadMsg.translate(\"QAD\", \"Edit\"))\n editMenu.addAction(self.erase_action)\n editMenu.addAction(self.rotate_action)\n editMenu.addAction(self.move_action)\n editMenu.addAction(self.scale_action)\n editMenu.addAction(self.copy_action)\n editMenu.addAction(self.offset_action)\n editMenu.addAction(self.extend_action)\n editMenu.addAction(self.trim_action)\n editMenu.addAction(self.mirror_action)\n editMenu.addAction(self.stretch_action)\n editMenu.addAction(self.lengthen_action)\n editMenu.addAction(self.break_action)\n editMenu.addAction(self.pedit_action)\n editMenu.addAction(self.fillet_action)\n return editMenu\n \n def createToolsMenu(self):\n # menu Tools \n toolsMenu = QMenu(QadMsg.translate(\"QAD\", \"Tools\"))\n toolsMenu.addAction(self.setCurrLayerByGraph_action)\n toolsMenu.addAction(self.setCurrUpdateableLayerByGraph_action) \n toolsMenu.addAction(self.dsettings_action)\n return toolsMenu\n\n def createDimMenu(self):\n # menu Dim \n dimMenu = QMenu(QadMsg.translate(\"QAD\", \"Dimensioning\"))\n dimMenu.addAction(self.dimLinear_action)\n dimMenu.addAction(self.dimAligned_action)\n dimMenu.addAction(self.dimStyle_action)\n return dimMenu\n \n #============================================================================\n # FINE - Gestione MENU\n #============================================================================\n\n\n #============================================================================\n # INIZIO - Gestione TOOLBAR\n #============================================================================\n def createArcToolButton(self):\n arcToolButton = QToolButton(self.toolBar)\n arcToolButton.setPopupMode(QToolButton.MenuButtonPopup)\n arcToolButton.setMenu(self.arcMenu)\n arcToolButton.setDefaultAction(self.arcMenu.actions()[0]) # prima voce di menu\n arcToolButton.triggered.connect(self.arcToolButtonTriggered)\n return arcToolButton\n def arcToolButtonTriggered(self, action):\n self.arcToolButton.setDefaultAction(action)\n \n def createCircleToolButton(self):\n circleToolButton = QToolButton(self.toolBar)\n circleToolButton.setPopupMode(QToolButton.MenuButtonPopup)\n circleToolButton.setMenu(self.circleMenu)\n circleToolButton.setDefaultAction(self.circleMenu.actions()[0]) # prima voce di menu\n circleToolButton.triggered.connect(self.circleToolButtonTriggered)\n return circleToolButton\n def circleToolButtonTriggered(self, action):\n self.circleToolButton.setDefaultAction(action)\n\n def createDimToolBar(self):\n # aggiunge la toolbar per la quotatura\n toolBar = self.iface.addToolBar(QadMsg.translate(\"QAD\", \"QAD - Dimensioning\"))\n toolBar.setObjectName(QadMsg.translate(\"QAD\", \"QAD - Dimensioning\"))\n toolBar.addAction(self.dimLinear_action)\n toolBar.addAction(self.dimAligned_action)\n toolBar.addAction(self.dimStyle_action)\n return toolBar\n\n\n #============================================================================\n # FINE - Gestione TOOLBAR\n #============================================================================\n\n\n #============================================================================\n # INIZIO - Gestione Layer\n #============================================================================\n\n # se viene salvato per prima un layer di quote testuale:\n # 1) beforeCommitChanges su layer testuale\n # 2) committedFeaturesAdded su layer testuale\n # 3) editingStopped su layer testuale che scatena\n # 1) committedFeaturesAdded su layer linee\n # 2) committedFeaturesAdded su layer simboli\n\n # se viene salvato per prima un layer di quote simbolo o linea:\n # 1) beforeCommitChanges su layer simbolo o linea\n # 2) committedFeaturesAdded su layer testuale\n # 3) editingStopped su layer testuale che scatena\n # 1) committedFeaturesAdded su layer linea\n # 2) committedFeaturesAdded su layer simboli\n \n def layerAdded(self, layer):\n QObject.connect(layer, SIGNAL(\"layerModified()\"), self.layerModified)\n QObject.connect(layer, SIGNAL(\"beforeCommitChanges()\"), self.beforeCommitChanges)\n QObject.connect(layer, SIGNAL(\"committedFeaturesAdded(QString, QgsFeatureList)\"), self.committedFeaturesAdded)\n # vedi qgsvectorlayer.cpp funzione QgsVectorLayer::commitChanges()\n # devo predere l'ultimo segnale vhe viene emesso dal salvataggio QGIS\n # questo segnale arriva alla fine del salvataggio di un layer dalla versione 2.3 di QGIS\n #QObject.connect(layer, SIGNAL(\"repaintRequested()\"), self.repaintRequested)\n # questo segnale arriva alla fine del salvataggio di un layer alla versione 2.2 di QGIS\n QObject.connect(layer, SIGNAL(\"editingStopped()\"), self.editingStopped) \n \n \n def removeLayer(self, layerId):\n # viene rimosso un layer quindi lo tolgo dallo stack\n self.undoStack.clearByLayer(layerId)\n self.enableUndoRedoButtons()\n\n\n def editingStopped(self):\n # questo segnale arriva alla fine del salvataggio di un layer alla versione 2.2 di QGIS\n # se bisogna fare la ricodifica delle quote\n if self.dimTextEntitySetRecodeOnSave.isEmpty() == False:\n layer = self.dimTextEntitySetRecodeOnSave.layer\n # ricavo gli stili di quotatura\n dimStyleList = self.mQadDimStyle.getDimListByLayer(layer)\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # cerco tutte le feature in self.dimTextEntitySetRecodeOnSave che appartengono allo stile\n # di quotatura dimStyle\n textAddedFeatures = dimStyle.getFilteredFeatureCollection(self.dimTextEntitySetRecodeOnSave)\n # salvo gli oggetti di quello stile di quotatura aggiornando i reference\n self.isSaveControlledByQAD = True\n # ricodifica \n dimStyle.updateTextReferencesOnSave(self, textAddedFeatures)\n \n self.dimTextEntitySetRecodeOnSave.clear()\n\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # salvataggio\n dimStyle.commitChanges(self.beforeCommitChangesDimLayer)\n self.beforeCommitChangesDimLayer = None\n self.isSaveControlledByQAD = False\n dimStyle.startEditing()\n elif self.isSaveControlledByQAD == False:\n layer = self.sender()\n # verifico se il layer che si è appena finito di salvare appartiene ad uno o più stili di quotatura\n dimStyleList = self.mQadDimStyle.getDimListByLayer(layer)\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # salvataggio\n self.isSaveControlledByQAD = True\n dimStyle.commitChanges(self.beforeCommitChangesDimLayer)\n self.beforeCommitChangesDimLayer = None\n self.isSaveControlledByQAD = False\n dimStyle.startEditing()\n\n\n def repaintRequested(self):\n # questo segnale arriva alla fine del salvataggio di un layer dalla versione 2.3 di QGIS\n # se bisogna fare la ricodifica delle quote\n if self.dimTextEntitySetRecodeOnSave.isEmpty() == False:\n # ricavo gli stili di quotatura\n dimStyleList = self.mQadDimStyle.getDimListByLayer(self.dimTextEntitySetRecodeOnSave.layer)\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # cerco tutte le feature in self.dimTextEntitySetRecodeOnSave che appartengono allo stile\n # di quotatura dimStyle\n textAddedFeatures = dimStyle.getFilteredFeatureCollection(self.dimTextEntitySetRecodeOnSave) \n # salvo gli oggetti di quello stile di quotatura aggiornando i reference\n self.isSaveControlledByQAD = True\n # ricodifica \n dimStyle.updateTextReferencesOnSave(self, textAddedFeatures)\n \n self.dimTextEntitySetRecodeOnSave.clear()\n \n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # salvataggio\n dimStyle.commitChanges(self.beforeCommitChangesDimLayer)\n self.beforeCommitChangesDimLayer = None\n self.isSaveControlledByQAD = False\n dimStyle.startEditing()\n\n \n def beforeCommitChanges(self):\n if self.isSaveControlledByQAD == False:\n layer = self.sender()\n # verifico se il layer che si sta per salvare appartiene ad uno o più stili di quotatura\n dimStyleList = self.mQadDimStyle.getDimListByLayer(layer)\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n if dimStyle.getTextualLayer().id() != layer.id(): # se non si tratta del layer dei testi di quota\n self.beforeCommitChangesDimLayer = layer # memorizzo il layer da cui é scaturito il salvataggio delle quotature\n self.isSaveControlledByQAD = True\n dimStyle.textCommitChangesOnSave() # salvo i testi delle quote per ricodifica ID\n dimStyle.startEditing()\n self.isSaveControlledByQAD = False\n\n \n def committedFeaturesAdded(self, layerId, addedFeatures):\n layer = qad_layer.getLayerById(layerId)\n # verifico se il layer che é stato salvato appartiene ad uno o più stili di quotatura\n dimStyleList = self.mQadDimStyle.getDimListByLayer(layer)\n for dimStyle in dimStyleList:\n if dimStyle.getInValidErrMsg() is None: # stile valido\n # se si tratta del layer testuale delle quote\n if dimStyle.getTextualLayer().id() == layerId:\n # mi memorizzo le features testuali da riallineare \n self.dimTextEntitySetRecodeOnSave.set(dimStyle.getTextualLayer(), addedFeatures)\n return\n\n\n def layerModified(self):\n if self.isQadActive == False:\n # la modifica fatta su quel layer é stata fatta dall'esterno di QAD\n # quindi ho perso la sincronizzazione con lo stack di undo di QAD che\n # viene svuotato perché ormai inutilizzabile\n self.undoStack.clear()\n self.enableUndoRedoButtons()\n \n\n #============================================================================\n # INIZIO - Gestione UNDO e REDO\n #============================================================================\n\n \n def enableUndoRedoButtons(self):\n self.undo_action.setEnabled(self.undoStack.isUndoAble())\n self.u_action.setEnabled(self.undoStack.isUndoAble())\n self.redo_action.setEnabled(self.undoStack.isRedoAble())\n\n def beginEditCommand(self, text, layerList):\n if type(layerList) == list or type(layerList) == tuple:\n # layerList é una lista di layer\n self.undoStack.beginEditCommand(text, layerList)\n else:\n # layerList é un solo layer\n self.undoStack.beginEditCommand(text, [layerList])\n\n\n def destroyEditCommand(self):\n # pulisco le entità selezionate e i grip points correnti\n self.tool.clearEntitySet()\n self.tool.clearEntityGripPoints()\n\n self.isQadActive = True\n self.undoStack.destroyEditCommand()\n self.isQadActive = False\n self.enableUndoRedoButtons()\n\n\n def endEditCommand(self):\n self.isQadActive = True\n self.undoStack.endEditCommand(self.canvas)\n self.isQadActive = False\n self.enableUndoRedoButtons()\n \n def undoEditCommand(self, nTimes = 1):\n # pulisco le entità selezionate e i grip points correnti\n self.tool.clearEntitySet()\n self.tool.clearEntityGripPoints()\n \n self.isQadActive = True\n self.undoStack.undoEditCommand(self.canvas, nTimes)\n self.isQadActive = False\n self.enableUndoRedoButtons()\n\n\n def redoEditCommand(self, nTimes = 1): \n # pulisco le entità selezionate e i grip points correnti\n self.tool.clearEntitySet()\n self.tool.clearEntityGripPoints()\n\n self.isQadActive = True\n self.undoStack.redoEditCommand(self.canvas, nTimes)\n self.isQadActive = False\n self.enableUndoRedoButtons()\n\n\n def addLayerToLastEditCommand(self, text, layer):\n self.undoStack.addLayerToLastEditCommand(text, layer)\n \n def insertBeginGroup(self, text = \"Group\"):\n self.undoStack.insertBeginGroup(text)\n \n def insertEndGroup(self):\n return self.undoStack.insertEndGroup()\n\n def insertBookmark(self, text = \"Bookmark\"):\n return self.undoStack.insertBookmark(text)\n \n def getPrevBookmarkPos(self):\n return self.undoStack.getPrevBookmarkPos(self.undoStack.index)\n \n def undoUntilBookmark(self):\n # pulisco le entità selezionate e i grip points correnti\n self.tool.clearEntitySet()\n self.tool.clearEntityGripPoints()\n\n self.isQadActive = True\n self.undoStack.undoUntilBookmark(self.canvas)\n self.isQadActive = False\n self.enableUndoRedoButtons()\n\n \n #============================================================================\n # FINE - Gestione UNDO e REDO\n #============================================================================\n\n def run(self):\n self.setStandardMapTool()\n self.showTextWindow()\n\n def deactivate(self):\n self.mainAction.setChecked(False)\n\n def setStandardMapTool(self):\n mc = self.canvas\n mc.setMapTool(self.tool)\n self.mainAction.setChecked(True)\n\n def keyPressEvent(self, event):\n self.TextWindow.keyPressEvent(event)\n pass\n\n \n #============================================================================\n # INIZIO - funzioni per visualizzare messaggi nella finestra di testo \n #============================================================================\n def showTextWindow(self, mode = True):\n if mode == True:\n if self.__alreadyDockedTextWindow == False:\n self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.TextWindow)\n self.__alreadyDockedTextWindow = True\n\n self.TextWindow.setVisible(mode)\n if mode == True:\n self.TextWindow.setFocus()\n\n def showMsg(self, msg, displayPromptAfterMsg = False):\n self.TextWindow.showMsg(msg, displayPromptAfterMsg)\n \n def showErr(self, err):\n self.TextWindow.showErr(err)\n\n def showInputMsg(self, inputMsg = None, inputType = QadInputTypeEnum.COMMAND, \\\n default = None, keyWords = \"\", inputMode = QadInputModeEnum.NONE):\n # il valore di default del parametro di una funzione non può essere una traduzione\n # perché lupdate.exe non lo riesce ad interpretare\n if inputMsg is None: \n inputMsg = QadMsg.translate(\"QAD\", \"Command: \")\n \n self.TextWindow.showInputMsg(inputMsg, inputType, default, keyWords, inputMode)\n\n \n #============================================================================\n # INIZIO - funzioni per comandi \n #============================================================================\n \n def clearCurrentObjsSelection(self):\n # pulisco le entità selezionate e i grip points correnti\n self.tool.clearEntitySet()\n self.clearEntityGripPoints()\n\n def clearEntityGripPoints(self):\n # pulisco i grip points correnti\n self.tool.clearEntityGripPoints()\n \n def runCommand(self, command, param = None):\n self.QadCommands.run(command, param)\n\n def runMacro(self, args):\n self.QadCommands.runMacro(args)\n \n def continueCommandFromMapTool(self):\n self.QadCommands.continueCommandFromMapTool()\n\n def continueCommandFromTextWindow(self, msg):\n self.QadCommands.continueCommandFromTextWindow(msg)\n\n def abortCommand(self):\n self.QadCommands.abortCommand()\n \n def isValidCommand(self, command):\n return self.QadCommands.isValidCommand(command)\n \n def getCommandNames(self):\n return self.QadCommands.getCommandNames()\n \n def getCommandObj(self, cmdName):\n return self.QadCommands.getCommandObj(cmdName)\n \n def getMoreUsedCmd(self, filter):\n return self.QadCommands.getMoreUsedCmd(filter)\n\n def isValidEnvVariable(self, variable):\n return self.QadCommands.isValidEnvVariable(variable)\n \n def forceCommandMapToolSnapTypeOnce(self, snapType, snapParams = None):\n self.QadCommands.forceCommandMapToolSnapTypeOnce(snapType, snapParams)\n \n def refreshCommandMapToolSnapType(self):\n self.QadCommands.refreshCommandMapToolSnapType()\n \n def getCurrenPointFromCommandMapTool(self):\n return self.QadCommands.getCurrenPointFromCommandMapTool()\n \n def toggleOsMode(self):\n value = QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\"))\n if value & QadSnapTypeEnum.DISABLE:\n value = value - QadSnapTypeEnum.DISABLE\n msg = QadMsg.translate(\"QAD\", \"<Snap on>\")\n else:\n value = value + QadSnapTypeEnum.DISABLE\n msg = QadMsg.translate(\"QAD\", \"<Snap off>\")\n\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"OSMODE\"), value)\n QadVariables.save()\n self.showMsg(msg, True) \n self.QadCommands.refreshCommandMapToolSnapType()\n\n def toggleOrthoMode(self):\n value = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ORTHOMODE\"))\n if value == 0:\n value = 1\n autosnap = QadVariables.get(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"))\n if (autosnap & 8) == True:\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"), autosnap - 8) # disattivo la modalità polare \n msg = QadMsg.translate(\"QAD\", \"<Ortho on>\")\n else:\n value = 0\n msg = QadMsg.translate(\"QAD\", \"<Ortho off>\")\n\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"ORTHOMODE\"), value)\n QadVariables.save()\n self.showMsg(msg, True) \n self.QadCommands.refreshCommandMapToolOrthoMode()\n\n def togglePolarMode(self):\n value = QadVariables.get(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"))\n if (value & 8) == False:\n value = value + 8\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"ORTHOMODE\"), 0) # disattivo la modalità orto \n msg = QadMsg.translate(\"QAD\", \"<Polar on>\")\n else:\n value = value - 8\n msg = QadMsg.translate(\"QAD\", \"<Polar off>\")\n\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"), value)\n QadVariables.save()\n self.showMsg(msg, True) \n self.QadCommands.refreshCommandMapToolAutoSnap()\n \n def getCurrMsgFromTxtWindow(self):\n return self.TextWindow.getCurrMsg()\n\n def getHistoryfromTxtWindow(self):\n return self.TextWindow.getHistory() # list\n\n def updateHistoryfromTxtWindow(self, command):\n return self.TextWindow.updateHistory(command)\n\n def showEvaluateMsg(self, msg = None):\n self.TextWindow.showEvaluateMsg(msg)\n \n #============================================================================\n # funzioni per l'avvio di un comando\n #============================================================================\n def runCommandAbortingTheCurrent(self, cmdName):\n self.mainAction.setChecked(True)\n self.canvas.setFocus()\n self.abortCommand()\n self.showEvaluateMsg(cmdName)\n\n def runMacroAbortingTheCurrent(self, args):\n self.mainAction.setChecked(True)\n self.canvas.setFocus()\n self.abortCommand() \n self.runMacro(args)\n \n def runIDCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"ID\"))\n \n def runSETVARCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"SETVAR\"))\n\n def runPLINECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"PLINE\"))\n \n def runSETCURRLAYERBYGRAPHCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"SETCURRLAYERBYGRAPH\"))\n\n def runSETCURRUPDATEABLELAYERBYGRAPHCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"SETCURRUPDATEABLELAYERBYGRAPH\"))\n \n def runARCCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"ARC\"))\n def runARCBY3POINTSCommand(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), None, None, None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_CENTER_END_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None,\n None] \n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_CENTER_ANGLE_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Angle\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_CENTER_LENGTH_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"chord Length\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_END_ANGLE_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"End\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Angle\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_END_TAN_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"End\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Direction\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_START_END_RADIUS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"End\"), \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Radius\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_CENTER_START_END_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None, \\\n None, \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_CENTER_START_ANGLE_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None, \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"Angle\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runARC_BY_CENTER_START_LENGTH_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"ARC\"), \\\n QadMsg.translate(\"Command_ARC\", \"Center\"), \\\n None, \\\n None, \\\n QadMsg.translate(\"Command_ARC\", \"chord Length\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n \n def runCIRCLECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"CIRCLE\"))\n def runCIRCLE_BY_CENTER_RADIUS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CIRCLE\"), \\\n None, \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runCIRCLE_BY_CENTER_DIAMETER_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CERCHIO\"), \\\n None, \\\n QadMsg.translate(\"Command_CIRCLE\", \"Diameter\"), \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runCIRCLE_BY_2POINTS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CIRCLE\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"2POints\"), \\\n None, \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runCIRCLE_BY_3POINTS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CIRCLE\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"3Points\"), \\\n None, \\\n None, \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runCIRCLE_BY_2TANS_RADIUS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CIRCLE\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"Ttr (tangent tangent radius)\"), \\\n None, \\\n None, \\\n None]\n self.runMacroAbortingTheCurrent(args)\n def runCIRCLE_BY_3TANS_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"CIRCLE\"), \\\n QadMsg.translate(\"Command_CIRCLE\", \"3Points\"), \\\n QadMsg.translate(\"Snap\", \"TAN\"), \\\n QadMsg.translate(\"Snap\", \"TAN\"), \\\n QadMsg.translate(\"Snap\", \"TAN\")]\n self.runMacroAbortingTheCurrent(args)\n \n def runDSETTINGSCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"DSETTINGS\"))\n \n def runLINECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"LINE\"))\n \n def runERASECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"ERASE\"))\n \n def runMPOLYGONCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"MPOLYGON\"))\n \n def runMBUFFERCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"MBUFFER\"))\n \n def runROTATECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"ROTATE\"))\n \n def runMOVECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"MOVE\"))\n \n def runSCALECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"SCALE\"))\n \n def runCOPYCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"COPY\"))\n \n def runOFFSETCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"OFFSET\"))\n \n def runEXTENDCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"EXTEND\"))\n \n def runTRIMCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"TRIM\"))\n \n def runRECTANGLECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"RECTANGLE\"))\n \n def runMIRRORCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"MIRROR\"))\n \n def runUNDOCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"UNDO\"))\n def runU_Command(self): # MACRO\n # nome comando + argomenti\n args = [QadMsg.translate(\"Command_list\", \"UNDO\"), \\\n QadMsg.translate(\"Command_UNDO\", \"1\")]\n self.runMacroAbortingTheCurrent(args)\n \n def runREDOCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"REDO\"))\n \n def runINSERTCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"INSERT\"))\n \n def runTEXTCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"TEXT\"))\n \n def runSTRETCHCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"STRETCH\"))\n \n def runBREAKCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"BREAK\"))\n \n def runPEDITCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"PEDIT\"))\n\n def runFILLETCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"FILLET\"))\n \n def runPOLYGONCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"POLYGON\"))\n \n def runDIMLINEARCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"DIMLINEAR\"))\n\n def runDIMALIGNEDCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"DIMALIGNED\"))\n\n def runDIMSTYLECommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"DIMSTYLE\"))\n\n def runHELPCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"HELP\"))\n\n def runLENGTHENCommand(self):\n self.runCommandAbortingTheCurrent(QadMsg.translate(\"Command_list\", \"LENGTHEN\"))\n"
},
{
"alpha_fraction": 0.508308470249176,
"alphanum_fraction": 0.5134214162826538,
"avg_line_length": 33.02898406982422,
"blob_id": "5316517659bf48e96550d777dd4d201bc2d545a9",
"content_id": "527cda0d0860dede7b4479146e8cde650fecb28e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2347,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 69,
"path": "/qad_dsettings_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando DSETTINGS per impostazione disegno\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\n\n\nfrom qad_dsettings_dlg import QadDSETTINGSDialog\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\n\n\n# Classe che gestisce il comando DSETTINGS\nclass QadDSETTINGSCommandClass(QadCommandClass):\n \n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadDSETTINGSCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"DSETTINGS\")\n\n def getEnglishName(self):\n return \"DSETTINGS\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runDSETTINGSCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/dsettings.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_DSETTINGS\", \"Drafting Settings (snaps, etc.).\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n \n def run(self, msgMapTool = False, msg = None): \n Form = QadDSETTINGSDialog(self.plugIn)\n Form.exec_()\n return True"
},
{
"alpha_fraction": 0.654796302318573,
"alphanum_fraction": 0.6883085370063782,
"avg_line_length": 81.80342102050781,
"blob_id": "cc26d3978f752bf30d42a5213fbd90c1c32d1767",
"content_id": "e23c6a64f4f9108054ae5a6f704c20a5fbb55775",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 29064,
"license_type": "no_license",
"max_line_length": 318,
"num_lines": 351,
"path": "/qad_dsettings_ui.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qad_dsettings.ui'\n#\n# Created: Tue Sep 08 15:55:18 2015\n# by: PyQt4 UI code generator 4.10.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_DSettings_Dialog(object):\n def setupUi(self, DSettings_Dialog):\n DSettings_Dialog.setObjectName(_fromUtf8(\"DSettings_Dialog\"))\n DSettings_Dialog.setWindowModality(QtCore.Qt.ApplicationModal)\n DSettings_Dialog.resize(441, 455)\n DSettings_Dialog.setMouseTracking(True)\n DSettings_Dialog.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)\n DSettings_Dialog.setModal(True)\n self.tabWidget = QtGui.QTabWidget(DSettings_Dialog)\n self.tabWidget.setGeometry(QtCore.QRect(10, 10, 421, 401))\n self.tabWidget.setObjectName(_fromUtf8(\"tabWidget\"))\n self.tab_1 = QtGui.QWidget()\n self.tab_1.setObjectName(_fromUtf8(\"tab_1\"))\n self.groupBox = QtGui.QGroupBox(self.tab_1)\n self.groupBox.setGeometry(QtCore.QRect(10, 40, 391, 321))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.layoutWidget = QtGui.QWidget(self.groupBox)\n self.layoutWidget.setGeometry(QtCore.QRect(60, 290, 261, 25))\n self.layoutWidget.setObjectName(_fromUtf8(\"layoutWidget\"))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout_2.setMargin(0)\n self.horizontalLayout_2.setObjectName(_fromUtf8(\"horizontalLayout_2\"))\n self.pushButton_SelectALL = QtGui.QPushButton(self.layoutWidget)\n self.pushButton_SelectALL.setObjectName(_fromUtf8(\"pushButton_SelectALL\"))\n self.horizontalLayout_2.addWidget(self.pushButton_SelectALL)\n self.pushButton_DeSelectALL = QtGui.QPushButton(self.layoutWidget)\n self.pushButton_DeSelectALL.setObjectName(_fromUtf8(\"pushButton_DeSelectALL\"))\n self.horizontalLayout_2.addWidget(self.pushButton_DeSelectALL)\n self.layoutWidget1 = QtGui.QWidget(self.groupBox)\n self.layoutWidget1.setGeometry(QtCore.QRect(190, 20, 181, 261))\n self.layoutWidget1.setObjectName(_fromUtf8(\"layoutWidget1\"))\n self.gridLayout = QtGui.QGridLayout(self.layoutWidget1)\n self.gridLayout.setMargin(0)\n self.gridLayout.setObjectName(_fromUtf8(\"gridLayout\"))\n self.label_5 = QtGui.QLabel(self.layoutWidget1)\n self.label_5.setText(_fromUtf8(\"\"))\n self.label_5.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_EXTP.png\")))\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.gridLayout.addWidget(self.label_5, 3, 0, 1, 1)\n self.label_13 = QtGui.QLabel(self.layoutWidget1)\n self.label_13.setText(_fromUtf8(\"\"))\n self.label_13.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_PARP.png\")))\n self.label_13.setObjectName(_fromUtf8(\"label_13\"))\n self.gridLayout.addWidget(self.label_13, 4, 0, 1, 1)\n self.label_14 = QtGui.QLabel(self.layoutWidget1)\n self.label_14.setText(_fromUtf8(\"\"))\n self.label_14.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_PROGP.png\")))\n self.label_14.setObjectName(_fromUtf8(\"label_14\"))\n self.gridLayout.addWidget(self.label_14, 5, 0, 1, 1)\n self.label_2 = QtGui.QLabel(self.layoutWidget1)\n self.label_2.setText(_fromUtf8(\"\"))\n self.label_2.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_EXTINT.png\")))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.gridLayout.addWidget(self.label_2, 6, 0, 1, 1)\n self.label_9 = QtGui.QLabel(self.layoutWidget1)\n self.label_9.setText(_fromUtf8(\"\"))\n self.label_9.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_PERP.png\")))\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.gridLayout.addWidget(self.label_9, 1, 0, 1, 1)\n self.checkBox_PERP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_PERP.setTristate(False)\n self.checkBox_PERP.setObjectName(_fromUtf8(\"checkBox_PERP\"))\n self.gridLayout.addWidget(self.checkBox_PERP, 1, 1, 1, 1)\n self.label_10 = QtGui.QLabel(self.layoutWidget1)\n self.label_10.setText(_fromUtf8(\"\"))\n self.label_10.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_TANP.png\")))\n self.label_10.setObjectName(_fromUtf8(\"label_10\"))\n self.gridLayout.addWidget(self.label_10, 2, 0, 1, 1)\n self.checkBox_TANP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_TANP.setTristate(False)\n self.checkBox_TANP.setObjectName(_fromUtf8(\"checkBox_TANP\"))\n self.gridLayout.addWidget(self.checkBox_TANP, 2, 1, 1, 1)\n self.checkBox_EXTP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_EXTP.setTristate(False)\n self.checkBox_EXTP.setObjectName(_fromUtf8(\"checkBox_EXTP\"))\n self.gridLayout.addWidget(self.checkBox_EXTP, 3, 1, 1, 1)\n self.checkBox_PARALP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_PARALP.setTristate(False)\n self.checkBox_PARALP.setObjectName(_fromUtf8(\"checkBox_PARALP\"))\n self.gridLayout.addWidget(self.checkBox_PARALP, 4, 1, 1, 1)\n self.checkBox_PROGRESP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_PROGRESP.setTristate(False)\n self.checkBox_PROGRESP.setObjectName(_fromUtf8(\"checkBox_PROGRESP\"))\n self.gridLayout.addWidget(self.checkBox_PROGRESP, 5, 1, 1, 1)\n self.checkBox_EXT_INT = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_EXT_INT.setObjectName(_fromUtf8(\"checkBox_EXT_INT\"))\n self.gridLayout.addWidget(self.checkBox_EXT_INT, 6, 1, 1, 1)\n self.checkBox_QUADP = QtGui.QCheckBox(self.layoutWidget1)\n self.checkBox_QUADP.setTristate(False)\n self.checkBox_QUADP.setObjectName(_fromUtf8(\"checkBox_QUADP\"))\n self.gridLayout.addWidget(self.checkBox_QUADP, 0, 1, 1, 1)\n self.label_3 = QtGui.QLabel(self.layoutWidget1)\n self.label_3.setText(_fromUtf8(\"\"))\n self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_QUADP.png\")))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.gridLayout.addWidget(self.label_3, 0, 0, 1, 1)\n self.lineEdit_ProgrDistance = QtGui.QLineEdit(self.groupBox)\n self.lineEdit_ProgrDistance.setGeometry(QtCore.QRect(340, 210, 41, 20))\n self.lineEdit_ProgrDistance.setObjectName(_fromUtf8(\"lineEdit_ProgrDistance\"))\n self.layoutWidget2 = QtGui.QWidget(self.groupBox)\n self.layoutWidget2.setGeometry(QtCore.QRect(10, 20, 154, 261))\n self.layoutWidget2.setObjectName(_fromUtf8(\"layoutWidget2\"))\n self.gridLayout_2 = QtGui.QGridLayout(self.layoutWidget2)\n self.gridLayout_2.setMargin(0)\n self.gridLayout_2.setObjectName(_fromUtf8(\"gridLayout_2\"))\n self.label_8 = QtGui.QLabel(self.layoutWidget2)\n self.label_8.setText(_fromUtf8(\"\"))\n self.label_8.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_ENDP.png\")))\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.gridLayout_2.addWidget(self.label_8, 0, 0, 1, 1)\n self.checkBox_END_PLINE = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_END_PLINE.setObjectName(_fromUtf8(\"checkBox_END_PLINE\"))\n self.gridLayout_2.addWidget(self.checkBox_END_PLINE, 0, 1, 1, 1)\n self.label_ENDP = QtGui.QLabel(self.layoutWidget2)\n self.label_ENDP.setText(_fromUtf8(\"\"))\n self.label_ENDP.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_ENDP.png\")))\n self.label_ENDP.setObjectName(_fromUtf8(\"label_ENDP\"))\n self.gridLayout_2.addWidget(self.label_ENDP, 1, 0, 1, 1)\n self.checkBox_ENDP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_ENDP.setTristate(False)\n self.checkBox_ENDP.setObjectName(_fromUtf8(\"checkBox_ENDP\"))\n self.gridLayout_2.addWidget(self.checkBox_ENDP, 1, 1, 1, 1)\n self.label_MIDP = QtGui.QLabel(self.layoutWidget2)\n self.label_MIDP.setText(_fromUtf8(\"\"))\n self.label_MIDP.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_MEDP.png\")))\n self.label_MIDP.setObjectName(_fromUtf8(\"label_MIDP\"))\n self.gridLayout_2.addWidget(self.label_MIDP, 2, 0, 1, 1)\n self.checkBox_MIDP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_MIDP.setTristate(False)\n self.checkBox_MIDP.setObjectName(_fromUtf8(\"checkBox_MIDP\"))\n self.gridLayout_2.addWidget(self.checkBox_MIDP, 2, 1, 1, 1)\n self.label_4 = QtGui.QLabel(self.layoutWidget2)\n self.label_4.setText(_fromUtf8(\"\"))\n self.label_4.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_INTP.png\")))\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.gridLayout_2.addWidget(self.label_4, 3, 0, 1, 1)\n self.checkBox_INTP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_INTP.setTristate(False)\n self.checkBox_INTP.setObjectName(_fromUtf8(\"checkBox_INTP\"))\n self.gridLayout_2.addWidget(self.checkBox_INTP, 3, 1, 1, 1)\n self.label_6 = QtGui.QLabel(self.layoutWidget2)\n self.label_6.setText(_fromUtf8(\"\"))\n self.label_6.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_CENP.png\")))\n self.label_6.setObjectName(_fromUtf8(\"label_6\"))\n self.gridLayout_2.addWidget(self.label_6, 4, 0, 1, 1)\n self.checkBox_CENP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_CENP.setTristate(False)\n self.checkBox_CENP.setObjectName(_fromUtf8(\"checkBox_CENP\"))\n self.gridLayout_2.addWidget(self.checkBox_CENP, 4, 1, 1, 1)\n self.label_7 = QtGui.QLabel(self.layoutWidget2)\n self.label_7.setText(_fromUtf8(\"\"))\n self.label_7.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_NODP.png\")))\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.gridLayout_2.addWidget(self.label_7, 5, 0, 1, 1)\n self.checkBox_NODP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_NODP.setTristate(False)\n self.checkBox_NODP.setObjectName(_fromUtf8(\"checkBox_NODP\"))\n self.gridLayout_2.addWidget(self.checkBox_NODP, 5, 1, 1, 1)\n self.label_11 = QtGui.QLabel(self.layoutWidget2)\n self.label_11.setText(_fromUtf8(\"\"))\n self.label_11.setPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/dsettings/OSNAP_NEARP.png\")))\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.gridLayout_2.addWidget(self.label_11, 6, 0, 1, 1)\n self.checkBox_NEARP = QtGui.QCheckBox(self.layoutWidget2)\n self.checkBox_NEARP.setTristate(False)\n self.checkBox_NEARP.setObjectName(_fromUtf8(\"checkBox_NEARP\"))\n self.gridLayout_2.addWidget(self.checkBox_NEARP, 6, 1, 1, 1)\n self.checkBox_IsOsnapON = QtGui.QCheckBox(self.tab_1)\n self.checkBox_IsOsnapON.setGeometry(QtCore.QRect(10, 10, 126, 17))\n self.checkBox_IsOsnapON.setObjectName(_fromUtf8(\"checkBox_IsOsnapON\"))\n self.tabWidget.addTab(self.tab_1, _fromUtf8(\"\"))\n self.tab_2 = QtGui.QWidget()\n self.tab_2.setObjectName(_fromUtf8(\"tab_2\"))\n self.checkBox_PolarPickPoint = QtGui.QCheckBox(self.tab_2)\n self.checkBox_PolarPickPoint.setGeometry(QtCore.QRect(10, 10, 171, 17))\n self.checkBox_PolarPickPoint.setObjectName(_fromUtf8(\"checkBox_PolarPickPoint\"))\n self.groupBox_2 = QtGui.QGroupBox(self.tab_2)\n self.groupBox_2.setGeometry(QtCore.QRect(10, 40, 151, 81))\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.label_12 = QtGui.QLabel(self.groupBox_2)\n self.label_12.setGeometry(QtCore.QRect(10, 20, 121, 16))\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.comboBox_increment_angle = QtGui.QComboBox(self.groupBox_2)\n self.comboBox_increment_angle.setGeometry(QtCore.QRect(10, 40, 131, 22))\n self.comboBox_increment_angle.setEditable(True)\n self.comboBox_increment_angle.setObjectName(_fromUtf8(\"comboBox_increment_angle\"))\n self.tabWidget.addTab(self.tab_2, _fromUtf8(\"\"))\n self.layoutWidget3 = QtGui.QWidget(DSettings_Dialog)\n self.layoutWidget3.setGeometry(QtCore.QRect(190, 420, 239, 25))\n self.layoutWidget3.setObjectName(_fromUtf8(\"layoutWidget3\"))\n self.horizontalLayout = QtGui.QHBoxLayout(self.layoutWidget3)\n self.horizontalLayout.setMargin(0)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.okButton = QtGui.QPushButton(self.layoutWidget3)\n self.okButton.setObjectName(_fromUtf8(\"okButton\"))\n self.horizontalLayout.addWidget(self.okButton)\n self.cancelButton = QtGui.QPushButton(self.layoutWidget3)\n self.cancelButton.setObjectName(_fromUtf8(\"cancelButton\"))\n self.horizontalLayout.addWidget(self.cancelButton)\n self.pushButton_HELP = QtGui.QPushButton(self.layoutWidget3)\n self.pushButton_HELP.setObjectName(_fromUtf8(\"pushButton_HELP\"))\n self.horizontalLayout.addWidget(self.pushButton_HELP)\n\n self.retranslateUi(DSettings_Dialog)\n self.tabWidget.setCurrentIndex(0)\n QtCore.QObject.connect(self.pushButton_DeSelectALL, QtCore.SIGNAL(_fromUtf8(\"pressed()\")), DSettings_Dialog.ButtonDeselectALL_Pressed)\n QtCore.QObject.connect(self.pushButton_SelectALL, QtCore.SIGNAL(_fromUtf8(\"pressed()\")), DSettings_Dialog.ButtonSelectALL_Pressed)\n QtCore.QObject.connect(self.pushButton_HELP, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DSettings_Dialog.ButtonHELP_Pressed)\n QtCore.QObject.connect(self.okButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DSettings_Dialog.ButtonBOX_Accepted)\n QtCore.QObject.connect(self.cancelButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DSettings_Dialog.reject)\n QtCore.QMetaObject.connectSlotsByName(DSettings_Dialog)\n\n def retranslateUi(self, DSettings_Dialog):\n DSettings_Dialog.setWindowTitle(_translate(\"DSettings_Dialog\", \"QAD - Drawing settings\", None))\n self.groupBox.setTitle(_translate(\"DSettings_Dialog\", \"Object Snap modes\", None))\n self.pushButton_SelectALL.setText(_translate(\"DSettings_Dialog\", \"Select All\", None))\n self.pushButton_DeSelectALL.setText(_translate(\"DSettings_Dialog\", \"Deselect All\", None))\n self.checkBox_PERP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Perpendicular OSnap: orthogonal projection of a given point on a segment.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_PERP.png\\\" /></p></body></html>\", None))\n self.checkBox_PERP.setText(_translate(\"DSettings_Dialog\", \"Perpendicular\", None))\n self.checkBox_TANP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">tangent point on a curve of a line passing through a given point.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_TANP.png\\\" /></p></body></html>\", None))\n self.checkBox_TANP.setText(_translate(\"DSettings_Dialog\", \"Tangent\", None))\n self.checkBox_EXTP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Extension OSnap: point on the segment extension until the cursor position.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_EXTP.png\\\" /></p></body></html>\", None))\n self.checkBox_EXTP.setText(_translate(\"DSettings_Dialog\", \"Extend\", None))\n self.checkBox_PARALP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:8pt;\\\">Parallel OSnap: point on a line, passing through a given point, parallel to a segment.</span></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_PARLP.png\\\" /></p></body></html>\", None))\n self.checkBox_PARALP.setText(_translate(\"DSettings_Dialog\", \"Parallel\", None))\n self.checkBox_PROGRESP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:8pt;\\\">Progressive OSnap: point at a given distance along a geometry line: from a vertex we can set a point at a distance measured along the geometry line.</span></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_PROGRESP.png\\\" /></p></body></html>\", None))\n self.checkBox_PROGRESP.setText(_translate(\"DSettings_Dialog\", \"Progressive\", None))\n self.checkBox_EXT_INT.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:8pt;\\\">Intersection on extension OSnap: intersection point of the extensions of two segments.</span></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_EXTINT.png\\\" /></p></body></html>\", None))\n self.checkBox_EXT_INT.setText(_translate(\"DSettings_Dialog\", \"Intersection on extension\", None))\n self.checkBox_QUADP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Quadrant OSnap: intersections of the cartesian axis with a circumference of a circle or an arc.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_QUADP.png\\\" /></p></body></html>\", None))\n self.checkBox_QUADP.setText(_translate(\"DSettings_Dialog\", \"Quadrant\", None))\n self.checkBox_END_PLINE.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><span style=\\\" font-size:8pt;\\\">Start / End OSnap: starting and ending vertices of a linear geometry.</span></p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_END_PLINE.png\\\" /></p></body></html>\", None))\n self.checkBox_END_PLINE.setText(_translate(\"DSettings_Dialog\", \"Start / End\", None))\n self.checkBox_ENDP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Start / End segment OSnap: starting and ending vertices of each segment of a geometry.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_ENDP.png\\\" /></p></body></html>\", \"aa\"))\n self.checkBox_ENDP.setText(_translate(\"DSettings_Dialog\", \"Segment Start / End\", None))\n self.checkBox_MIDP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Middle point OSnap: middle point of each segment of a geometry.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_MIDP.png\\\" /></p></body></html>\", None))\n self.checkBox_MIDP.setText(_translate(\"DSettings_Dialog\", \"Middle point\", None))\n self.checkBox_INTP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Intersection OSnap: intersection between two segments.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_INTP.png\\\" /></p></body></html>\", None))\n self.checkBox_INTP.setText(_translate(\"DSettings_Dialog\", \"Intersection\", None))\n self.checkBox_CENP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Center OSnap: center of a circle or arc or centroid of an areal geometry.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_CENP.png\\\" /></p></body></html>\", None))\n self.checkBox_CENP.setText(_translate(\"DSettings_Dialog\", \"Center\", None))\n self.checkBox_NODP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Node OSnap: coordinate of a punctual geometry.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_NODP.png\\\" /></p></body></html>\", None))\n self.checkBox_NODP.setText(_translate(\"DSettings_Dialog\", \"Node\", None))\n self.checkBox_NEARP.setToolTip(_translate(\"DSettings_Dialog\", \"<!DOCTYPE HTML PUBLIC \\\"-//W3C//DTD HTML 4.0//EN\\\" \\\"http://www.w3.org/TR/REC-html40/strict.dtd\\\">\\n\"\n\"<html><head><meta name=\\\"qrichtext\\\" content=\\\"1\\\" /><style type=\\\"text/css\\\">\\n\"\n\"p, li { white-space: pre-wrap; }\\n\"\n\"</style></head><body style=\\\" font-family:\\'MS Shell Dlg 2\\'; font-size:8.25pt; font-weight:400; font-style:normal;\\\">\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\">Near OSnap: point of a segment close to the cursor position.</p>\\n\"\n\"<p style=\\\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\\\"><img src=\\\":/plugins/qad/icons/dsettings/OSNAP_ToolTIP_NEARP.png\\\" /></p></body></html>\", None))\n self.checkBox_NEARP.setText(_translate(\"DSettings_Dialog\", \"Near\", None))\n self.checkBox_IsOsnapON.setText(_translate(\"DSettings_Dialog\", \"Object Snap (F3)\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_1), _translate(\"DSettings_Dialog\", \"Object Snap\", None))\n self.checkBox_PolarPickPoint.setText(_translate(\"DSettings_Dialog\", \"Polar Tracking (F10)\", None))\n self.groupBox_2.setTitle(_translate(\"DSettings_Dialog\", \"Polar angle settings\", None))\n self.label_12.setText(_translate(\"DSettings_Dialog\", \"Increment angle:\", None))\n self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate(\"DSettings_Dialog\", \"Polar Tracking\", None))\n self.okButton.setText(_translate(\"DSettings_Dialog\", \"OK\", None))\n self.cancelButton.setText(_translate(\"DSettings_Dialog\", \"Cancel\", None))\n self.pushButton_HELP.setText(_translate(\"DSettings_Dialog\", \"?\", None))\n\nimport qad_dsettings_rc\n"
},
{
"alpha_fraction": 0.6999282240867615,
"alphanum_fraction": 0.7221823334693909,
"avg_line_length": 43.935482025146484,
"blob_id": "990d7f0071640b0b76c8f1a696266d00c765a013",
"content_id": "8b04e4269741dcb0bb9820d02292c24dfa7cb69a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1393,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 31,
"path": "/help/help_en/16_Commandscustomization.htm",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n<meta name=\"generator\" content=\n\"HTML Tidy for Windows (vers 25 March 2009), see www.w3.org\">\n<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\">\n<meta name=\"Generator\" content=\"Microsoft Word 14 (filtered)\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"embeddedstyles.css\">\n<title>Commands customization</title>\n<meta name=\"generator\" content=\"chmProcessor\">\n</head>\n<body lang=\"IT\">\n<div class=\"WordSection1\">\n<h2><a name=\"node15\" id=\"node15\"></a><span lang=\"EN-US\">Commands\ncustomization</span></h2>\n<p class=\"MsoNormal\"><span lang=\"EN-US\">It is possible customize\nthe commands (<em><span style=\n'font-family:\"Calibri\",\"sans-serif\"'>shortcuts</span></em>) by a\nfile named qad_<language>_<region>.pgp\n(utf-8).</span></p>\n<p class=\"MsoNormal\"><span lang=\"EN-US\">Language is the current\nQGIS language (mandatory) and region is the current linguistic\nregion (optional). For example qad_pt_br.pgp is the file in\nportuguese language of region Brazil, qad_en.pgp is the English\nversion of the pgp file. The file is searched by QAD following the\npaths in the system variable SUPPORTPATH.</span></p>\n<b><span lang=\"EN-US\" style=\n'font-size:13.0pt;line-height:115%;font-family:\"Cambria\",\"serif\"; color:#4F81BD'><br clear=\"all\"\nstyle='page-break-before:always'></span></b></div>\n</body>\n</html>\n"
},
{
"alpha_fraction": 0.5738950371742249,
"alphanum_fraction": 0.5786910057067871,
"avg_line_length": 40.02083206176758,
"blob_id": "a188a7ad40dc3c9c4bbb1056d6b1e7acef3a7603",
"content_id": "948eab266760095c6ab406216e981b2b927ac108",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 53194,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 1296,
"path": "/qad_textwindow.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire la finestra testuale\n \n -------------------\n begin : 2014-09-21\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport sys\nimport string\nimport difflib\n\n\nfrom qad_ui_textwindow import Ui_QadTextWindow, Ui_QadCmdSuggestWindow\nfrom qad_msg import QadMsg\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_variables import QadVariables\n\n\n#===============================================================================\n# QadInputTypeEnum class.\n#===============================================================================\nclass QadInputTypeEnum():\n NONE = 0 # nessuno\n COMMAND = 1 # nome di un comando\n POINT2D = 2 # punto \n POINT3D = 4 # punto \n KEYWORDS = 8 # una parola chiave\n STRING = 16 # una stringa\n INT = 32 # un numero intero\n LONG = 64 # un numero intero\n FLOAT = 128 # un numero reale\n BOOL = 256 # un valore booleano\n ANGLE = 512 # un valore reale in gradi\n\n\n#===============================================================================\n# QadInputModeEnum class.\n#===============================================================================\nclass QadInputModeEnum():\n NONE = 0\n NOT_NULL = 1 # inserimento nullo non permesso\n NOT_ZERO = 2 # valore zero non permesso \n NOT_NEGATIVE = 4 # valore negativo non permesso \n NOT_POSITIVE = 8 # valore positivo non permesso \n\n \n#===============================================================================\n# QadCmdOptionPos\n#===============================================================================\nclass QadCmdOptionPos(): \n def __init__(self, name = \"\", initialPos = 0, finalPos = 0):\n self.name = name\n self.initialPos = initialPos\n self.finalPos = finalPos\n \n def isSelected(self, pos):\n return True if pos >= self.initialPos and pos <= self.finalPos else False\n\n\n#===============================================================================\n# QadTextWindow\n#===============================================================================\nclass QadTextWindow(QDockWidget, Ui_QadTextWindow, object):\n \"\"\"This class \n \"\"\"\n \n def __init__(self, plugin):\n \"\"\"The constructor.\"\"\"\n\n QDockWidget.__init__(self, None)\n self.setupUi(self)\n self.setAllowedAreas(Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)\n self.plugin = plugin\n self.cmdSuggestWindow = None\n self.connect(self, SIGNAL(\"topLevelChanged(bool)\"), self.topLevelChanged)\n\n title = self.windowTitle()\n self.setWindowTitle(title + \" - \" + plugin.version())\n \n def initGui(self):\n self.chronologyEdit = QadChronologyEdit(self)\n self.chronologyEdit.setObjectName(\"QadChronologyEdit\")\n \n self.edit = QadEdit(self, self.chronologyEdit)\n self.edit.setObjectName(\"QadTextEdit\")\n \n self.edit.displayPrompt(QadMsg.translate(\"QAD\", \"Command: \"))\n \n # Creo la finestra per il suggerimento dei comandi\n # lista composta da elementi con:\n # <nome locale comando>, <nome inglese comando>, <icona>, <note>\n infoCmds = []\n for cmdName in self.getCommandNames():\n cmd = self.getCommandObj(cmdName[0])\n if cmd is not None:\n infoCmds.append([cmdName[0], cmd.getEnglishName(), cmd.getIcon(), cmd.getNote()])\n \n # Creo la finestra per il suggerimento delle variabili di ambiente\n # lista composta da elementi con:\n # <nome variabile>, \"\", <icona>, <note>\n infoVars = []\n icon = QIcon(\":/plugins/qad/icons/variable.png\")\n for varName in QadVariables.getVarNames():\n var = QadVariables.getVariable(varName)\n infoVars.append([varName, \"\", icon, var.descr])\n\n self.cmdSuggestWindow = QadCmdSuggestWindow(self, infoCmds, infoVars)\n self.cmdSuggestWindow.initGui()\n self.cmdSuggestWindow.show(False)\n\n\n def getDockWidgetArea(self):\n return self.parentWidget().dockWidgetArea(self)\n \n def setFocus(self):\n self.edit.setFocus()\n \n def keyPressEvent(self, e):\n self.edit.keyPressEvent(e)\n\n def topLevelChanged(self, topLevel):\n self.resizeEdits\n self.setFocus()\n \n def toggleShow(self):\n if self.isVisible():\n self.hide()\n else:\n self.show()\n \n def showMsg(self, msg, displayPromptAfterMsg = False, append = True):\n self.edit.showMsg(msg, displayPromptAfterMsg, append)\n\n def showInputMsg(self, inputMsg = None, inputType = QadInputTypeEnum.COMMAND, \\\n default = None, keyWords = \"\", inputMode = QadInputModeEnum.NONE):\n # il valore di default del parametro di una funzione non può essere una traduzione\n # perché lupdate.exe non lo riesce ad interpretare\n self.edit.showInputMsg(inputMsg, inputType, default, keyWords, inputMode)\n\n def showErr(self, err):\n self.showMsg(err, True) # ripete il prompt\n\n def showMsgOnChronologyEdit(self, msg):\n if self.chronologyEdit is not None:\n self.chronologyEdit.insertText(msg)\n\n def showCmdSuggestWindow(self, mode = True, filter = \"\"):\n if self.cmdSuggestWindow is not None:\n inputSearchOptions = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\"))\n # inputSearchOptions & 1 = Turns on all automated keyboard features when typing at the Command prompt\n # inputSearchOptions & 4 = Displays a list of suggestions as keystrokes are entered\n if inputSearchOptions & 1 and inputSearchOptions & 4:\n self.cmdSuggestWindow.show(mode, filter)\n else:\n self.cmdSuggestWindow.show(False)\n\n \n def showEvaluateMsg(self, msg = None):\n self.edit.showEvaluateMsg(msg)\n\n def getCurrMsg(self):\n return self.edit.getCurrMsg()\n\n def getHistory(self):\n return self.edit.history # list\n\n def updateHistory(self, command):\n return self.edit.updateHistory(command)\n \n def runCommand(self, cmd):\n self.plugin.runCommand(cmd) \n \n def continueCommand(self, cmd):\n self.plugin.continueCommandFromTextWindow(cmd) \n \n def abortCommand(self):\n self.plugin.abortCommand() \n\n def clearCurrentObjsSelection(self):\n self.plugin.clearCurrentObjsSelection()\n\n def isValidCommand(self, cmd):\n return self.plugin.isValidCommand(cmd)\n\n def getCommandNames(self):\n return self.plugin.getCommandNames()\n\n def getCommandObj(self, cmdName):\n return self.plugin.getCommandObj(cmdName)\n\n def isValidEnvVariable(self, variable):\n return self.plugin.isValidEnvVariable(variable)\n\n def forceCommandMapToolSnapTypeOnce(self, snapType, snapParams = None):\n return self.plugin.forceCommandMapToolSnapTypeOnce(snapType, snapParams) \n\n def toggleOsMode(self):\n return self.plugin.toggleOsMode() \n\n def toggleOrthoMode(self):\n return self.plugin.toggleOrthoMode() \n\n def togglePolarMode(self):\n return self.plugin.togglePolarMode() \n\n def getLastPoint(self):\n return self.plugin.lastPoint\n\n def setLastPoint(self, pt):\n return self.plugin.setLastPoint(pt)\n\n def getCurrenPointFromCommandMapTool(self):\n return self.plugin.getCurrenPointFromCommandMapTool()\n\n def resizeEdits(self):\n if self.edit is None or self.chronologyEdit is None:\n return\n \n rect = self.rect()\n h = rect.height()\n w = rect.width()\n \n editHeight = self.edit.getOptimalHeight()\n if editHeight > h:\n editHeight = h\n chronologyEditHeight = h - editHeight\n if not self.isFloating():\n offsetY = 20\n chronologyEditHeight = chronologyEditHeight - offsetY\n else: \n offsetY = 0\n \n if chronologyEditHeight < 0:\n chronologyEditHeight = 0\n \n self.chronologyEdit.move(0, offsetY)\n self.chronologyEdit.resize(w, chronologyEditHeight) \n self.chronologyEdit.ensureCursorVisible()\n \n self.edit.resize(w, editHeight)\n self.edit.move(0, chronologyEditHeight + offsetY)\n self.edit.ensureCursorVisible()\n \n\n def resizeEvent(self, e):\n if self:\n self.resizeEdits()\n self.cmdSuggestWindow.resizeEvent(e)\n \n#===============================================================================\n# QadChronologyEdit\n#===============================================================================\nclass QadChronologyEdit(QTextEdit):\n \n def __init__(self, parent):\n QTextEdit.__init__(self, parent)\n \n self.set_Colors()\n self.setReadOnly(True)\n self.setMinimumSize(0, 1)\n \n def set_Colors(self, foregroundColor = Qt.black, backGroundColor = Qt.lightGray):\n p = self.palette()\n p.setColor(QPalette.Base, backGroundColor)\n self.setPalette(p)\n self.setTextColor(foregroundColor)\n self.setTextBackgroundColor(backGroundColor) \n\n def insertText(self, txt):\n cursor = self.textCursor()\n for line in txt.split('\\n'):\n if len(line) > 0: # to avoid one more empty line \n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) # fine documento\n self.setTextCursor(cursor)\n self.insertPlainText('\\n' + line)\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) # fine documento\n self.setTextCursor(cursor)\n self.ensureCursorVisible()\n \n \n#===============================================================================\n# QadEdit\n#===============================================================================\nclass QadEdit(QTextEdit):\n PROMPT, KEY_WORDS = range(2)\n \n def __init__(self, parent, chronologyEdit):\n QTextEdit.__init__(self, parent)\n\n self.currentPrompt = \"\"\n self.currentPromptLength = 0\n\n self.inputType = QadInputTypeEnum.COMMAND\n self.default = None \n self.inputMode = QadInputModeEnum.NONE\n\n self.setTextInteractionFlags(Qt.TextEditorInteraction)\n self.setMinimumSize(30, 21)\n self.setUndoRedoEnabled(False)\n self.setAcceptRichText(False)\n self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n \n self.buffer = []\n \n self.history = []\n self.historyIndex = 0\n\n # stringa contenente le parole chiave separate da \"/\".\n # la stringa può contenere il carattere speciale \"_\" per separare le parole chiave\n # in lingua locale da quelle in inglese (es. \"Si/No/Altra opzione_Yes/No/Other option\")\n self.englishKeyWords = [] # parole chiave in inglese\n self.cmdOptionPosList = [] # lista delle posizioni delle opzioni del comando corrente\n self.currentCmdOptionPos = None\n\n self.upperKeyWordForegroundColor = Qt.blue\n self.keyWordBackGroundColor = QColor(210, 210, 210)\n self.keyWordHighlightBackGroundColor = Qt.gray\n \n self.tcf_normal = QTextCharFormat()\n self.tcf_history = QTextCharFormat()\n self.tcf_keyWord = QTextCharFormat()\n self.tcf_upperKeyWord = QTextCharFormat()\n self.tcf_highlightKeyWord = QTextCharFormat()\n self.tcf_highlightUpperKeyWord = QTextCharFormat()\n self.set_Colors()\n self.set_keyWordColors()\n\n self.setMouseTracking(True)\n QObject.connect(self, SIGNAL(\"textChanged()\"), self.onTextChanged)\n \n self.timerForCmdSuggestWindow = QTimer()\n self.timerForCmdSuggestWindow.setSingleShot(True)\n self.timerForCmdAutoComplete = QTimer()\n self.timerForCmdAutoComplete.setSingleShot(True)\n \n\n def set_Colors(self, foregroundColor = Qt.black, backGroundColor = Qt.white, history_ForegroundColor = Qt.blue, \\\n history_BackGroundColor = Qt.gray):\n self.tcf_normal.setForeground(foregroundColor) \n self.tcf_normal.setBackground(backGroundColor)\n self.tcf_normal.setFontWeight(QFont.Normal)\n \n self.tcf_history.setForeground(history_ForegroundColor) \n self.tcf_history.setBackground(history_BackGroundColor)\n self.tcf_history.setFontWeight(QFont.Normal)\n\n def set_keyWordColors(self, backGroundColor = QColor(210, 210, 210), upperKeyWord_ForegroundColor = Qt.blue, \\\n highlightKeyWord_BackGroundColor = Qt.gray):\n self.tcf_keyWord.setBackground(backGroundColor)\n self.tcf_upperKeyWord.setForeground(upperKeyWord_ForegroundColor)\n self.tcf_upperKeyWord.setBackground(backGroundColor)\n self.tcf_upperKeyWord.setFontWeight(QFont.Bold)\n \n self.tcf_highlightKeyWord.setBackground(highlightKeyWord_BackGroundColor) \n self.tcf_highlightUpperKeyWord.setForeground(upperKeyWord_ForegroundColor)\n self.tcf_highlightUpperKeyWord.setBackground(highlightKeyWord_BackGroundColor)\n self.tcf_highlightUpperKeyWord.setFontWeight(QFont.Bold)\n \n def setFormat(self, start, count, fmt): # 1-indexed\n if count == 0:\n return\n cursor = QTextCursor(self.textCursor())\n cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor) # inizio documento\n cursor.movePosition(QTextCursor.Right, QTextCursor.MoveAnchor, start)\n cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, count)\n cursor.setCharFormat(fmt);\n self.setCurrentCharFormat(self.tcf_normal)\n \n def highlightKeyWords(self):\n lastBlock = self.document().lastBlock()\n txt = lastBlock.text()\n size = len(txt)\n \n # messaggio + \"[\" + opz1 + \"/\" + opz2 + \"]\"\n i = txt.find(\"[\")\n final = txt.rfind(\"]\")\n if i >= 0 and final > i: # se ci sono opzioni\n i = i + 1\n pos = lastBlock.position() + i\n while i < final:\n if txt[i] != \"/\":\n # se c'é un'opzione corrente deve essere evidenziata in modo diverso\n if self.currentCmdOptionPos is not None and \\\n pos >= self.currentCmdOptionPos.initialPos and \\\n pos <= self.currentCmdOptionPos.finalPos : \n if txt[i].isupper():\n self.setFormat(pos, 1, self.tcf_highlightUpperKeyWord)\n else:\n self.setFormat(pos, 1, self.tcf_highlightKeyWord) \n else:\n if txt[i].isupper():\n self.setFormat(pos, 1, self.tcf_upperKeyWord)\n else:\n self.setFormat(pos, 1, self.tcf_keyWord) \n i = i + 1\n pos = pos + 1\n \n \n def isCursorInEditionZone(self, newPos = None):\n cursor = self.textCursor()\n if newPos is None:\n pos = cursor.position()\n else:\n pos = newPos\n block = self.document().lastBlock()\n last = block.position() + self.currentPromptLength\n return pos >= last\n\n def currentCommand(self):\n block = self.textCursor().block()\n text = block.text()\n return text[self.currentPromptLength:]\n\n \n def getTextUntilPrompt(self):\n cursor = self.textCursor()\n text = cursor.block().text()\n return text[self.currentPromptLength : cursor.position()]\n \n def showMsgOnChronologyEdit(self, msg):\n self.parentWidget().showMsgOnChronologyEdit(msg) \n\n def showCmdSuggestWindow(self, mode = True, filter = \"\"):\n if mode == False: # se spengo la finestra\n self.timerForCmdSuggestWindow.stop()\n self.parentWidget().showCmdSuggestWindow(mode, filter)\n\n def showCmdAutoComplete(self, filter = \"\"):\n # autocompletamento\n self.timerForCmdAutoComplete.stop()\n \n # autocompletamento\n inputSearchOptions = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\"))\n filterLen = len(filter)\n if filterLen < 2:\n return\n # inputSearchOptions & 2 = Automatically appends suggestions as each keystroke is entered after the second keystroke.\n if inputSearchOptions & 2:\n if filterLen >= 2:\n cmdName, qty = self.parentWidget().plugin.getMoreUsedCmd(filter)\n else:\n cmdName = \"\"\n\n cursor = self.textCursor()\n cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)\n self.setTextCursor(cursor)\n if filterLen < len(cmdName): # se c'è qualcosa da aggiungere\n self.insertPlainText(cmdName[filterLen:])\n else:\n self.insertPlainText(\"\")\n #cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(cmdName) - filterLen)\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)\n cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor, len(cmdName) - filterLen)\n self.setTextCursor(cursor)\n \n \n \n \n \n \n \n \n\n def showMsg(self, msg, displayPromptAfterMsg = False, append = True):\n if len(msg) > 0:\n cursor = self.textCursor()\n sep = msg.rfind(\"\\n\")\n if sep >= 0:\n self.showMsgOnChronologyEdit(self.toPlainText() + msg[0:sep])\n newMsg = msg[sep + 1:]\n cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)\n cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)\n else:\n if append == True:\n cursor = self.textCursor()\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor) # fine documento\n newMsg = msg\n else:\n cursor.movePosition(QTextCursor.Start, QTextCursor.MoveAnchor)\n cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)\n newMsg = self.currentPrompt + msg\n\n self.setTextCursor(cursor)\n self.insertPlainText(newMsg) \n\n if self.inputType & QadInputTypeEnum.KEYWORDS: \n self.textCursor().block().setUserState(QadEdit.KEY_WORDS)\n self.setCmdOptionPosList() # inizializzo la lista delle posizioni delle keyWords\n self.highlightKeyWords()\n else: \n self.textCursor().block().setUserState(QadEdit.PROMPT)\n del self.cmdOptionPosList[:] # svuoto la lista delle posizioni delle keyWords\n \n if displayPromptAfterMsg:\n self.displayPrompt() # ripete il prompt\n\n\n def displayPrompt(self, prompt = None):\n if prompt is not None:\n self.currentPrompt = prompt \n self.currentPromptLength = len(self.currentPrompt) \n self.showMsg(\"\\n\" + self.currentPrompt)\n\n def displayKeyWordsPrompt(self, prompt = None):\n if prompt is not None:\n self.currentPrompt = prompt\n self.currentPromptLength = len(self.currentPrompt)\n self.showMsg(\"\\n\" + self.currentPrompt)\n \n def showNext(self):\n if self.historyIndex < len(self.history) and len(self.history) > 0:\n self.historyIndex += 1\n if self.historyIndex < len(self.history):\n # displayPromptAfterMsg = False, append = True\n self.showMsg(self.history[self.historyIndex], False, False) # sostituisce il testo dopo il prompt\n \n def showPrevious(self):\n if self.historyIndex > 0 and len(self.history) > 0:\n self.historyIndex -= 1\n if self.historyIndex < len(self.history):\n # displayPromptAfterMsg = False, append = True\n self.showMsg(self.history[self.historyIndex], False, False) # sostituisce il testo dopo il prompt\n \n def showLast(self):\n if len(self.history) > 0:\n self.showMsg(self.history[len(self.history) - 1])\n return self.history[len(self.history) - 1]\n else:\n return \"\"\n\n def showInputMsg(self, inputMsg = None, inputType = QadInputTypeEnum.COMMAND, \\\n default = None, keyWords = \"\", inputMode = QadInputModeEnum.NONE): \n # il valore di default del parametro di una funzione non può essere una traduzione\n # perché lupdate.exe non lo riesce ad interpretare\n if inputMsg is None: \n inputMsg = QadMsg.translate(\"QAD\", \"Command: \")\n\n cursor = self.textCursor()\n actualPos = cursor.position()\n \n self.inputType = inputType\n self.default = default\n self.inputMode = inputMode\n if inputType & QadInputTypeEnum.KEYWORDS and (keyWords is not None):\n # carattere separatore tra le parole chiave in lingua locale e quelle in inglese \n localEnglishKeyWords = keyWords.split(\"_\")\n self.keyWords = localEnglishKeyWords[0].split(\"/\") # carattere separatore delle parole chiave\n if len(localEnglishKeyWords) > 1:\n self.englishKeyWords = localEnglishKeyWords[1].split(\"/\") # carattere separatore delle parole chiave\n else:\n del self.englishKeyWords[:]\n self.displayKeyWordsPrompt(inputMsg)\n else:\n self.displayPrompt(inputMsg)\n \n return\n\n def setCmdOptionPosList(self):\n del self.cmdOptionPosList[:] # svuoto la lista\n lenKeyWords = len(self.keyWords)\n if lenKeyWords == 0 or len(self.currentPrompt) == 0:\n return\n # le opzioni sono racchiuse in parentesi quadre e separate tra loro da /\n prompt = self.currentPrompt\n initialPos = prompt.find(\"[\", 0)\n finalDelimiter = prompt.find(\"]\", initialPos)\n if initialPos == -1 or finalDelimiter == -1:\n return\n i = 0\n while i < lenKeyWords:\n keyWord = self.keyWords[i]\n initialPos = prompt.find(keyWord, initialPos + 1, finalDelimiter)\n if initialPos >= 0:\n finalPos = initialPos + len(keyWord)\n self.cmdOptionPosList.append(QadCmdOptionPos(keyWord, initialPos, finalPos)) \n initialPos = prompt.find(\"/\", finalPos)\n if initialPos == -1:\n return\n \n i = i + 1\n\n def getCmdOptionPosUnderMouse(self, pos):\n cursor = self.cursorForPosition(pos)\n pos = cursor.position()\n for cmdOptionPos in self.cmdOptionPosList:\n if cmdOptionPos.isSelected(pos):\n return cmdOptionPos\n return None\n\n def mouseMoveEvent(self, event):\n self.currentCmdOptionPos = self.getCmdOptionPosUnderMouse(event.pos())\n self.highlightKeyWords()\n self.currentCmdOptionPos = None\n \n def mouseDoubleClickEvent(self, event):\n cursor = self.cursorForPosition(event.pos())\n pos = cursor.position()\n if self.isCursorInEditionZone(pos):\n QTextEdit.mouseDoubleClickEvent(self, event)\n \n def mousePressEvent(self, event):\n cursor = self.cursorForPosition(event.pos())\n pos = cursor.position()\n if self.isCursorInEditionZone(pos):\n QTextEdit.mousePressEvent(self, event)\n \n def mouseReleaseEvent(self, event):\n # se sono sull'ultima riga \n if self.textCursor().position() >= self.document().lastBlock().position():\n if event.button() == Qt.LeftButton:\n cmdOptionPos = self.getCmdOptionPosUnderMouse(event.pos())\n if cmdOptionPos is not None:\n self.showEvaluateMsg(cmdOptionPos.name, False)\n \n def updateHistory(self, command):\n # Se command é una lista di comandi\n if isinstance(command, list):\n for line in command:\n self.updateHistory(line)\n elif not command == \"\":\n # se lo storico é vuoto o se il comando da inserire é diverso dall'ultimo\n if len(self.history) <= 0 or command != self.history[-1]: \n self.history.append(command)\n \n self.historyIndex = len(self.history)\n\n\n def keyPressEvent(self, e):\n cursor = self.textCursor()\n\n if self.inputType & QadInputTypeEnum.COMMAND: # nascondo la finestra di suggerimento\n self.showCmdSuggestWindow(False)\n\n #QMessageBox.warning(self.plugIn.TextWindow, \"titolo\" , 'msg')\n\n # Se é stato premuto il tasto CTRL (o META) + 9\n if ((e.modifiers() & Qt.ControlModifier) or (e.modifiers() & Qt.MetaModifier)) and \\\n e.key() == Qt.Key_9:\n # Accendo o spengo la finestra di testo\n self.parentWidget().toggleShow()\n return\n\n # Se é stato premuto il tasto F10\n if e.key() == Qt.Key_F10:\n # Attivo o disattivo il modo polare\n self.parentWidget().togglePolarMode()\n return\n\n # Se é stato premuto il tasto F3\n if e.key() == Qt.Key_F3:\n # Attivo o disattivo lo snap\n self.parentWidget().toggleOsMode()\n return\n\n # Se é stato premuto il tasto F8\n if e.key() == Qt.Key_F8:\n # Attivo o disattivo la modalità ortogonale\n self.parentWidget().toggleOrthoMode()\n return\n \n if e.key() == Qt.Key_Escape:\n self.parentWidget().abortCommand()\n self.parentWidget().clearCurrentObjsSelection()\n return\n \n # if the cursor isn't in the edit zone, don't do anything except Ctrl+C\n if not self.isCursorInEditionZone():\n if e.modifiers() & Qt.ControlModifier or e.modifiers() & Qt.MetaModifier:\n if e.key() == Qt.Key_C or e.key() == Qt.Key_A:\n QTextEdit.keyPressEvent(self, e)\n else:\n # all other keystrokes get sent to the input line\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)\n self.setTextCursor(cursor)\n QTextEdit.keyPressEvent(self, e)\n \n self.setTextCursor(cursor)\n self.ensureCursorVisible()\n else:\n # if Return is pressed, then perform the commands\n if e.key() == Qt.Key_Return:\n self.entered()\n # if Space is pressed during command request or value not string request\n elif e.key() == Qt.Key_Space and \\\n (self.inputType & QadInputTypeEnum.COMMAND or not(self.inputType & QadInputTypeEnum.STRING)):\n self.entered() \n # if Up or Down is pressed\n elif e.key() == Qt.Key_Down:\n self.showNext()\n elif e.key() == Qt.Key_Up:\n self.showPrevious()\n # if backspace is pressed, delete until we get to the prompt\n elif e.key() == Qt.Key_Backspace:\n if not cursor.hasSelection() and cursor.columnNumber() == self.currentPromptLength:\n return\n QTextEdit.keyPressEvent(self, e)\n # if the left key is pressed, move left until we get to the prompt\n elif e.key() == Qt.Key_Left and cursor.position() > self.document().lastBlock().position() + self.currentPromptLength:\n anchor = QTextCursor.KeepAnchor if e.modifiers() & Qt.ShiftModifier else QTextCursor.MoveAnchor\n move = QTextCursor.WordLeft if e.modifiers() & Qt.ControlModifier or e.modifiers() & Qt.MetaModifier else QTextCursor.Left\n cursor.movePosition(move, anchor)\n # use normal operation for right key\n elif e.key() == Qt.Key_Right:\n anchor = QTextCursor.KeepAnchor if e.modifiers() & Qt.ShiftModifier else QTextCursor.MoveAnchor\n move = QTextCursor.WordRight if e.modifiers() & Qt.ControlModifier or e.modifiers() & Qt.MetaModifier else QTextCursor.Right\n cursor.movePosition(move, anchor)\n # if home is pressed, move cursor to right of prompt\n elif e.key() == Qt.Key_Home:\n anchor = QTextCursor.KeepAnchor if e.modifiers() & Qt.ShiftModifier else QTextCursor.MoveAnchor\n cursor.movePosition(QTextCursor.StartOfBlock, anchor, 1)\n cursor.movePosition(QTextCursor.Right, anchor, self.currentPromptLength)\n # use normal operation for end key\n elif e.key() == Qt.Key_End:\n anchor = QTextCursor.KeepAnchor if e.modifiers() & Qt.ShiftModifier else QTextCursor.MoveAnchor\n cursor.movePosition(QTextCursor.EndOfBlock, anchor, 1)\n # use normal operation for all remaining keys\n else:\n QTextEdit.keyPressEvent(self, e)\n\n self.setTextCursor(cursor)\n self.ensureCursorVisible()\n \n if self.inputType & QadInputTypeEnum.COMMAND:\n # leggo il tempo di ritardo in msec\n inputSearchDelay = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHDELAY\"))\n \n # lista suggerimento dei comandi simili\n currMsg = self.getCurrMsg()\n shot1 = lambda: self.showCmdSuggestWindow(True, currMsg)\n\n del self.timerForCmdSuggestWindow\n self.timerForCmdSuggestWindow = QTimer()\n self.timerForCmdSuggestWindow.setSingleShot(True)\n self.timerForCmdSuggestWindow.timeout.connect(shot1)\n self.timerForCmdSuggestWindow.start(inputSearchDelay)\n\n if e.text().isalnum(): # autocompletamento se è stato premuto un tasto alfanumerico\n self.textUntilPrompt = self.getTextUntilPrompt()\n shot2 = lambda: self.showCmdAutoComplete(self.textUntilPrompt)\n del self.timerForCmdAutoComplete\n self.timerForCmdAutoComplete = QTimer()\n self.timerForCmdAutoComplete.setSingleShot(True)\n \n self.timerForCmdAutoComplete.timeout.connect(shot2)\n self.timerForCmdAutoComplete.start(inputSearchDelay)\n\n\n def entered(self):\n if self.inputType & QadInputTypeEnum.COMMAND:\n self.showCmdSuggestWindow(False)\n \n cursor = self.textCursor()\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)\n self.setTextCursor(cursor)\n self.evaluate(unicode(self.currentCommand()))\n \n def showEvaluateMsg(self, msg = None, append = True):\n \"\"\"\n mostra e valuta il messaggio msg se diverso da None altrimenti usa il messaggio corrente\n \"\"\"\n if msg is not None:\n self.showMsg(msg, False, append)\n self.entered()\n\n def getCurrMsg(self):\n \"\"\"\n restituisce il messaggio già presente nella finestra di testo\n \"\"\"\n cursor = self.textCursor()\n prevPos = cursor.position()\n cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)\n self.setTextCursor(cursor)\n msg = unicode(self.currentCommand())\n cursor.setPosition(prevPos)\n self.setTextCursor(cursor)\n return msg\n\n\n def getInvalidInputMsg(self):\n \"\"\"\n restituisce il messaggio di input non valido\n \"\"\"\n if self.inputType & QadInputTypeEnum.POINT2D or \\\n self.inputType & QadInputTypeEnum.POINT3D:\n if self.inputType & QadInputTypeEnum.KEYWORDS and \\\n (self.inputType & QadInputTypeEnum.FLOAT or self.inputType & QadInputTypeEnum.ANGLE):\n return QadMsg.translate(\"QAD\", \"\\nEnter a point, a real number or a keyword.\\n\")\n elif self.inputType & QadInputTypeEnum.KEYWORDS:\n return QadMsg.translate(\"QAD\", \"\\nEnter a point or a keyword.\\n\")\n elif self.inputType & QadInputTypeEnum.FLOAT or self.inputType & QadInputTypeEnum.ANGLE:\n return QadMsg.translate(\"QAD\", \"\\nEnter a point or a real number.\\n\")\n else:\n return QadMsg.translate(\"QAD\", \"\\nPoint not valid.\\n\") \n elif self.inputType & QadInputTypeEnum.KEYWORDS:\n return QadMsg.translate(\"QAD\", \"\\nKeyword not valid.\\n\")\n elif self.inputType & QadInputTypeEnum.STRING:\n return QadMsg.translate(\"QAD\", \"\\nString not valid.\\n\")\n elif self.inputType & QadInputTypeEnum.INT:\n return QadMsg.translate(\"QAD\", \"\\nInteger number not valid.\\n\")\n elif self.inputType & QadInputTypeEnum.LONG:\n return QadMsg.translate(\"QAD\", \"\\nLong integer number not valid.\\n\")\n elif self.inputType & QadInputTypeEnum.FLOAT or self.inputType & QadInputTypeEnum.ANGLE:\n return QadMsg.translate(\"QAD\", \"\\nReal number not valid.\\n\")\n elif self.inputType & QadInputTypeEnum.BOOL:\n return QadMsg.translate(\"QAD\", \"\\nBoolean not valid.\\n\")\n else:\n return \"\"\n \n\n def __evaluateKeyWords(self, cmd, keyWordList):\n # The required portion of the keyword is specified in uppercase characters, \n # and the remainder of the keyword is specified in lowercase characters.\n # The uppercase abbreviation can be anywhere in the keyword\n if cmd == \"\": # se cmd = \"\" la funzione find ritorna 0 (no comment)\n return None\n upperCmd = cmd.upper()\n selectedKeyWords = []\n for keyWord in keyWordList:\n # estraggo la parte maiuscola della parola chiave\n upperPart = \"\"\n for letter in keyWord:\n if letter.isupper():\n upperPart = upperPart + letter\n elif len(upperPart) > 0:\n break\n \n if upperPart.find(upperCmd) == 0: # se la parte maiuscola della parola chiave inizia per upperCmd\n if upperPart == upperCmd: # Se uguale\n return keyWord\n else:\n selectedKeyWords.append(keyWord)\n elif keyWord.upper().find(upperCmd) == 0: # se la parola chiave inizia per cmd (insensitive)\n if keyWord.upper() == upperCmd: # Se uguale\n return keyWord\n else:\n selectedKeyWords.append(keyWord)\n\n selectedKeyWordsLen = len(selectedKeyWords)\n if selectedKeyWordsLen == 0:\n return None\n elif selectedKeyWordsLen == 1:\n return selectedKeyWords[0]\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nAmbiguous answer: specify with greater clarity...\\n\"))\n Msg = \"\" \n for keyWord in selectedKeyWords:\n if Msg == \"\":\n Msg = keyWord\n else:\n Msg = Msg + QadMsg.translate(\"QAD\", \" or \") + keyWord\n\n Msg = Msg + QadMsg.translate(\"QAD\", \" ?\\n\")\n self.showMsg(Msg) \n \n return None\n\n def evaluateKeyWords(self, cmd):\n # The required portion of the keyword is specified in uppercase characters, \n # and the remainder of the keyword is specified in lowercase characters.\n # The uppercase abbreviation can be anywhere in the keyword\n if cmd == \"\": # se cmd = \"\" la funzione find ritorna 0 (no comment)\n return None\n \n if cmd[0] == \"_\": # versione inglese\n keyWord = self.__evaluateKeyWords(cmd[1:], self.englishKeyWords)\n if keyWord is None:\n return None\n # cerco la corrispondente parola chiave in lingua locale\n i = 0\n for k in self.englishKeyWords:\n if k == keyWord:\n return self.keyWords[i]\n i = i + 1\n return None\n else:\n return self.__evaluateKeyWords(cmd, self.keyWords)\n \n \n def evaluate(self, cmd): \n #------------------------------------------------------------------------------\n # nome di un comando\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.COMMAND:\n if cmd == \"\":\n cmd = unicode(self.showLast()) # ripeto ultimo comando\n \n if self.parentWidget().isValidCommand(cmd) or self.parentWidget().isValidEnvVariable(cmd):\n self.updateHistory(cmd)\n self.parentWidget().runCommand(cmd)\n else:\n msg = QadMsg.translate(\"QAD\", \"\\nInvalid command \\\"{0}\\\".\")\n self.showMsg(msg.format(cmd.encode('ascii','ignore')), True) # ripete il prompt\n return\n\n if cmd == \"\":\n if self.default is not None:\n if type(self.default) == QgsPoint:\n cmd = self.default.toString()\n else:\n cmd = unicode(self.default) \n \n if cmd == \"\" and \\\n not (self.inputMode & QadInputModeEnum.NOT_NULL): # permesso input nullo \n self.parentWidget().continueCommand(None) \n return\n \n #------------------------------------------------------------------------------\n # punto 2D\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.POINT2D:\n snapType = qad_utils.str2snapTypeEnum(cmd)\n if snapType != -1:\n # se é stato forzato uno snap\n snapParams = qad_utils.str2snapParams(cmd)\n self.parentWidget().forceCommandMapToolSnapTypeOnce(snapType, snapParams)\n self.showMsg(QadMsg.translate(\"QAD\", \"\\n(temporary snap)\\n\"), True) # ripeti il prompt\n return\n if (self.inputType & QadInputTypeEnum.INT) or \\\n (self.inputType & QadInputTypeEnum.LONG) or \\\n (self.inputType & QadInputTypeEnum.FLOAT) or \\\n (self.inputType & QadInputTypeEnum.ANGLE) or \\\n (self.inputType & QadInputTypeEnum.BOOL):\n oneNumberAllowed = False\n else:\n oneNumberAllowed = True\n \n pt = qad_utils.str2QgsPoint(cmd, \\\n self.parentWidget().getLastPoint(), \\\n self.parentWidget().getCurrenPointFromCommandMapTool(), \\\n oneNumberAllowed)\n \n if pt is not None:\n self.parentWidget().setLastPoint(pt)\n self.parentWidget().continueCommand(pt)\n return\n \n #------------------------------------------------------------------------------\n # punto 3D\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.POINT3D: # punto\n pass\n \n #------------------------------------------------------------------------------\n # una parola chiave\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.KEYWORDS:\n keyWord = self.evaluateKeyWords(cmd)\n \n if keyWord is not None:\n self.parentWidget().continueCommand(keyWord)\n return\n \n #------------------------------------------------------------------------------\n # una stringa\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.STRING: \n if cmd is not None: \n self.parentWidget().continueCommand(cmd)\n return \n \n #------------------------------------------------------------------------------\n # un numero intero\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.INT:\n num = qad_utils.str2int(cmd)\n if num == 0 and (self.inputMode & QadInputModeEnum.NOT_ZERO): # non permesso valore = 0 \n num = None\n elif num < 0 and (self.inputMode & QadInputModeEnum.NOT_NEGATIVE): # non permesso valore < 0 \n num = None\n elif num > 0 and (self.inputMode & QadInputModeEnum.NOT_POSITIVE): # non permesso valore > 0 \n num = None\n \n if num is not None:\n self.parentWidget().continueCommand(int(num))\n return \n \n #------------------------------------------------------------------------------\n # un numero lungo\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.LONG:\n num = qad_utils.str2long(cmd)\n if num == 0 and (self.inputMode & QadInputModeEnum.NOT_ZERO): # non permesso valore = 0 \n num = None\n elif num < 0 and (self.inputMode & QadInputModeEnum.NOT_NEGATIVE): # non permesso valore < 0 \n num = None\n elif num > 0 and (self.inputMode & QadInputModeEnum.NOT_POSITIVE): # non permesso valore > 0 \n num = None\n \n if num is not None:\n self.parentWidget().continueCommand(long(num))\n return \n \n #------------------------------------------------------------------------------\n # un numero reale\n #------------------------------------------------------------------------------ \n if self.inputType & QadInputTypeEnum.FLOAT or self.inputType & QadInputTypeEnum.ANGLE:\n num = qad_utils.str2float(cmd)\n if num == 0 and (self.inputMode & QadInputModeEnum.NOT_ZERO): # non permesso valore = 0 \n num = None\n elif num < 0 and (self.inputMode & QadInputModeEnum.NOT_NEGATIVE): # non permesso valore < 0 \n num = None\n elif num > 0 and (self.inputMode & QadInputModeEnum.NOT_POSITIVE): # non permesso valore > 0 \n num = None\n \n if num is not None:\n if self.inputType & QadInputTypeEnum.ANGLE: # se é un angolo in gradi\n # i gradi vanno convertiti in radianti\n num = qad_utils.toRadians(num) \n self.parentWidget().continueCommand(float(num)) \n return \n\n #------------------------------------------------------------------------------\n # un valore booleano\n #------------------------------------------------------------------------------ \n elif self.inputType & QadInputTypeEnum.BOOL:\n value = qad_utils.str2bool(cmd)\n \n if value is not None:\n self.parentWidget().continueCommand(value)\n return \n\n self.showMsg(self.getInvalidInputMsg())\n \n if self.inputType & QadInputTypeEnum.KEYWORDS:\n self.displayKeyWordsPrompt()\n else:\n self.displayPrompt()\n \n return\n \n def getOptimalHeight(self):\n fm = QFontMetrics(self.currentFont())\n pixelsWidth = fm.width(QadMsg.translate(\"QAD\", \"Command: \"))\n pixelsHeight = fm.height()\n # + 8 perché la QTextEdit ha un offset verticale sopra e sotto il testo\n return max(self.document().size().height(), pixelsHeight + 8)\n \n def onTextChanged(self):\n self.parentWidget().resizeEdits()\n self.timerForCmdAutoComplete.stop()\n\n \n#===============================================================================\n# QadCmdSuggestWindow\n#===============================================================================\nclass QadCmdSuggestWindow(QWidget, Ui_QadCmdSuggestWindow, object):\n \n def __init__(self, parent, infoCmds, infoVars):\n # lista composta da elementi con:\n # <nome locale comando>, <nome inglese comando>, <icona>, <note>\n QWidget.__init__(self, parent, Qt.Popup) # test\n #QWidget.__init__(self, parent, Qt.Widget) # test\n self.setupUi(self)\n self.infoCmds = infoCmds[:] # copio la lista comandi\n self.infoVars = infoVars[:] # copio la lista variabili ambiente\n \n def initGui(self):\n self.cmdNamesListView = QadCmdSuggestListView(self)\n self.cmdNamesListView.setObjectName(\"QadCmdNamesListView\")\n self.vboxlayout.addWidget(self.cmdNamesListView)\n \n def setFocus(self):\n self.cmdNamesListView.setFocus()\n \n def keyPressEvent(self, e):\n self.cmdNamesListView.keyPressEvent(e)\n\n\n def inFilteredInfoList(self, filteredInfoList, cmdName):\n for filteredInfo in filteredInfoList:\n if filteredInfo[0] == cmdName:\n return True\n return False\n\n\n def getFilteredInfoList(self, infoList, filter = \"\"):\n inputSearchOptions = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\"))\n # inputSearchOptions & 1 = Turns on all automated keyboard features when typing at the Command prompt\n # inputSearchOptions & 8 = Displays the icon of the command or system variable, if available.\n dispIcons = inputSearchOptions & 1 and inputSearchOptions & 8\n\n filteredInfoList = []\n upperFilter = filter.strip().upper()\n if len(upperFilter) > 0:\n if filter == \"*\": # se incomincia per * significa tutti i comandi in lingua locale\n # lista composta da elementi con:\n # <nome locale comando>, <nome inglese comando>, <icona>, <note>\n for info in infoList:\n if not self.inFilteredInfoList(filteredInfoList, info[0]):\n filteredInfoList.append([info[0], info[2] if dispIcons else None, info[3]])\n else:\n if upperFilter[0] == \"_\": # versione inglese \n upperFilter = upperFilter[1:]\n # lista composta da elementi con:\n # <nome locale comando>, <nome inglese comando>, <icona>, <note>\n for info in infoList:\n # se \"incomincia per\" o se \"abbastanza simile\"\n if string.find(info[1].upper(), upperFilter) == 0 or \\\n difflib.SequenceMatcher(None, info[1].upper(), upperFilter).ratio() > 0.6:\n if not self.inFilteredInfoList(filteredInfoList, \"_\" + info[1]):\n filteredInfoList.append([\"_\" + info[1], info[2] if dispIcons else None, info[3]])\n else: # versione italiana\n # lista composta da elementi con:\n # <nome locale comando>, <nome inglese comando>, <icona>, <note>\n for info in infoList:\n # se \"incomincia per\" o se \"abbastanza simile\"\n if string.find(info[0].upper(), upperFilter) == 0 or \\\n difflib.SequenceMatcher(None, info[0].upper(), upperFilter).ratio() > 0.6:\n if not self.inFilteredInfoList(filteredInfoList, info[0]):\n filteredInfoList.append([info[0], info[2] if dispIcons else None, info[3]])\n \n return filteredInfoList\n \n\n def show(self, mode = True, filter = \"\"):\n if mode == True:\n itemList = []\n itemList.extend(self.infoCmds)\n \n inputSearchOptions = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\"))\n # inputSearchOptions & 1 = Turns on all automated keyboard features when typing at the Command prompt\n # inputSearchOptions & 16 = Excludes the display of system variables\n if inputSearchOptions & 1 and (not inputSearchOptions & 16):\n itemList.extend(self.infoVars)\n\n # filtro i nomi\n filteredInfo = self.getFilteredInfoList(itemList, filter)\n\n if len(filteredInfo) == 0:\n self.setVisible(False)\n else:\n self.cmdNamesListView.set(filteredInfo)\n # seleziono il primo che incomincia per filter\n items = self.cmdNamesListView.model.findItems(filter, Qt.MatchStartsWith)\n if len(items) > 0:\n self.cmdNamesListView.setCurrentIndex(self.cmdNamesListView.model.indexFromItem(items[0]))\n \n self.moveAndResize()\n self.setVisible(True)\n else:\n self.setVisible(False)\n\n def getDataHeight(self):\n n = self.cmdNamesListView.model.rowCount()\n if n == 0:\n return 0\n\n OffSet = 4 # un pò di spazio in più per mostrare anche l'icona dei comandi\n return self.cmdNamesListView.sizeHintForRow(0) * n + OffSet\n \n\n def moveAndResize(self):\n dataHeight = self.getDataHeight()\n if dataHeight > 0:\n self.cmdNamesListView.setMinimumHeight(self.cmdNamesListView.sizeHintForRow(0))\n \n if self.parentWidget().isFloating():\n ptUp = self.parentWidget().edit.mapToGlobal(QPoint(0,0))\n spaceUp = ptUp.y() if ptUp.y() - dataHeight < 0 else dataHeight\n \n ptDown = QPoint(ptUp.x(), ptUp.y() + self.parentWidget().edit.height())\n rect = QApplication.desktop().screenGeometry()\n spaceDown = rect.height() - ptDown.y() if ptDown.y() + dataHeight > rect.height() else dataHeight\n\n # verifico se c'è più spazio sopra o sotto la finestra\n if spaceUp > spaceDown:\n pt = QPoint(ptUp.x(), ptUp.y() - spaceUp)\n dataHeight = spaceUp\n else:\n pt = QPoint(ptDown.x(), ptDown.y())\n dataHeight = spaceDown\n elif self.parentWidget().getDockWidgetArea() == Qt.BottomDockWidgetArea:\n pt = self.parentWidget().edit.mapToGlobal(QPoint(0,0))\n if pt.y() - dataHeight < 0:\n dataHeight = pt.y()\n pt.setY(pt.y() - dataHeight)\n elif self.parentWidget().getDockWidgetArea() == Qt.TopDockWidgetArea:\n pt = self.parentWidget().edit.mapToGlobal(QPoint(0,0))\n pt.setY(pt.y() + self.parentWidget().edit.height())\n rect = QApplication.desktop().screenGeometry()\n if pt.y() + dataHeight > rect.height():\n dataHeight = rect.height() - pt.y()\n\n if pt.x() < 0:\n pt.setX(0)\n \n self.move(pt)\n self.resize(200, dataHeight)\n\n def showEvaluateMsg(self, cmd = None):\n self.show(False)\n self.parentWidget().setFocus()\n self.parentWidget().showEvaluateMsg(cmd)\n\n def showMsg(self, cmd):\n # sostituisco il testo con il nuovo comando e riporto il cursore nella posizione di prima\n parent = self.parentWidget()\n cursor = parent.edit.textCursor()\n prevPos = cursor.position()\n parent.showMsg(cmd, False, False)\n cursor.setPosition(prevPos)\n parent.edit.setTextCursor(cursor)\n parent.edit.setFocus()\n self.parentWidget().setFocus()\n\n def keyPressEventToParent(self, e):\n self.parentWidget().keyPressEvent(e)\n\n\n#===============================================================================\n# QadCmdListView\n#===============================================================================\nclass QadCmdSuggestListView(QListView):\n\n def __init__(self, parent):\n QListView.__init__(self, parent)\n\n self.setViewMode(QListView.ListMode)\n self.setSelectionBehavior(QAbstractItemView.SelectItems)\n self.setUniformItemSizes(True)\n self.model = QStandardItemModel()\n self.setModel(self.model)\n \n def set(self, filteredCmdNames):\n # lista composta da elementi con <nome comando>, <icona>, <note> \n self.model.clear()\n\n for infoCmd in filteredCmdNames:\n cmdName = infoCmd[0]\n cmdIcon = infoCmd[1]\n cmdNote = infoCmd[2]\n if cmdIcon is None: \n item = QStandardItem(cmdName)\n else:\n item = QStandardItem(cmdIcon, cmdName)\n \n if cmdNote is not None and len(cmdNote) > 0:\n item.setToolTip(cmdNote)\n \n item.setEditable(False)\n self.model.appendRow(item)\n \n self.model.sort(0)\n\n\n# def selectionChanged(self, i1, i2):\n# inputSearchOptions = QadVariables.get(QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\"))\n# # inputSearchOptions & 2 = Automatically appends suggestions as each keystroke is entered after the second keystroke.\n# if inputSearchOptions & 2:\n# cmd = self.selectionModel().currentIndex().data()\n# self.parentWidget().showMsg(cmd)\n\n \n def keyPressEvent(self, e):\n if e.key() == Qt.Key_Up or e.key() == Qt.Key_Down or \\\n e.key() == Qt.Key_PageUp or e.key() == Qt.Key_PageDown or \\\n e.key() == Qt.Key_End or e.key() == Qt.Key_Home:\n QListView.keyPressEvent(self, e) \n # if Return is pressed, then perform the commands\n elif e.key() == Qt.Key_Return:\n cmd = self.selectionModel().currentIndex().data()\n if cmd is not None:\n self.parentWidget().showMsg(cmd)\n self.parentWidget().showEvaluateMsg()\n else:\n self.parentWidget().keyPressEventToParent(e)\n\n \n def mouseReleaseEvent(self, e):\n cmd = self.selectionModel().currentIndex().data()\n self.parentWidget().showMsg(cmd)\n self.parentWidget().showEvaluateMsg()\n \n"
},
{
"alpha_fraction": 0.5964757204055786,
"alphanum_fraction": 0.5992037057876587,
"avg_line_length": 39.72972869873047,
"blob_id": "2ec3d8472b98699d9d3b1d09b62bb46fca9e3952",
"content_id": "8eca08ee7664c2980067f6af8b9744c0193e6001",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13572,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 333,
"path": "/qad_pedit_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando pedit\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_rubberband import QadRubberBand\nfrom qad_highlight import QadHighlight\nfrom qad_dim import QadDimStyles\n\n\n#===============================================================================\n# Qad_pedit_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_pedit_maptool_ModeEnum():\n # si richiede la selezione di un'entità\n ASK_FOR_ENTITY_SEL = 1 \n # non si richiede niente\n NONE = 2 \n # si richiede il primo punto per calcolo distanza di approssimazione \n ASK_FOR_FIRST_TOLERANCE_PT = 3 \n # noto il primo punto per calcolo distanza di approssimazione si richiede il secondo punto\n FIRST_TOLERANCE_PT_KNOWN_ASK_FOR_SECOND_PT = 4\n # si richiede un nuovo vertice da inserire\n ASK_FOR_NEW_VERTEX = 5 \n # si richiede la nuova posizione di un vertice da spostare\n ASK_FOR_MOVE_VERTEX = 6 \n # si richiede la posizione più vicina ad un vertice\n ASK_FOR_VERTEX = 7\n # si richede il punto base (grip mode)\n ASK_FOR_BASE_PT = 8\n\n\n#===============================================================================\n# Qad_pedit_maptool class\n#===============================================================================\nclass Qad_pedit_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n\n self.firstPt = None\n self.mode = None\n \n self.layer = None\n self.linearObjectList = qad_utils.QadLinearObjectList()\n self.tolerance2ApproxCurve = None\n self.vertexAt = 0\n self.vertexPt = None\n self.after = True \n self.basePt = None\n self.__highlight = QadHighlight(self.canvas)\n\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None\n if self.basePt is not None:\n del(self.basePt)\n self.basePt = None\n\n def setLinearObjectList(self, linearObjectList, layer):\n self.linearObjectList.set(linearObjectList)\n self.layer = layer\n self.tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n\n def setVertexAt(self, vertexAt, after = None):\n if vertexAt == self.linearObjectList.qty():\n self.firstPt = self.linearObjectList.getLinearObjectAt(-1).getEndPt()\n else:\n self.firstPt = self.linearObjectList.getLinearObjectAt(vertexAt).getStartPt()\n \n self.vertexPt = QgsPoint(self.firstPt)\n self.vertexAt = vertexAt\n self.after = after \n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__highlight.reset()\n tmpLinearObjectList = None \n \n # si richiede un nuovo vertice da inserire\n if self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_NEW_VERTEX:\n if self.basePt is not None:\n offSetX = self.tmpPoint.x() - self.basePt.x()\n offSetY = self.tmpPoint.y() - self.basePt.y()\n newPt = QgsPoint(self.vertexPt.x() + offSetX, self.vertexPt.y() + offSetY)\n else:\n newPt = QgsPoint(self.tmpPoint)\n \n tmpLinearObjectList = qad_utils.QadLinearObjectList()\n tmpLinearObjectList.set(self.linearObjectList)\n if self.after: # dopo\n if self.vertexAt == tmpLinearObjectList.qty() and tmpLinearObjectList.isClosed():\n tmpLinearObjectList.insertPoint(0, newPt)\n else:\n tmpLinearObjectList.insertPoint(self.vertexAt, newPt)\n else: # prima\n if self.vertexAt == 0 and tmpLinearObjectList.isClosed():\n tmpLinearObjectList.insertPoint(tmpLinearObjectList.qty() - 1, newPt)\n else:\n tmpLinearObjectList.insertPoint(self.vertexAt - 1, newPt)\n elif self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_MOVE_VERTEX:\n newPt = QgsPoint(self.tmpPoint)\n tmpLinearObjectList = qad_utils.QadLinearObjectList()\n tmpLinearObjectList.set(self.linearObjectList) \n tmpLinearObjectList.movePoint(self.vertexAt, newPt)\n \n if tmpLinearObjectList is not None:\n pts = tmpLinearObjectList.asPolyline(self.tolerance2ApproxCurve) \n if self.layer.geometryType() == QGis.Polygon:\n geom = QgsGeometry.fromPolygon([pts])\n else:\n geom = QgsGeometry.fromPolyline(pts)\n \n # trasformo la geometria nel crs del layer\n self.__highlight.addGeometry(self.mapToLayerCoordinates(self.layer, geom), self.layer)\n \n \n def activate(self):\n QadGetPoint.activate(self)\n self.__highlight.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n \n # si richiede la selezione di un'entità\n if self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_ENTITY_SEL:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n \n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n # non si richiede niente\n elif self.mode == Qad_pedit_maptool_ModeEnum.NONE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si richiede il primo punto per calcolo distanza di approssimazione\n # si richiede la posizione più vicina ad un vertice\n elif self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_FIRST_TOLERANCE_PT:\n self.onlyEditableLayers = False\n self.checkPointLayer = True\n self.checkLineLayer = True\n self.checkPolygonLayer = True\n self.setSnapType()\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il primo punto per calcolo distanza di approssimazione si richiede il secondo punto\n elif self.mode == Qad_pedit_maptool_ModeEnum.FIRST_TOLERANCE_PT_KNOWN_ASK_FOR_SECOND_PT or \\\n self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_NEW_VERTEX or \\\n self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_MOVE_VERTEX: \n self.onlyEditableLayers = False\n self.checkPointLayer = True\n self.checkLineLayer = True\n self.checkPolygonLayer = True\n self.setSnapType()\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.firstPt)\n # si richiede la posizione più vicina ad un vertice\n elif self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_VERTEX:\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si richede il punto base (grip mode)\n elif self.mode == Qad_pedit_maptool_ModeEnum.ASK_FOR_BASE_PT:\n self.setSnapType()\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n\n\n#===============================================================================\n# Qad_gripLineToArcConvert_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_gripLineToArcConvert_maptool_ModeEnum():\n # noti il punto iniziale e finale dell'arco si richiede il punto intermedio\n START_END_PT_KNOWN_ASK_FOR_SECOND_PT = 1\n # non si richiede niente\n NONE = 2 \n\n\n#===============================================================================\n# Qad_gripLineToArcConvert_maptool class\n#===============================================================================\nclass Qad_gripLineToArcConvert_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n\n self.firstPt = None\n self.mode = None\n \n self.layer = None \n self.linearObjectList = qad_utils.QadLinearObjectList()\n self.linearObject = None\n self.startPt = None\n self.endPt = None\n self.tolerance2ApproxCurve = None\n self.__highlight = QadHighlight(self.canvas)\n\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None\n\n def setLinearObjectList(self, linearObjectList, layer, partAt):\n self.linearObjectList.set(linearObjectList)\n self.layer = layer\n self.tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n self.linearObject = self.linearObjectList.getLinearObjectAt(partAt)\n self.firstPt = self.linearObject.getMiddlePt()\n self.startPt = self.linearObject.getStartPt()\n self.endPt = self.linearObject.getEndPt()\n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__highlight.reset()\n ok = False\n \n # noti il punto iniziale e finale dell'arco si richiede il punto intermedio\n if self.mode == Qad_gripLineToArcConvert_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_SECOND_PT:\n if self.linearObject is None:\n return\n arc = QadArc()\n if arc.fromStartSecondEndPts(self.startPt, self.tmpPoint, self.endPt) == False:\n return\n if qad_utils.ptNear(self.startPt, arc.getStartPt()):\n self.linearObject.setArc(arc, False) # arco non inverso\n else:\n self.linearObject.setArc(arc, True) # arco inverso\n ok = True\n \n if ok:\n pts = self.linearObjectList.asPolyline(self.tolerance2ApproxCurve)\n if self.layer.geometryType() == QGis.Polygon:\n geom = QgsGeometry.fromPolygon([pts])\n else:\n geom = QgsGeometry.fromPolyline(pts)\n # trasformo la geometria nel crs del layer\n self.__highlight.addGeometry(self.mapToLayerCoordinates(self.layer, geom), self.layer)\n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__highlight.show()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n \n # noti il punto iniziale e finale dell'arco si richiede il punto intermedio\n if self.mode == Qad_gripLineToArcConvert_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_SECOND_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.firstPt)\n # non si richiede niente\n elif self.mode == Qad_pedit_maptool_ModeEnum.NONE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n"
},
{
"alpha_fraction": 0.5585674047470093,
"alphanum_fraction": 0.5604051351547241,
"avg_line_length": 50.32476043701172,
"blob_id": "aa2e419e27c38028f75a081f312a1dd1699bc2c8",
"content_id": "7063b405bcf2222c29c991be3cf2d0c865aa289d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 47928,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 933,
"path": "/qad_ssget_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando da inserire in altri comandi per la selezione di un gruppo di feature\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nfrom qad_entity import *\nfrom qad_dim import QadDimStyles\nfrom qad_getpoint import *\nfrom qad_pline_cmd import QadPLINECommandClass\nfrom qad_circle_cmd import QadCIRCLECommandClass\nfrom qad_mpolygon_cmd import QadMPOLYGONCommandClass\n# ho dovuto spostare in fondo questo import perché qad_mbuffer_cmd fa l'import di qad_ssget_cmd\n#from qad_mbuffer_cmd import QadMBUFFERCommandClass\nimport qad_utils\n\n\n#===============================================================================\n# QadSSGetClass\n#===============================================================================\nclass QadSSGetClass(QadCommandClass):\n# Classe che gestisce la selezione di oggetti geometrici\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadSSGetClass(self.plugIn)\n \n def __init__(self, plugIn):\n self.init(plugIn)\n\n def __del__(self):\n QadCommandClass.__del__(self)\n #self.entitySet.deselectOnLayer()\n\n def init(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.AddOnSelection = True # se = False significa remove\n self.entitySet = QadEntitySet()\n self.points = []\n self.currSelectionMode = \"\"\n # opzioni per limitare gli oggetti da selezionare\n self.onlyEditableLayers = False\n self.checkPointLayer = True\n self.checkLineLayer = True\n self.checkPolygonLayer = True\n self.checkDimLayers = True # include tutte le features che compongono le quotature selezionate\n \n self.help = False\n # se SingleSelection = True viene selezionato il primo oggetto o gruppo di oggetti indicato,\n # senza che vengano richieste altre selezioni. \n self.SingleSelection = False\n self.pickAdd = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKADD\"))\n \n # se exitAfterSelection = True il comando viene terminato dopo una qualunque selezione \n # indipendentemente che sia stato selezionato o meno un oggetto o gruppo di oggetti.\n # usato da QadVirtualSelCommandClass\n self.exitAfterSelection = False\n \n # selezione degli oggetti aggiunti più recentemente al gruppo di selezione (x opzione annulla)\n self.lastEntitySet = QadEntitySet()\n self.PLINECommand = None\n self.CIRCLECommand = None\n self.MPOLYGONCommand = None\n self.MBUFFERCommand = None\n self.SSGetClass = None\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 4: # quando si é in fase di disegno linea\n return self.PLINECommand.getPointMapTool(drawMode)\n elif self.step == 5: # quando si é in fase di disegno cerchio\n return self.CIRCLECommand.getPointMapTool(drawMode)\n elif self.step == 6: # quando si é in fase di selezione entità\n return self.SSGetClass.getPointMapTool(drawMode)\n elif self.step == 7: # quando si é in fase di disegno polygono\n return self.MPOLYGONCommand.getPointMapTool(drawMode)\n elif self.step == 8: # quando si é in fase di disegno buffer \n return self.MBUFFERCommand.getPointMapTool(drawMode) \n else:\n ptMapTool = QadCommandClass.getPointMapTool(self, drawMode)\n ptMapTool.setSnapType(QadSnapTypeEnum.DISABLE)\n ptMapTool.setOrthoMode(0)\n return ptMapTool\n\n \n #============================================================================\n # getLayersToCheck\n #============================================================================\n def getLayersToCheck(self):\n layerList = []\n for layer in self.plugIn.canvas.layers(): # Tutti i layer visibili visibili\n # considero solo i layer vettoriali che sono filtrati per tipo\n if (layer.type() == QgsMapLayer.VectorLayer) and \\\n ((layer.geometryType() == QGis.Point and self.checkPointLayer == True) or \\\n (layer.geometryType() == QGis.Line and self.checkLineLayer == True) or \\\n (layer.geometryType() == QGis.Polygon and self.checkPolygonLayer == True)) and \\\n (self.onlyEditableLayers == False or layer.isEditable()):\n # se devo includere i layers delle quotature\n if self.checkDimLayers == True or \\\n len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n return layerList\n\n\n #============================================================================\n # showMsgOnAddRemove\n #============================================================================\n def showMsgOnAddRemove(self, found):\n msg = QadMsg.translate(\"Command_SSGET\", \" found {0}, total {1}\")\n self.showMsg(msg.format(found, self.entitySet.count()), True) # ripete il prompt \n\n\n #============================================================================\n # elaborateEntity\n #============================================================================\n def elaborateEntity(self, entity, shiftKey):\n if self.AddOnSelection == True: # aggiungi al gruppo di selezione\n if shiftKey: # se la selezione é avvenuta con shift premuto\n if self.pickAdd == 0: # The objects most recently selected become the selection set\n if self.entitySet.containsEntity(entity): # se l'entità era già stata selezionata\n self.AddRemoveEntity(entity, False) # rimuovo l'entità\n else:\n self.AddRemoveEntity(entity, True) # aggiungo l'entità\n else:\n self.AddRemoveEntity(entity, False) # rimuovo l'entità\n else: # senza tasto shift\n if self.pickAdd == 0: # The objects most recently selected become the selection set\n self.SetEntity(entity)\n else:\n self.AddRemoveEntity(entity, True) # aggiungo l'entità\n else: # se si deve rimuovere dal gruppo di selezione\n self.AddRemoveEntity(entity, False) # rimuovo l'entità\n\n\n #============================================================================\n # SetEntity\n #============================================================================\n def SetEntity(self, entity):\n # controllo sul layer\n if self.onlyEditableLayers == True and entity.layer.isEditable() == False:\n self.showMsgOnAddRemove(0)\n return\n # controllo sul tipo\n if (self.checkPointLayer == False and entity.layer.geometryType() == QGis.Point) or \\\n (self.checkLineLayer == False and entity.layer.geometryType() == QGis.Line) or \\\n (self.checkPolygonLayer == False and entity.layer.geometryType() == QGis.Polygon):\n self.showMsgOnAddRemove(0)\n return\n \n # controllo su layer delle quotature\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimEntity = QadDimStyles.getDimEntity(entity)\n if self.checkDimLayers == False and dimEntity is not None:\n self.showMsgOnAddRemove(0)\n return\n\n self.entitySet.deselectOnLayer()\n self.entitySet.clear()\n self.entitySet.addEntity(entity)\n\n if self.checkDimLayers == True and dimEntity is not None:\n # Aggiungo i componenenti della quotatura a set <entitySet>\n self.entitySet.unite(dimEntity.getEntitySet())\n\n self.showMsgOnAddRemove(self.entitySet.count())\n self.entitySet.selectOnLayer(False) # incremental = False aaaaaaaaaaaaaaaaaaaaaaaaaa qui parte l'evento activate di qad_maptool\n self.lastEntitySet.clear()\n self.lastEntitySet.addEntity(entity)\n\n\n #============================================================================\n # AddRemoveEntity\n #============================================================================\n def AddRemoveEntity(self, entity, Add):\n # controllo sul layer\n if self.onlyEditableLayers == True and entity.layer.isEditable() == False:\n self.showMsgOnAddRemove(0)\n return\n # controllo sul tipo\n if (self.checkPointLayer == False and entity.layer.geometryType() == QGis.Point) or \\\n (self.checkLineLayer == False and entity.layer.geometryType() == QGis.Line) or \\\n (self.checkPolygonLayer == False and entity.layer.geometryType() == QGis.Polygon):\n self.showMsgOnAddRemove(0)\n return\n # controllo su layer delle quotature\n if self.checkDimLayers == False and len(QadDimStyles.getDimListByLayer(entity.layer)) > 0:\n self.showMsgOnAddRemove(0)\n return\n \n self.entitySet.deselectOnLayer()\n if Add == True: # aggiungi al gruppo di selezione\n self.entitySet.addEntity(entity)\n else: # rimuovi dal gruppo di selezione\n self.entitySet.removeEntity(entity)\n\n if self.checkDimLayers == True:\n dimEntitySet = QadEntitySet()\n dimEntitySet.addEntity(entity)\n # La funzione verifica se le entità che fanno parte di un entitySet sono anche parte di quotatura e,\n # in caso affermativo, aggiunge/rimuove tutti i componenti delle quotature all'entitySet.\n QadDimStyles.addAllDimComponentsToEntitySet(dimEntitySet, self.onlyEditableLayers)\n if Add == True: # aggiungi al gruppo di selezione\n self.entitySet.unite(dimEntitySet)\n else: # rimuovi dal gruppo di selezione\n self.entitySet.subtract(dimEntitySet)\n self.showMsgOnAddRemove(dimEntitySet.count())\n else:\n self.showMsgOnAddRemove(1)\n \n self.entitySet.selectOnLayer(False) # incremental = False\n self.lastEntitySet.clear()\n self.lastEntitySet.addEntity(entity)\n\n\n #============================================================================\n # elaborateSelSet\n #============================================================================\n def elaborateSelSet(self, selSet, shiftKey):\n if self.AddOnSelection == True: # aggiungi al gruppo di selezione\n if shiftKey: # se la selezione é avvenuta con shift premuto\n if self.pickAdd == 0: # The objects most recently selected become the selection set\n # verifico se ci sono degli oggetti non ancora selezionati\n intersectSS = QadEntitySet(selSet)\n intersectSS.subtract(self.entitySet)\n if intersectSS.isEmpty(): # tutti gli oggetti erano già selezionati\n self.AddRemoveSelSet(selSet, False) # rimuovo il gruppo di selezione\n else:\n self.AddRemoveSelSet(selSet, True) # aggiungo il gruppo di selezione\n else:\n self.AddRemoveSelSet(selSet, False) # rimuovo il gruppo di selezione\n else: # senza tasto shift\n if self.pickAdd == 0: # The objects most recently selected become the selection set\n self.SetSelSet(selSet)\n else:\n self.AddRemoveSelSet(selSet, True) # aggiungo il gruppo di selezione\n else: # se si deve rimuovere dal gruppo di selezione\n self.AddRemoveEntity(selSet, False) # rimuovo il gruppo di selezione\n\n \n #============================================================================\n # SetSelSet\n #============================================================================\n def SetSelSet(self, selSet):\n for layerEntitySet in self.entitySet.layerEntitySetList:\n # se il layer non é presente in selSet\n if selSet.findLayerEntitySet(layerEntitySet) is None: \n layerEntitySet.deselectOnLayer()\n else:\n layerEntitySet.deselectOnLayer()\n\n self.entitySet.set(selSet)\n \n if self.checkDimLayers == True:\n dimEntitySet = QadEntitySet(selSet)\n # La funzione verifica se le entità che fanno parte di un entitySet sono anche parte di quotatura e,\n # in caso affermativo, aggiunge tutti i componenti delle quotature all'entitySet.\n QadDimStyles.addAllDimComponentsToEntitySet(dimEntitySet, self.onlyEditableLayers)\n self.entitySet.unite(dimEntitySet)\n\n self.showMsgOnAddRemove(self.entitySet.count())\n self.entitySet.selectOnLayer(False) # incremental = False\n self.lastEntitySet.set(selSet)\n\n\n #============================================================================\n # AddCurrentQgsSelectedFeatures\n #============================================================================\n def AddCurrentQgsSelectedFeatures(self):\n # verifico se ci sono entità correntemente selezionate\n self.entitySet.initByCurrentQgsSelectedFeatures(self.getLayersToCheck())\n found = self.entitySet.count()\n if found > 0:\n msg = QadMsg.translate(\"Command_SSGET\", \"\\nfound {0}\")\n self.showMsg(msg.format(found), False) # non ripete il prompt\n return True\n else:\n return False\n\n\n #============================================================================\n # AddRemoveSelSet\n #============================================================================\n def AddRemoveSelSet(self, selSet, Add):\n self.entitySet.deselectOnLayer()\n if Add == True: # aggiungi al gruppo di selezione\n self.entitySet.unite(selSet)\n else: # rimuovi dal gruppo di selezione\n self.entitySet.subtract(selSet)\n\n self.showMsgOnAddRemove(selSet.count())\n\n self.entitySet.selectOnLayer(False) # incremental = False\n self.lastEntitySet.set(selSet)\n\n #============================================================================\n # AddRemoveSelSetByFence\n #============================================================================\n def AddRemoveSelSetByFence(self, points):\n if len(points) > 1:\n selSet = qad_utils.getSelSet(\"F\", self.getPointMapTool(), points, \\\n self.getLayersToCheck())\n self.elaborateSelSet(selSet, False)\n\n #============================================================================\n # AddRemoveSelSetByPolygon\n #============================================================================\n def AddRemoveSelSetByPolygon(self, mode, points):\n if len(points) > 2:\n selSet = qad_utils.getSelSet(mode, self.getPointMapTool(), points, \\\n self.getLayersToCheck())\n self.elaborateSelSet(selSet, False)\n\n #============================================================================\n # AddRemoveSelSetByGeometry\n #============================================================================\n def AddRemoveSelSetByGeometry(self, mode, geom):\n if type(geom) == QgsGeometry: # singola geometria\n selSet = qad_utils.getSelSet(mode, self.getPointMapTool(), geom, \\\n self.getLayersToCheck())\n else: # lista di geometrie\n selSet = QadEntitySet()\n for g in geom:\n partial = qad_utils.getSelSet(mode, self.getPointMapTool(), g, \\\n self.getLayersToCheck())\n selSet.unite(partial)\n self.elaborateSelSet(selSet, False)\n\n \n #============================================================================\n # WaitForFirstPoint\n #============================================================================\n def WaitForFirstPoint(self):\n self.step = 1\n\n # \"Finestra\" \"Ultimo\" \"Interseca\"\n # \"Riquadro\" \"Tutto\" \"iNTercetta\"\n # \"FPoligono\" \"IPoligono\"\n # \"FCerchio\" \"ICerchio\"\n # \"FOggetti\" \"IOggetti\"\n # \"FBuffer\" \"IBuffer\"\n # \"AGgiungi\" \"Elimina\"\n # \"Precedente\" \"Annulla\"\n # \"AUto\" \"SIngolo\" \"Help\"\n keyWords = QadMsg.translate(\"Command_SSGET\", \"Window\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Last\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Crossing\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Box\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"All\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Fence\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"WPolygon\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"CPolygon\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"WCircle\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"CCircle\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"WObjects\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"CObjects\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"WBuffer\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"CBuffer\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Add\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Remove\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Previous\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"AUto\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"SIngle\") + \"/\" + \\\n QadMsg.translate(\"Command_SSGET\", \"Help\")\n englishKeyWords = \"Window\" + \"/\" + \"Last\" + \"/\" + \"Crossing\" + \"/\" + \"Box\" + \"/\" \\\n + \"All\" + \"/\" + \"Fence\" + \"/\" + \"WPolygon\" + \"/\" + \"CPolygon\" + \"/\" \\\n + \"WCircle\" + \"/\" + \"CCircle\" + \"/\" + \"WObjects\" + \"/\" + \"CObjects\" + \"/\" \\\n + \"WBuffer\" + \"/\" + \"CBuffer\" + \"/\" + \"Add\" + \"/\" + \"Remove\" + \"/\" \\\n + \"Previous\" + \"/\" + \"Undo\" + \"/\" + \"AUto\" + \"/\" + \"SIngle\" + \"/\" + \"Help\"\n \n if self.AddOnSelection == True:\n prompt = QadMsg.translate(\"Command_SSGET\", \"Select Objects\")\n else:\n prompt = QadMsg.translate(\"Command_SSGET\", \"Remove objects\")\n \n if self.help == True: \n prompt = prompt + QadMsg.translate(\"Command_SSGET\", \" or [{0}]\").format(keyWords)\n \n prompt = prompt + QadMsg.translate(\"Command_SSGET\", \": \")\n \n # imposto il map tool\n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)\n # imposto i layer da controllare sul maptool\n self.getPointMapTool().layersToCheck = self.getLayersToCheck()\n self.points = []\n \n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n return\n\n def run(self, msgMapTool = False, msg = None):\n # ritorna:\n # True per selezione non terminata\n # False per selezione terminata\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # errore\n \n #=========================================================================\n # RICHIESTA PRIMO PUNTO PER SELEZIONE OGGETTI\n if self.step == 0:\n # if you can also select objects before you start a command\n if QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKFIRST\")) == 1:\n if self.AddCurrentQgsSelectedFeatures() == True:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True;\n self.WaitForFirstPoint()\n return False # continua\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PRIMO PUNTO PER SELEZIONE OGGETTI\n elif self.step == 1: # dopo aver atteso un punto o enter o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False # continua\n \n shiftKey = self.getPointMapTool().shiftKey\n\n # se é stata selezionata un'entità\n if self.getPointMapTool().entity.isInitialized():\n value = self.getPointMapTool().entity\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n shiftKey = False\n value = msg\n\n if value is None:\n if self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if type(value) == unicode:\n self.currSelectionMode = value\n \n if value == QadMsg.translate(\"Command_SSGET\", \"Window\") or value == \"Window\" or \\\n value == QadMsg.translate(\"Command_SSGET\", \"Crossing\") or value == \"Crossing\":\n # \"Finestra\" = Seleziona tutti gli oggetti che si trovano completamente all'interno di un rettangolo definito da due punti\n # \"Interseca\" = Seleziona gli oggetti che intersecano o si trovano all'interno di un'area definita da due punti\n # imposto il map tool\n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"First corner: \"))\n self.step = 2\n if value == QadMsg.translate(\"Command_SSGET\", \"Last\") or value == \"Last\": \n # Seleziona l'ultima entità inserita\n if self.plugIn.getLastEntity() is None:\n self.showMsgOnAddRemove(0)\n else:\n self.AddRemoveEntity(self.plugIn.getLastEntity(), self.AddOnSelection)\n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n \n if self.exitAfterSelection == True:\n return True # fine\n \n self.WaitForFirstPoint() \n elif value == QadMsg.translate(\"Command_SSGET\", \"Box\") or value == \"Box\":\n # Seleziona tutti gli oggetti che intersecano o si trovano all'interno di un rettangolo specificato da due punti.\n # Se i punti del rettangolo sono specificati da destra a sinistra, Riquadro equivale ad Interseca,\n # altrimenti é equivalente a Finestra\n # imposto il map tool\n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"First corner: \"))\n self.step = 2 \n elif value == QadMsg.translate(\"Command_SSGET\", \"All\") or value == \"All\":\n # Seleziona tutti gli oggetti \n selSet = qad_utils.getSelSet(\"X\", self.getPointMapTool(), None, \\\n self.getLayersToCheck())\n self.elaborateSelSet(selSet, False)\n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine \n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"Fence\") or value == \"Fence\":\n # Seleziona tutti gli oggetti che intersecano una polilinea\n self.PLINECommand = QadPLINECommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.PLINECommand.virtualCmd = True \n self.PLINECommand.run(msgMapTool, msg)\n self.step = 4\n elif value == QadMsg.translate(\"Command_SSGET\", \"WPolygon\") or value == \"WPolygon\" or \\\n value == QadMsg.translate(\"Command_SSGET\", \"CPolygon\") or value == \"CPolygon\":\n # \"FPoligono\" = Seleziona oggetti che si trovano completamente all'interno di un poligono definito da punti\n # \"IPoligono\" = Seleziona gli oggetti che intersecano o si trovano all'interno di un poligono definito specificando dei punti\n self.MPOLYGONCommand = QadMPOLYGONCommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.MPOLYGONCommand.virtualCmd = True\n \n if value == QadMsg.translate(\"Command_SSGET\", \"WPolygon\") or value == \"WPolygon\":\n self.MPOLYGONCommand.setRubberBandColor(None, getColorForWindowSelectionArea())\n else:\n self.MPOLYGONCommand.setRubberBandColor(None, getColorForCrossingSelectionArea())\n \n self.MPOLYGONCommand.run(msgMapTool, msg)\n self.step = 7\n elif value == QadMsg.translate(\"Command_SSGET\", \"WCircle\") or value == \"WCircle\" or \\\n value == QadMsg.translate(\"Command_SSGET\", \"CCircle\") or value == \"CCircle\":\n # \"FCerchio\" = Seleziona oggetti che si trovano completamente all'interno di un cerchio\n # \"ICerchio\" = Seleziona oggetti che intersecano o si trovano all'interno di un cerchio\n self.CIRCLECommand = QadCIRCLECommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare un cerchio\n # che non verrà salvata su un layer\n self.CIRCLECommand.virtualCmd = True\n \n if value == QadMsg.translate(\"Command_SSGET\", \"WCircle\") or value == \"WCircle\":\n self.CIRCLECommand.setRubberBandColor(None, getColorForWindowSelectionArea())\n else:\n self.CIRCLECommand.setRubberBandColor(None, getColorForCrossingSelectionArea())\n \n self.CIRCLECommand.run(msgMapTool, msg)\n self.step = 5\n elif value == QadMsg.translate(\"Command_SSGET\", \"WObjects\") or value == \"WObjects\" or \\\n value == QadMsg.translate(\"Command_SSGET\", \"CObjects\") or value == \"CObjects\":\n # \"FOggetti\" = Seleziona oggetti che si trovano completamente all'interno di oggetti da selezionare\n # \"IOggetti\" = Seleziona oggetti che intersecano o si trovano all'interno di oggetti da selezionare\n self.SSGetClass = QadSSGetClass(self.plugIn)\n self.SSGetClass.run(msgMapTool, msg)\n self.step = 6\n elif value == QadMsg.translate(\"Command_SSGET\", \"WBuffer\") or value == \"WBuffer\" or \\\n value == QadMsg.translate(\"Command_SSGET\", \"CBuffer\") or value == \"CBuffer\":\n # ho dovuto spostare questo import perché qad_mbuffer_cmd fa l'import di qad_ssget_cmd\n from qad_mbuffer_cmd import QadMBUFFERCommandClass\n \n # \"FBuffer\" = Seleziona oggetti che si trovano completamente all'interno di buffer intorno ad oggetti da selezionare\n # \"IBuffer\" = Seleziona oggetti che intersecano o si trovano all'interno di buffer intorno ad oggetti da selezionare\n self.MBUFFERCommand = QadMBUFFERCommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare un cerchio\n # che non verrà salvata su un layer\n self.MBUFFERCommand.virtualCmd = True \n \n if value == QadMsg.translate(\"Command_SSGET\", \"WBuffer\") or value == \"WBuffer\":\n self.MBUFFERCommand.setRubberBandColor(None, getColorForWindowSelectionArea())\n else:\n self.MBUFFERCommand.setRubberBandColor(None, getColorForCrossingSelectionArea())\n \n self.MBUFFERCommand.run(msgMapTool, msg)\n self.step = 8\n elif value == QadMsg.translate(\"Command_SSGET\", \"Add\") or value == \"Add\":\n # Passa al metodo Aggiungi: gli oggetti selezionati possono essere aggiunti al gruppo di selezione \n self.AddOnSelection = True\n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"Remove\") or value == \"Remove\":\n # Passa al metodo Rimuovi: gli oggetti possono essere rimossi dal gruppo di selezione\n self.AddOnSelection = False\n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"Previous\") or value == \"Previous\":\n # Seleziona il gruppo di selezione più recente\n if self.plugIn.lastEntitySet is None:\n self.showMsgOnAddRemove(0)\n else:\n entitySet = QadEntitySet()\n entitySet.set(self.plugIn.lastEntitySet)\n # controllo sul layer \n if self.onlyEditableLayers == True:\n entitySet.removeNotEditable()\n # controllo sul tipo\n if self.checkPointLayer == False:\n entitySet.removeGeomType(QGis.Point)\n if self.checkLineLayer == False:\n entitySet.removeGeomType(QGis.Line)\n if self.checkPolygonLayer == False:\n entitySet.removeGeomType(QGis.Polygon)\n # controllo sulle quotature\n if self.checkDimLayers == False:\n QadDimStyles.removeAllDimLayersFromEntitySet(entitySet)\n \n entitySet.removeNotExisting()\n self.elaborateSelSet(entitySet, False)\n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"Undo\") or value == \"Undo\":\n # Annulla la selezione dell'oggetto aggiunto più recentemente al gruppo di selezione.\n # Inverto il tipo di selezione\n prevAddOnSelection = self.AddOnSelection\n self.AddOnSelection = not self.AddOnSelection\n self.elaborateSelSet(self.lastEntitySet, False)\n # Ripristino il tipo di selezione\n self.AddOnSelection = prevAddOnSelection\n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n \n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"AUto\") or value == \"AUto\":\n # Passa alla selezione automatica: vengono selezionati gli oggetti sui quali si posiziona il puntatore.\n # Facendo clic su un'area vuota all'interno o all'esterno di un oggetto, \n # si crea il primo angolo di un rettangolo di selezione, come per il metodo Riquadro\n self.SingleSelection = False\n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"SIngle\") or value == \"SIngle\":\n # Passa al metodo Singolo: viene selezionato il primo oggetto o gruppo di oggetti indicato,\n # senza che vengano richieste altre selezioni.\n self.SingleSelection = True\n if self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine \n self.WaitForFirstPoint()\n elif value == QadMsg.translate(\"Command_SSGET\", \"Help\") or value == \"Help\":\n self.help = True\n self.WaitForFirstPoint()\n elif type(value) == QgsPoint: # se é stato inserito il punto iniziale del rettangolo\n self.currSelectionMode = QadMsg.translate(\"Command_SSGET\", \"Box\")\n self.points.append(value) \n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITYSET_SELECTION)\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_RECTANGLE)\n self.getPointMapTool().setStartPoint(value)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"Specify opposite corner: \"))\n self.step = 3\n else: # se é stata selezionata un'entità\n self.elaborateEntity(value, shiftKey)\n\n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine \n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n \n return False # continua\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL PRIMO PUNTO DEL RETTANGOLO DA OPZIONE \n # FINESTRA, INTERSECA, RIQUADRO (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n self.showMsg(QadMsg.translate(\"Command_SSGET\", \"Window not correct.\"))\n self.WaitForFirstPoint()\n return False\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n \n if type(value) == QgsPoint:\n self.points.append(value) \n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITYSET_SELECTION)\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_RECTANGLE)\n \n # cambio il colore impostato da setDrawMode\n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"Window\") or value == \"Window\":\n self.getPointMapTool().rectangleCrossingSelectionColor = self.getPointMapTool().rectangleWindowSelectionColor\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"Crossing\") or value == \"Crossing\":\n self.getPointMapTool().rectangleWindowSelectionColor = self.getPointMapTool().rectangleCrossingSelectionColor\n \n self.rectangleCrossingSelectionColor = getColorForCrossingSelectionArea()\n self.rectangleWindowSelectionColor = getColorForWindowSelectionArea()\n \n self.getPointMapTool().setStartPoint(value)\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"Specify opposite corner: \"))\n self.step = 3\n else:\n self.showMsg(QadMsg.translate(\"Command_SSGET\", \"Window not correct.\"))\n self.WaitForFirstPoint()\n\n return False # continua\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL SECONDO PUNTO DEL RETTANGOLO (da step = 1)\n elif self.step == 3: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n self.showMsg(QadMsg.translate(\"Command_SSGET\", \"Window not correct.\"))\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"Specify opposite corner: \"))\n return False\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n shiftKey = self.getPointMapTool().shiftKey\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n shiftKey = False\n value = msg\n \n if type(value) == QgsPoint:\n self.getPointMapTool().clear()\n self.points.append(value)\n \n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"Box\") or \\\n self.currSelectionMode == \"Box\":\n if self.points[0].x() < value.x():\n mode = \"W\"\n else:\n mode = \"C\"\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"Window\") or \\\n self.currSelectionMode == \"Window\": \n mode = \"W\"\n else: # \"Interseca\"\n mode = \"C\"\n \n selSet = qad_utils.getSelSet(mode, self.getPointMapTool(), self.points, \\\n self.getLayersToCheck())\n self.elaborateSelSet(selSet, shiftKey)\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n else:\n self.showMsg(QadMsg.translate(\"Command_SSGET\", \"Window not correct.\"))\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_SSGET\", \"Specify opposite corner: \"))\n\n return False # continua\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' INTERCETTA (da step = 1 o 4)\n elif self.step == 4: # dopo aver atteso un punto si riavvia il comando\n if self.PLINECommand.run(msgMapTool, msg) == True:\n self.showMsg(\"\\n\")\n self.AddRemoveSelSetByFence(self.PLINECommand.vertices)\n del self.PLINECommand\n self.PLINECommand = None\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PER MODALITA' FCERCHIO e ICERCHIO (da step = 1 o 5)\n elif self.step == 5: # dopo aver atteso un punto si riavvia il comando\n if self.CIRCLECommand.run(msgMapTool, msg) == True:\n self.showMsg(\"\\n\")\n if (self.CIRCLECommand.centerPt is not None) and \\\n (self.CIRCLECommand.radius is not None):\n circle = QadCircle()\n circle.set(self.CIRCLECommand.centerPt, self.CIRCLECommand.radius)\n points = circle.asPolyline()\n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"WCircle\") or \\\n self.currSelectionMode == \"WCircle\":\n self.AddRemoveSelSetByPolygon(\"WP\", points)\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"CCircle\") or \\\n self.currSelectionMode == \"CCircle\":\n self.AddRemoveSelSetByPolygon(\"CP\", points) \n \n del self.CIRCLECommand\n self.CIRCLECommand = None\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DI SELEZIONE DI OGGETTI PER MODALITA' FOGGETTI e IOGGETTI (da step = 1 o 6)\n elif self.step == 6: # dopo aver atteso un punto si riavvia il comando\n if self.SSGetClass.run(msgMapTool, msg) == True:\n self.showMsg(\"\\n\")\n destCRS = self.SSGetClass.getPointMapTool().canvas.mapRenderer().destinationCrs()\n geoms = self.SSGetClass.entitySet.getGeometryCollection(destCRS) # trasformo la geometria\n \n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"WObjects\") or \\\n self.currSelectionMode == \"WObjects\":\n self.AddRemoveSelSetByGeometry(\"WO\", geoms)\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"CObjects\") or \\\n self.currSelectionMode == \"CObjects\":\n self.AddRemoveSelSetByGeometry(\"CO\", geoms)\n \n del self.SSGetClass\n self.SSGetClass = None\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PER MODALITA' FPOLIGONO e IPOLIGONO (da step = 1 o 7)\n elif self.step == 7: # dopo aver atteso un punto si riavvia il comando\n if self.MPOLYGONCommand.run(msgMapTool, msg) == True:\n self.showMsg(\"\\n\") \n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"WPolygon\") or \\\n self.currSelectionMode == \"WPolygon\":\n self.AddRemoveSelSetByPolygon(\"WP\", self.MPOLYGONCommand.vertices)\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"CPolygon\") or \\\n self.currSelectionMode == \"CPolygon\":\n self.AddRemoveSelSetByPolygon(\"CP\", self.MPOLYGONCommand.vertices) \n \n del self.MPOLYGONCommand\n self.MPOLYGONCommand = None\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DI SELEZIONE DI OGGETTI PER MODALITA' FBUFFER e IBUFFER (da step = 1 o 8)\n elif self.step == 8: # dopo aver atteso un punto si riavvia il comando\n if self.MBUFFERCommand.run(msgMapTool, msg) == True:\n self.showMsg(\"\\n\")\n\n bufferGeoms = []\n for layerEntitySet in self.MBUFFERCommand.entitySet.layerEntitySetList:\n geoms = layerEntitySet.getGeometryCollection()\n width = qad_utils.distMapToLayerCoordinates(self.MBUFFERCommand.width, \\\n self.MBUFFERCommand.getPointMapTool().canvas,\\\n layerEntitySet.layer)\n for geom in geoms:\n bufferGeoms.append(geom.buffer(width, self.MBUFFERCommand.segments))\n \n if self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"WBuffer\") or \\\n self.currSelectionMode == \"WBuffer\":\n self.AddRemoveSelSetByGeometry(\"WO\", bufferGeoms)\n elif self.currSelectionMode == QadMsg.translate(\"Command_SSGET\", \"CBuffer\") or \\\n self.currSelectionMode == \"CBuffer\":\n self.AddRemoveSelSetByGeometry(\"CO\", bufferGeoms)\n \n del self.MBUFFERCommand\n self.MBUFFERCommand = None\n \n if self.SingleSelection == True and self.entitySet.count() > 0:\n self.plugIn.setLastEntitySet(self.entitySet)\n return True # fine\n\n if self.exitAfterSelection == True:\n return True # fine\n\n self.WaitForFirstPoint()\n return False"
},
{
"alpha_fraction": 0.5475510954856873,
"alphanum_fraction": 0.5496512651443481,
"avg_line_length": 35.02714157104492,
"blob_id": "08e030ab33322da8f914fc85ad43c6ce10be7088",
"content_id": "0a8f5392010c7f3d38763376826dc8e897b40e92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 25257,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 700,
"path": "/qad_layer.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n funzioni per i layer\n \n -------------------\n begin : 2013-11-15\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport re # regular expression\n\n\nfrom qad_msg import QadMsg\nimport qad_utils\n\n\n#===============================================================================\n# layerGeometryTypeToStr\n#===============================================================================\ndef layerGeometryTypeToStr(geomType):\n \"\"\"\n restituisce la stringa corrispondente al tipo di geometria del layer\n \"\"\"\n msg = \"\"\n if (type(geomType) == list or type(geomType) == tuple): # se lista di tipi\n for gType in geomType:\n if len(msg) > 0:\n msg = msg + \", \" \n msg = msg + layerGeometryTypeToStr(gType)\n else:\n if geomType == QGis.Point:\n msg = QadMsg.translate(\"QAD\", \"point\") \n elif geomType == QGis.Line: \n msg = QadMsg.translate(\"QAD\", \"line\") \n elif geomType == QGis.Polygon: \n msg = QadMsg.translate(\"QAD\", \"polygon\") \n\n return msg\n\n\n#===============================================================================\n# getCurrLayerEditable\n#===============================================================================\ndef getCurrLayerEditable(canvas, geomType = None):\n \"\"\"\n Ritorna il layer corrente se é aggiornabile e compatibile con il tipo geomType +\n eventuale messaggio di errore.\n Se <geomType> é una lista allora verifica che sia compatibile con almeno un tipo nella lista <geomType>\n altrimenti se <> None verifica che sia compatibile con il tipo <geomType>\n \"\"\"\n vLayer = canvas.currentLayer()\n if vLayer is None:\n return None, QadMsg.translate(\"QAD\", \"\\nNo current layer.\\n\")\n \n if (vLayer.type() != QgsMapLayer.VectorLayer):\n return None, QadMsg.translate(\"QAD\", \"\\nThe current layer is not a vector layer.\\n\")\n\n if geomType is not None:\n if (type(geomType) == list or type(geomType) == tuple): # se lista di tipi\n if vLayer.geometryType() not in geomType:\n errMsg = QadMsg.translate(\"QAD\", \"\\nThe geometry type of the current layer is {0} and it is not valid.\\n\")\n errMsg = errMsg + QadMsg.translate(\"QAD\", \"Admitted {1} layer type only.\\n\")\n errMsg.format(layerGeometryTypeToStr(vLayer.geometryType()), layerGeometryTypeToStr(geomType))\n return None, errMsg.format(layerGeometryTypeToStr(vLayer.geometryType()), layerGeometryTypeToStr(geomType))\n else:\n if vLayer.geometryType() != geomType:\n errMsg = QadMsg.translate(\"QAD\", \"\\nThe geometry type of the current layer is {0} and it is not valid.\\n\")\n errMsg = errMsg + QadMsg.translate(\"QAD\", \"Admitted {1} layer type only.\\n\")\n errMsg.format(layerGeometryTypeToStr(vLayer.geometryType()), layerGeometryTypeToStr(geomType))\n return None, errMsg.format(layerGeometryTypeToStr(vLayer.geometryType()), layerGeometryTypeToStr(geomType))\n\n provider = vLayer.dataProvider()\n if not (provider.capabilities() & QgsVectorDataProvider.EditingCapabilities):\n return None, QadMsg.translate(\"QAD\", \"\\nThe current layer is not editable.\\n\")\n \n if not vLayer.isEditable():\n return None, QadMsg.translate(\"QAD\", \"\\nThe current layer is not editable.\\n\")\n\n return vLayer, None\n \n\n#===============================================================================\n# addPointToLayer\n#===============================================================================\ndef addPointToLayer(plugIn, layer, point, transform = True, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge un punto ad un layer. Se il punto é già \n nel sistema di coordinate del layer allora non va trasformato se invece é nel\n sistema map-coordinate allora transform deve essere = True\n \"\"\"\n if len(points) < 2:\n return False\n \n f = QgsFeature()\n \n if transform:\n transformedPoint = plugIn.canvas.mapRenderer().mapToLayerCoordinates(layer, point)\n g = QgsGeometry.fromPoint(transformedPoint)\n else:\n g = QgsGeometry.fromPoint(point)\n\n if check_validity:\n if not g.isGeosValid():\n return False\n \n f.setGeometry(g)\n \n # Add attributefields to feature.\n fields = layer.pendingFields()\n f.setFields(fields)\n\n # assegno i valori di default\n provider = layer.dataProvider()\n for field in fields.toList():\n i = fields.indexFromName(field.name())\n f[field.name()] = provider.defaultValue(i)\n\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n\n if layer.addFeature(f, False):\n if refresh == True:\n plugIn.endEditCommand()\n plugIn.setLastEntity(layer, f.id())\n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# addLineToLayer\n#===============================================================================\ndef addLineToLayer(plugIn, layer, points, transform = True, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge una linea (lista di punti) ad un layer. Se la lista di punti é già \n nel sistema di coordinate del layer allora non va trasformata se invece é nel\n sistema map-coordinate allora transform deve essere = True\n \"\"\"\n if len(points) < 2: # almeno 2 punti\n return False\n \n f = QgsFeature()\n \n if transform:\n layerPoints = []\n for point in points:\n transformedPoint = plugIn.canvas.mapRenderer().mapToLayerCoordinates(layer, point)\n layerPoints.append(transformedPoint) \n g = QgsGeometry.fromPolyline(layerPoints)\n else:\n g = QgsGeometry.fromPolyline(points)\n\n if check_validity:\n if not g.isGeosValid():\n return False\n \n f.setGeometry(g)\n \n # Add attributefields to feature.\n fields = layer.pendingFields()\n f.setFields(fields)\n\n # assegno i valori di default\n provider = layer.dataProvider()\n for field in fields.toList():\n i = fields.indexFromName(field.name())\n f[field.name()] = provider.defaultValue(i)\n\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n\n if layer.addFeature(f, False):\n if refresh == True:\n plugIn.endEditCommand()\n plugIn.setLastEntity(layer, f.id())\n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# addPolygonToLayer\n#===============================================================================\ndef addPolygonToLayer(plugIn, layer, points, transform = True, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge un poligono (lista di punti) ad un layer. Se la lista di punti é già \n nel sistema di coordinate del layer allora non va trasformata se invece é nel\n sistema map-coordinate allora transform deve essere = True\n \"\"\"\n if len(points) < 3: # almeno 4 punti (il primo e l'ultimo sono uguali)\n return False\n \n f = QgsFeature()\n \n if transform:\n layerPoints = []\n for point in points:\n transformedPoint = plugIn.canvas.mapRenderer().mapToLayerCoordinates(layer, point)\n layerPoints.append(transformedPoint) \n g = QgsGeometry.fromPolygon([layerPoints])\n else:\n g = QgsGeometry.fromPolygon([points])\n\n if check_validity:\n if not g.isGeosValid():\n return False\n \n f.setGeometry(g)\n \n # Add attributefields to feature.\n fields = layer.pendingFields()\n f.setFields(fields)\n\n # assegno i valori di default\n provider = layer.dataProvider()\n for field in fields.toList():\n i = fields.indexFromName(field.name())\n f[field.name()] = provider.defaultValue(i)\n\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n\n if layer.addFeature(f, False):\n if refresh == True:\n plugIn.endEditCommand()\n plugIn.setLastEntity(layer, f.id())\n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# addGeomToLayer\n#===============================================================================\ndef addGeomToLayer(plugIn, layer, geom, coordTransform = None, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge una geometria ad un layer. Se la geometria é da convertire allora\n deve essere passato il parametro <coordTransform> di tipo QgsCoordinateTransform.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\" \n f = QgsFeature()\n \n g = QgsGeometry(geom)\n if coordTransform is not None:\n g.transform(coordTransform) \n\n if check_validity:\n if not g.isGeosValid():\n return False\n \n f.setGeometry(g)\n \n # Add attributefields to feature.\n fields = layer.pendingFields()\n f.setFields(fields)\n\n # assegno i valori di default\n provider = layer.dataProvider()\n for field in fields.toList():\n i = fields.indexFromName(field.name())\n f[field.name()] = provider.defaultValue(i)\n\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n\n if layer.addFeature(f, False):\n if refresh == True:\n plugIn.endEditCommand()\n plugIn.setLastEntity(layer, f.id())\n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# addGeomsToLayer\n#===============================================================================\ndef addGeomsToLayer(plugIn, layer, geoms, coordTransform = None, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge le geometrie ad un layer. Se la geometria é da convertire allora\n deve essere passato il parametro <coordTransform> di tipo QgsCoordinateTransform.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\"\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n \n for geom in geoms:\n if addGeomToLayer(plugIn, layer, geom, coordTransform, False, check_validity) == False:\n if refresh == True:\n plugIn.destroyEditCommand()\n return False\n \n if refresh == True:\n plugIn.endEditCommand()\n\n return True\n\n\n#===============================================================================\n# addFeatureToLayer\n#===============================================================================\ndef addFeatureToLayer(plugIn, layer, f, coordTransform = None, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge una feature ad un layer. Se la geometria é da convertire allora\n deve essere passato il parametro <coordTransform> di tipo QgsCoordinateTransform.\n <refresh> controlla la transazione del comando e il refresh del canvas\n \"\"\" \n \n if coordTransform is not None:\n g = QgsGeometry(f.geometry())\n g.transform(coordTransform) \n f.setGeometry(g)\n\n if check_validity:\n if not f.geometry().isGeosValid():\n return False\n \n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n\n if layer.addFeature(f, False):\n if refresh == True:\n plugIn.endEditCommand()\n \n plugIn.setLastEntity(layer, f.id())\n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# addFeaturesToLayer\n#===============================================================================\ndef addFeaturesToLayer(plugIn, layer, features, coordTransform = None, refresh = True, check_validity = False):\n \"\"\"\n Aggiunge le feature ad un layer. Se la geometria é da convertire allora\n deve essere passato il parametro <coordTransform> di tipo QgsCoordinateTransform.\n <refresh> controlla la transazione del comando e il refresh del canvas\n \"\"\"\n if refresh == True:\n plugIn.beginEditCommand(\"Feature added\", layer)\n \n for f in features:\n if addFeatureToLayer(plugIn, layer, f, coordTransform, False, check_validity) == False:\n if refresh == True:\n plugIn.destroyEditCommand()\n return False\n \n if refresh == True:\n plugIn.endEditCommand()\n \n return True\n\n\n#===============================================================================\n# updateFeatureToLayer\n#===============================================================================\ndef updateFeatureToLayer(plugIn, layer, f, refresh = True, check_validity = False):\n \"\"\"\n Aggiorna la feature ad un layer.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\" \n if check_validity:\n if not f.geometry().isGeosValid():\n return False\n \n if refresh == True:\n plugIn.beginEditCommand(\"Feature modified\", layer)\n\n if layer.updateFeature(f):\n if refresh == True:\n plugIn.endEditCommand()\n \n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# updateFeaturesToLayer\n#===============================================================================\ndef updateFeaturesToLayer(plugIn, layer, features, refresh = True, check_validity = False):\n \"\"\"\n Aggiorna le features ad un layer.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\"\n if refresh == True:\n plugIn.beginEditCommand(\"Feature modified\", layer)\n \n for f in features:\n if updateFeatureToLayer(plugIn, layer, f, False, check_validity) == False:\n if refresh == True:\n plugIn.destroyEditCommand()\n return False\n \n if refresh == True:\n plugIn.endEditCommand()\n \n return True\n\n\n#===============================================================================\n# deleteFeatureToLayer\n#===============================================================================\ndef deleteFeatureToLayer(plugIn, layer, featureId, refresh = True):\n \"\"\"\n Cancella la feature da un layer.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\" \n if refresh == True:\n plugIn.beginEditCommand(\"Feature deleted\", layer)\n\n if layer.deleteFeature(featureId):\n if refresh == True:\n plugIn.endEditCommand()\n \n result = True\n else:\n if refresh == True:\n plugIn.destroyEditCommand()\n result = False\n \n return result\n\n\n#===============================================================================\n# deleteFeaturesToLayer\n#===============================================================================\ndef deleteFeaturesToLayer(plugIn, layer, featureIds, refresh = True):\n \"\"\"\n Aggiorna le features ad un layer.\n refresh controlla la transazione del comando e il refresh del canvas\n \"\"\"\n if refresh == True:\n plugIn.beginEditCommand(\"Feature deleted\", layer)\n \n for featureId in featureIds:\n if deleteFeatureToLayer(plugIn, layer, featureId, False) == False:\n if refresh == True:\n plugIn.destroyEditCommand()\n return False\n \n if refresh == True:\n plugIn.endEditCommand()\n \n return True\n\n\n#===============================================================================\n# getLayersByName\n#===============================================================================\ndef getLayersByName(regularExprName):\n \"\"\"\n Ritorna la lista dei layer il cui nome soddisfa la regular expression di ricerca\n (per conversione da wildcards vedi la funzione wildCard2regularExpr)\n \"\"\"\n result = []\n regExprCompiled = re.compile(regularExprName)\n for layer in QgsMapLayerRegistry.instance().mapLayers().values():\n if re.match(regExprCompiled, layer.name()):\n if layer.isValid():\n result.append(layer)\n\n return result\n\n\n#===============================================================================\n# getLayerById\n#===============================================================================\ndef getLayerById(id):\n \"\"\"\n Ritorna il layer con id noto\n \"\"\"\n for layer in QgsMapLayerRegistry.instance().mapLayers().values():\n if layer.id() == id:\n return layer\n return None\n\n\n#===============================================================================\n# get_symbolRotationFieldName\n#===============================================================================\ndef get_symbolRotationFieldName(layer):\n \"\"\"\n return rotation field name (or empty string if not set or not supported by renderer) \n \"\"\"\n if (layer.type() != QgsMapLayer.VectorLayer) or (layer.geometryType() != QGis.Point):\n return \"\"\n\n try:\n expr = QgsSymbolLayerV2Utils.fieldOrExpressionToExpression(layer.rendererV2().rotationField())\n columns = expr.referencedColumns()\n return columns[0] if len(columns) == 1 else \"\"\n except:\n return \"\"\n\n\n#===============================================================================\n# get_symbolScaleFieldName\n#===============================================================================\ndef get_symbolScaleFieldName(layer):\n \"\"\"\n return symbol scale field name (or empty string if not set or not supported by renderer) \n \"\"\"\n if (layer.type() != QgsMapLayer.VectorLayer) or (layer.geometryType() != QGis.Point):\n return \"\"\n \n try:\n expr = QgsSymbolLayerV2Utils.fieldOrExpressionToExpression(layer.rendererV2().sizeScaleField())\n columns = expr.referencedColumns()\n return columns[0] if len(columns) == 1 else \"\"\n except:\n return \"\"\n \n\n\n#===============================================================================\n# isTextLayer\n#===============================================================================\ndef isTextLayer(layer):\n \"\"\"\n return True se il layer é di tipo testo \n \"\"\"\n # deve essere un VectorLayer di tipo puntuale\n if (layer.type() != QgsMapLayer.VectorLayer) or (layer.geometryType() != QGis.Point):\n return False\n # deve avere il-i simbolo-i trasparenti almeno entro il 10% \n for symbol in layer.rendererV2().symbols():\n if symbol.alpha() > 0.1: # Get alpha transparency 1 for opaque, 0 for invisible\n return False\n # deve avere etichette\n palyr = QgsPalLayerSettings()\n palyr.readFromLayer(layer)\n if palyr.enabled == False:\n return False\n \n return True\n\n\n#===============================================================================\n# isSymbolLayer\n#===============================================================================\ndef isSymbolLayer(layer):\n \"\"\"\n return True se il layer é di tipo simbolo \n \"\"\" \n # deve essere un VectorLayer di tipo puntuale\n if (layer.type() != QgsMapLayer.VectorLayer) or (layer.geometryType() != QGis.Point):\n return False\n # se la rotazione é letta da un campo ricordarsi che per i simboli la rotazione é in senso orario\n # quindi usare l'espressione 360 - <campo rotazione>\n # se non é un layer di tipo testo é di tipo simbolo\n return False if isTextLayer(layer) else True \n\n\n#============================================================================\n# INIZIO - Gestione layer temporanei di QAD\n#============================================================================\n\n\n#===============================================================================\n# createQADTempLayer\n#===============================================================================\ndef createQADTempLayer(plugIn, GeomType):\n \"\"\"\n Aggiunge tre liste di geometrie rispettivamente a tre layer temporanei di QAD (uno per tipologia di\n geometria). Se le geometrie sono da convertire allora\n deve essere passato il parametro <coordTransform> di tipo QgsCoordinateTransform.\n <epsg> = the authority identifier for this srs \n \"\"\"\n layer = None\n epsg = plugIn.iface.mapCanvas().mapRenderer().destinationCrs().authid()\n \n if GeomType == QGis.Point:\n layerName = QadMsg.translate(\"QAD\", \"QAD - Temporary points\")\n layerList = getLayersByName(qad_utils.wildCard2regularExpr(layerName))\n if len(layerList) == 0:\n layer = QgsVectorLayer(\"Point?crs=%s&index=yes\" % epsg, layerName, \"memory\")\n QgsMapLayerRegistry.instance().addMapLayers([layer], True)\n else:\n layer = layerList[0]\n elif GeomType == QGis.Line:\n layerName = QadMsg.translate(\"QAD\", \"QAD - Temporary lines\") \n layerList = getLayersByName(qad_utils.wildCard2regularExpr(layerName))\n if len(layerList) == 0:\n layer = QgsVectorLayer(\"LineString?crs=%s&index=yes\" % epsg, layerName, \"memory\")\n QgsMapLayerRegistry.instance().addMapLayers([layer], True)\n else:\n layer = layerList[0]\n elif GeomType == QGis.Polygon:\n layerName = QadMsg.translate(\"QAD\", \"QAD - Temporary polygons\") \n layerList = getLayersByName(qad_utils.wildCard2regularExpr(layerName))\n if len(layerList) == 0:\n layer = QgsVectorLayer(\"Polygon?crs=%s&index=yes\" % epsg, layerName, \"memory\")\n QgsMapLayerRegistry.instance().addMapLayers([layer], True)\n else:\n layer = layerList[0]\n\n layer.startEditing()\n return layer\n\n \n#===============================================================================\n# addGeometriesToQADTempLayers\n#===============================================================================\ndef addGeometriesToQADTempLayers(plugIn, pointGeoms = None, lineGeoms = None, polygonGeoms = None, \\\n crs = None, refresh = True):\n \"\"\"\n Aggiunge tre liste di geometrie rispettivamente a tre layer temporanei di QAD (uno per tipologia di\n geometria). Se le geometrie sono da convertire allora\n deve essere passato il parametro <csr> che definisce il sistema di coordinate delle geometrie.\n \"\"\" \n if pointGeoms is not None and len(pointGeoms) > 0:\n layer = createQADTempLayer(plugIn, QGis.Point)\n if layer is None:\n return False\n if crs is None:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, pointGeoms, None, refresh, False) == False:\n return False\n else:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, pointGeoms, QgsCoordinateTransform(crs, layer.crs()), \\\n refresh, False) == False:\n return False\n \n if lineGeoms is not None and len(lineGeoms) > 0:\n layer = createQADTempLayer(plugIn, QGis.Line)\n if layer is None:\n return False\n if crs is None:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, lineGeoms, None, refresh, False) == False:\n return False\n else:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, lineGeoms, QgsCoordinateTransform(crs, layer.crs()), \\\n refresh, False) == False:\n return False\n \n if polygonGeoms is not None and len(polygonGeoms) > 0:\n layer = createQADTempLayer(plugIn, QGis.Polygon)\n if layer is None:\n return False\n if crs is None:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, polygonGeoms, None, refresh, False) == False:\n return False\n else:\n # plugIn, layer, geoms, coordTransform , refresh, check_validity\n if addGeomsToLayer(plugIn, layer, polygonGeoms, QgsCoordinateTransform(crs, layer.crs()), \\\n refresh, False) == False:\n return False\n \n return True\n \n "
},
{
"alpha_fraction": 0.5397241115570068,
"alphanum_fraction": 0.5422254800796509,
"avg_line_length": 47.47344207763672,
"blob_id": "cc4be08a9ecb50d8a83986149ff092bb407b1837",
"content_id": "c75535c156267f17ba4bd176e756943ac4ccf987",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 42027,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 866,
"path": "/qad_stretch_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando STRETCH per stirare oggetti grafici\n \n -------------------\n begin : 2013-07-15\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_stretch_maptool import *\nfrom qad_getpoint import *\nfrom qad_textwindow import *\nfrom qad_mpolygon_cmd import QadMPOLYGONCommandClass\nfrom qad_rectangle_cmd import QadRECTANGLECommandClass\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nimport qad_utils\nimport qad_layer\nimport qad_stretch_fun\nimport qad_grip\n\n\n# Classe che gestisce il comando STRETCH\nclass QadSTRETCHCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadSTRETCHCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"STRETCH\")\n\n def getEnglishName(self):\n return \"STRETCH\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runSTRETCHCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/stretch.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_STRETCH\", \"Stretches objects.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.AddOnSelection = True # se = False significa remove\n self.points = []\n self.MPOLYGONCommand = None\n self.SSGeomList = [] # lista di entità da stirare con geom di selezione\n self.basePt = QgsPoint()\n \n def __del__(self):\n QadCommandClass.__del__(self)\n if self.MPOLYGONCommand is not None:\n del self.MPOLYGONCommand \n for SSGeom in self.SSGeomList:\n SSGeom[0].deselectOnLayer()\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 2: # quando si é in fase di disegno linea\n return self.MPOLYGONCommand.getPointMapTool(drawMode)\n else:\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_stretch_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n def stretch(self, entity, containerGeom, offSetX, offSetY, tolerance2ApproxCurve):\n # entity = entità da stirare\n # ptList = lista dei punti da stirare\n # offSetX, offSetY = spostamento da fare\n # tolerance2ApproxCurve = tolleranza per ricreare le curve\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.whatIs() == \"ENTITY\":\n stretchedGeom = entity.getGeometry()\n # controllo inserito perchè con le quote, questa viene cancellata e ricreata quindi alcuni oggetti potrebbero non esistere più\n if stretchedGeom is None: # se non c'è lo salto senza errore\n return True\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs())\n stretchedGeom.transform(coordTransform) \n # stiro la feature\n stretchedGeom = qad_stretch_fun.stretchQgsGeometry(stretchedGeom, containerGeom, \\\n offSetX, offSetY, \\\n tolerance2ApproxCurve)\n \n if stretchedGeom is not None:\n # trasformo la geometria nel crs del layer\n coordTransform = QgsCoordinateTransform(self.plugIn.canvas.mapRenderer().destinationCrs(), entity.layer.crs())\n stretchedGeom.transform(coordTransform)\n \n f = entity.getFeature()\n f.setGeometry(stretchedGeom)\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, entity.layer, f, False, False) == False:\n return False\n\n elif entity.whatIs() == \"DIMENTITY\":\n # stiro la quota\n if entity.deleteToLayers(self.plugIn) == False:\n return False \n entity.stretch(self.plugIn, containerGeom, offSetX, offSetY)\n if entity.addToLayers(self.plugIn) == False:\n return False \n \n return True\n\n\n #============================================================================\n # stretchFeatures\n #============================================================================\n def stretchFeatures(self, newPt):\n # mi ricavo un unico QadEntitySet con le entità selezionate\n entitySet = QadEntitySet()\n for SSGeom in self.SSGeomList:\n entitySet.unite(SSGeom[0])\n self.plugIn.beginEditCommand(\"Feature stretched\", entitySet.getLayerList())\n \n dimElaboratedList = [] # lista delle quotature già elaborate\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n offSetX = newPt.x() - self.basePt.x()\n offSetY = newPt.y() - self.basePt.y()\n \n entity = QadEntity()\n for SSGeom in self.SSGeomList:\n # copio entitySet\n entitySet = QadEntitySet(SSGeom[0])\n geomSel = SSGeom[1]\n\n for layerEntitySet in entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n\n for featureId in layerEntitySet.featureIds:\n entity.set(layer, featureId)\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimEntity = QadDimStyles.getDimEntity(entity) \n if dimEntity is None: \n if self.stretch(entity, geomSel, offSetX, offSetY, tolerance2ApproxCurve) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n found = False\n for dimElaborated in dimElaboratedList:\n if dimElaborated == dimEntity:\n found = True\n \n if found == False: # quota non ancora elaborata\n dimElaboratedList.append(dimEntity)\n if self.stretch(dimEntity, geomSel, offSetX, offSetY, tolerance2ApproxCurve) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n\n\n #============================================================================\n # setEntitySetGeom\n #============================================================================\n def setEntitySetGeom(self, entitySet, selGeom):\n for SSGeom in self.SSGeomList:\n SSGeom[0].deselectOnLayer()\n del self.SSGeomList[:] # svuoto la lista \n # aggiuge il gruppo di selezione con la geometria usata per la selezione\n self.SSGeomList.append([entitySet, selGeom])\n entitySet.selectOnLayer(False) # incremental = False\n\n #============================================================================\n # addEntitySetGeom\n #============================================================================\n def addEntitySetGeom(self, entitySet, selGeom): \n # elimino dai gruppi precedenti gli oggetti presenti in entitySet\n self.removeEntitySet(entitySet)\n # aggiuge il gruppo di selezione con la geometria usata per la selezione\n self.SSGeomList.append([entitySet, selGeom])\n entitySet.selectOnLayer(True) # incremental = True\n \n\n #============================================================================\n # removeEntitySet\n #============================================================================\n def removeEntitySet(self, entitySet):\n # elimino dai gruppi precedenti gli oggetti presenti in entitySet\n for SSGeom in self.SSGeomList:\n SSGeom[0].subtract(entitySet)\n for SSGeom in self.SSGeomList:\n SSGeom[0].selectOnLayer(False) # incremental = False\n\n\n #============================================================================\n # SSGeomListIsEmpty\n #============================================================================\n def SSGeomListIsEmpty(self):\n if len(self.SSGeomList) == 0:\n return True \n for SSGeom in self.SSGeomList:\n if SSGeom[0].isEmpty() == False:\n return False\n return True\n\n \n #============================================================================\n # waitForObjectSel\n #============================================================================\n def waitForObjectSel(self): \n self.step = 1 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.ASK_FOR_FIRST_PT_RECTANGLE) \n \n keyWords = QadMsg.translate(\"Command_STRETCH\", \"Polygon\") + \"/\" + \\\n QadMsg.translate(\"Command_STRETCH\", \"Add\") + \"/\" + \\\n QadMsg.translate(\"Command_STRETCH\", \"Remove\")\n\n if self.AddOnSelection == True:\n prompt = QadMsg.translate(\"Command_STRETCH\", \"Select vertices\")\n else:\n prompt = QadMsg.translate(\"Command_STRETCH\", \"Remove vertices\")\n prompt = prompt + QadMsg.translate(\"Command_STRETCH\", \" to stretch crossed by a selection window or [{0}]: \").format(keyWords) \n\n englishKeyWords = \"Polygon\" + \"/\" + \"Add\" + \"/\" + \"Remove\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n\n\n #============================================================================\n # waitForBasePt\n #============================================================================\n def waitForBasePt(self): \n self.step = 4 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT) \n \n keyWords = QadMsg.translate(\"Command_STRETCH\", \"Displacement\")\n prompt = QadMsg.translate(\"Command_STRETCH\", \"Specify base point or [{0}] <{0}>: \").format(keyWords)\n \n englishKeyWords = \"Displacement\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI\n if self.step == 0: # inizio del comando\n # si appresta ad attendere la selezione degli oggetti da stirare\n self.waitForObjectSel()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI DA STIRARE\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = None\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_STRETCH\", \"Polygon\") or value == \"Polygon\":\n # Seleziona tutti gli oggetti che sono interni al poligono\n self.MPOLYGONCommand = QadMPOLYGONCommandClass(self.plugIn)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.MPOLYGONCommand.virtualCmd = True \n self.MPOLYGONCommand.run(msgMapTool, msg)\n self.step = 2\n return False \n elif value == QadMsg.translate(\"Command_SSGET\", \"Add\") or value == \"Add\":\n # Passa al metodo Aggiungi: gli oggetti selezionati possono essere aggiunti al gruppo di selezione \n self.AddOnSelection = True\n elif value == QadMsg.translate(\"Command_SSGET\", \"Remove\") or value == \"Remove\":\n # Passa al metodo Rimuovi: gli oggetti possono essere rimossi dal gruppo di selezione\n self.AddOnSelection = False \n elif type(value) == QgsPoint: # se é stato selezionato un punto\n del self.points[:] # svuoto la lista\n self.points.append(value)\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_RECTANGLE) \n self.getPointMapTool().setStartPoint(value)\n \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_STRETCH\", \"Specify opposite corner: \"))\n self.step = 3\n return False \n else:\n if self.SSGeomListIsEmpty():\n return True\n # si appresta ad attendere il punto base o lo spostamento\n self.waitForBasePt()\n return False \n \n # si appresta ad attendere la selezione degli oggetti da stirare\n self.waitForObjectSel()\n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' POLIGONO (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto si riavvia il comando\n if self.MPOLYGONCommand.run(msgMapTool, msg) == True:\n if len(self.MPOLYGONCommand.vertices) > 1:\n # cerco tutte le geometrie intersecanti il poligono\n # e considerando solo layer editabili \n selSet = qad_utils.getSelSet(\"CP\", self.getPointMapTool(), self.MPOLYGONCommand.vertices, \\\n None, True, True, True, \\\n True)\n # se la selezione é avvenuta con shift premuto o se si deve rimuovere il gruppo selSet dal gruppo\n if self.AddOnSelection == False:\n self.removeEntitySet(selSet)\n else:\n self.setEntitySetGeom(selSet, QgsGeometry.fromPolygon([self.MPOLYGONCommand.vertices]))\n \n del self.MPOLYGONCommand\n self.MPOLYGONCommand = None\n\n # si appresta ad attendere la selezione degli oggetti da stirare\n self.waitForObjectSel() \n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di mpolygon \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO PER MODALITA' FINESTRA (da step = 1)\n elif self.step == 3: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n self.showMsg(QadMsg.translate(\"Command_STRETCH\", \"Window not correct.\"))\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_STRETCH\", \"Specify opposite corner: \"))\n return False\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n shiftKey = self.getPointMapTool().shiftKey\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n shiftKey = False\n value = msg\n\n\n if type(value) == QgsPoint:\n self.points.append(value) \n # cerco tutte le geometrie intersecanti il rettangolo\n # e considerando solo layer editabili\n selSet = qad_utils.getSelSet(\"C\", self.getPointMapTool(), self.points, \\\n None, True, True, True, \\\n True) \n # se si deve rimuovere il gruppo entitySet dal gruppo\n if self.AddOnSelection == False:\n self.removeEntitySet(selSet)\n else:\n if shiftKey: # se la selezione é avvenuta con shift premuto\n self.addEntitySetGeom(selSet, QgsGeometry.fromRect(QgsRectangle(self.points[0], self.points[1])))\n else:\n self.setEntitySetGeom(selSet, QgsGeometry.fromRect(QgsRectangle(self.points[0], self.points[1])))\n # si appresta ad attendere la selezione degli oggetti da stirare\n self.waitForObjectSel() \n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n pass # opzione di default \"spostamento\"\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n # imposto il map tool\n self.getPointMapTool().SSGeomList = self.SSGeomList\n\n if value is None or type(value) == unicode:\n self.basePt.set(0, 0)\n self.getPointMapTool().basePt = self.basePt\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT) \n # si appresta ad attendere un punto\n msg = QadMsg.translate(\"Command_STRETCH\", \"Specify the displacement from the origin point 0,0 <{0}, {1}>: \")\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(msg.format(str(self.plugIn.lastOffsetPt.x()), str(self.plugIn.lastOffsetPt.y())), \\\n QadInputTypeEnum.POINT2D, \\\n self.plugIn.lastOffsetPt, \\\n \"\", QadInputModeEnum.NONE) \n self.step = 5 \n elif type(value) == QgsPoint: # se é stato inserito il punto base\n self.basePt.set(value.x(), value.y())\n\n # imposto il map tool\n self.getPointMapTool().basePt = self.basePt\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT) \n \n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(QadMsg.translate(\"Command_STRETCH\", \"Specify second point or [Array] <use first point as displacement from origin point 0,0>: \"), \\\n QadInputTypeEnum.POINT2D, \\\n None, \\\n \"\", QadInputModeEnum.NONE) \n self.step = 6 \n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL PUNTO DI SPOSTAMENTO (da step = 2)\n elif self.step == 5: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.plugIn.setLastOffsetPt(value)\n self.stretchFeatures(value)\n return True # fine comando \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA SECONDO PUNTO PER SPOSTAMENTO (da step = 2)\n elif self.step == 6: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n newPt = QgsPoint(self.basePt.x() * 2, self.basePt.y() * 2)\n self.stretchFeatures(newPt)\n elif type(value) == QgsPoint: # se é stato inserito lo spostamento con un punto\n self.stretchFeatures(value)\n \n return True # fine comando\n\n\n\n#============================================================================\n# Classe che gestisce il comando STRETCH per i grip\n#============================================================================\nclass QadGRIPSTRETCHCommandClass(QadCommandClass):\n\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadGRIPSTRETCHCommandClass(self.plugIn)\n\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.selectedEntityGripPoints = [] # lista in cui ogni elemento è una entità + una lista di punti da stirare\n self.basePt = QgsPoint()\n self.skipToNextGripCommand = False\n self.copyEntities = False\n self.nOperationsToUndo = 0\n\n \n def __del__(self):\n QadCommandClass.__del__(self)\n\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_gripStretch_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n #============================================================================\n # addToSelectedEntityGripPoints\n #============================================================================\n def addToSelectedEntityGripPoints(self, entityGripPoints):\n # entità con lista dei grip point\n i = 0\n gripPoints = entityGripPoints.gripPoints\n gripPointsLen = len(gripPoints)\n ptList = []\n while i < gripPointsLen:\n gripPoint = gripPoints[i]\n # grip point selezionato\n if gripPoint.getStatus() == qad_grip.QadGripStatusEnum.SELECTED:\n if gripPoint.gripType == qad_grip.QadGripPointTypeEnum.CENTER:\n ptList.append(gripPoint.getPoint())\n elif gripPoint.gripType == qad_grip.QadGripPointTypeEnum.LINE_MID_POINT:\n # aggiungo il vertice precedente e successivo di quello intermedio\n if i > 0:\n ptList.append(gripPoints[i - 1].getPoint())\n if i < gripPointsLen - 1:\n ptList.append(gripPoints[i + 1].getPoint())\n elif gripPoint.gripType == qad_grip.QadGripPointTypeEnum.QUA_POINT:\n ptList.append(gripPoint.getPoint())\n elif gripPoint.gripType == qad_grip.QadGripPointTypeEnum.VERTEX or \\\n gripPoint.gripType == qad_grip.QadGripPointTypeEnum.END_VERTEX:\n ptList.append(gripPoint.getPoint())\n elif gripPoint.gripType == qad_grip.QadGripPointTypeEnum.ARC_MID_POINT:\n ptList.append(gripPoint.getPoint())\n i = i + 1\n \n if len(ptList) > 0:\n self.selectedEntityGripPoints.append([entityGripPoints.entity, ptList])\n\n \n #============================================================================\n # setSelectedEntityGripPoints\n #============================================================================\n def setSelectedEntityGripPoints(self, entitySetGripPoints):\n # lista delle entityGripPoint con dei grip point selezionati\n # ritorna una lista in cui ogni elemento è una entità + una lista di punti da stirare\n del self.selectedEntityGripPoints[:] # svuoto la lista\n\n for entityGripPoints in entitySetGripPoints.entityGripPoints:\n self.addToSelectedEntityGripPoints(entityGripPoints)\n self.getPointMapTool().selectedEntityGripPoints = self.selectedEntityGripPoints\n\n\n #============================================================================\n # getSelectedEntityGripPointNdx\n #============================================================================\n def getSelectedEntityGripPointNdx(self, entity):\n # lista delle entityGripPoint con dei grip point selezionati\n # cerca la posizione di un'entità nella lista in cui ogni elemento è una entità + una lista di punti da stirare\n i = 0\n tot = len(self.selectedEntityGripPoints)\n while i < tot:\n selectedEntityGripPoint = self.selectedEntityGripPoints[i]\n if selectedEntityGripPoint[0] == entity:\n return i\n i = i + 1\n return -1\n\n\n #============================================================================\n # stretch\n #============================================================================\n def stretch(self, entity, ptList, offSetX, offSetY, tolerance2ApproxCurve):\n # entity = entità da stirare\n # ptList = lista dei punti da stirare\n # offSetX, offSetY = spostamento da fare\n # tolerance2ApproxCurve = tolleranza per ricreare le curve\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.whatIs() == \"ENTITY\":\n stretchedGeom = entity.getGeometry()\n # controllo inserito perchè con le quote, questa viene cancellata e ricreata quindi alcuni oggetti potrebbero non esistere più\n if stretchedGeom is None: # se non c'è lo salto senza errore\n return True\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs())\n stretchedGeom.transform(coordTransform) \n # stiro la feature\n stretchedGeom = qad_stretch_fun.gripStretchQgsGeometry(stretchedGeom, self.basePt, ptList, \\\n offSetX, offSetY, \\\n tolerance2ApproxCurve)\n \n if stretchedGeom is not None:\n # trasformo la geometria nel crs del layer\n coordTransform = QgsCoordinateTransform(self.plugIn.canvas.mapRenderer().destinationCrs(), entity.layer.crs())\n stretchedGeom.transform(coordTransform)\n \n f = entity.getFeature()\n f.setGeometry(stretchedGeom)\n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, entity.layer, f, False, False) == False:\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, entity.layer, f, None, False, False) == False:\n return False\n \n elif entity.whatIs() == \"DIMENTITY\":\n # stiro la quota\n if self.copyEntities == False:\n if entity.deleteToLayers(self.plugIn) == False:\n return False \n entity.stretch(self.plugIn, ptList, offSetX, offSetY)\n if entity.addToLayers(self.plugIn) == False:\n return False \n \n return True\n\n\n #============================================================================\n # stretchFeatures\n #============================================================================\n def stretchFeatures(self, newPt):\n # mi ricavo un unico QadEntitySet con le entità selezionate\n entitySet = QadEntitySet()\n for selectedEntity in self.selectedEntityGripPoints:\n entitySet.addEntity(selectedEntity[0])\n self.plugIn.beginEditCommand(\"Feature stretched\", entitySet.getLayerList())\n \n dimElaboratedList = [] # lista delle quotature già elaborate\n \n for selectedEntity in self.selectedEntityGripPoints:\n entity = selectedEntity[0]\n ptList = selectedEntity[1]\n layer = entity.layer\n \n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n offSetX = newPt.x() - self.basePt.x()\n offSetY = newPt.y() - self.basePt.y()\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimEntity = QadDimStyles.getDimEntity(entity) \n if dimEntity is None:\n if self.stretch(entity, ptList, offSetX, offSetY, tolerance2ApproxCurve) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n found = False\n for dimElaborated in dimElaboratedList:\n if dimElaborated == dimEntity:\n found = True\n \n if found == False: # quota non ancora elaborata\n dimEntitySet = dimEntity.getEntitySet()\n # creo un'unica lista contenente i grip points di tutti i componenti della quota\n dimPtlist = []\n for layerEntitySet in dimEntitySet.layerEntitySetList:\n for featureId in layerEntitySet.featureIds:\n componentDim = QadEntity()\n componentDim.set(layerEntitySet.layer, featureId)\n i = self.getSelectedEntityGripPointNdx(componentDim)\n if i >= 0:\n dimPtlist.extend(self.selectedEntityGripPoints[i][1])\n\n dimElaboratedList.append(dimEntity)\n if self.stretch(dimEntity, dimPtlist, offSetX, offSetY, tolerance2ApproxCurve) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n \n #============================================================================\n # waitForStretchPoint\n #============================================================================\n def waitForStretchPoint(self):\n self.step = 1\n self.plugIn.setLastPoint(self.basePt)\n # imposto il map tool\n self.getPointMapTool().basePt = self.basePt\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT)\n \n keyWords = QadMsg.translate(\"Command_GRIP\", \"Base point\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Copy\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"eXit\")\n\n prompt = QadMsg.translate(\"Command_GRIPSTRETCH\", \"Specify stretch point or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Base point\" + \"/\" + \"Copy\" + \"/\" + \"Undo\" + \"/\" + \"eXit\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n\n\n #============================================================================\n # waitForBasePt\n #============================================================================\n def waitForBasePt(self):\n self.step = 2 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_stretch_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT) \n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_GRIPSTRETCH\", \"Specify base point: \"))\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTI\n if self.step == 0: # inizio del comando\n if len(self.selectedEntityGripPoints) == 0: # non ci sono oggetti da stirare\n return True\n self.showMsg(QadMsg.translate(\"Command_GRIPSTRETCH\", \"\\n** STRETCH **\\n\"))\n # si appresta ad attendere un punto di stiramento\n self.waitForStretchPoint()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DI UN PUNTO DI STIRAMENTO\n elif self.step == 1:\n ctrlKey = False\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = None\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n\n ctrlKey = self.getPointMapTool().ctrlKey\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_GRIP\", \"Base point\") or value == \"Base point\":\n # si appresta ad attendere il punto base\n self.waitForBasePt()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Copy\") or value == \"Copy\":\n # Copia entità lasciando inalterate le originali\n self.copyEntities = True \n # si appresta ad attendere un punto di stiramento\n self.waitForStretchPoint()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n # si appresta ad attendere un punto di stiramento\n self.waitForStretchPoint()\n elif value == QadMsg.translate(\"Command_GRIP\", \"eXit\") or value == \"eXit\":\n return True # fine comando\n elif type(value) == QgsPoint: # se é stato selezionato un punto\n if ctrlKey:\n self.copyEntities = True\n \n self.stretchFeatures(value)\n\n if self.copyEntities == False:\n return True\n # si appresta ad attendere un punto di stiramento\n self.waitForStretchPoint()\n \n else:\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n \n return False \n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO BASE (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n pass # opzione di default \"spostamento\"\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint: # se é stato inserito il punto base\n self.basePt.set(value.x(), value.y())\n # imposto il map tool\n self.getPointMapTool().basePt = self.basePt\n \n # si appresta ad attendere un punto di stiramento\n self.waitForStretchPoint()\n\n return False"
},
{
"alpha_fraction": 0.5717355012893677,
"alphanum_fraction": 0.5741603374481201,
"avg_line_length": 44.51210021972656,
"blob_id": "89a4960ada16352e838b9302f0f254d661d1e7b4",
"content_id": "8512773a9d430c295f53296ad364dd68013d0c57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 47053,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 1033,
"path": "/qad_lengthen_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando ALLUNGA per allungare un oggetto \n \n -------------------\n begin : 2015-10-05\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nimport qad_utils\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_getdist_cmd import QadGetDistClass\nfrom qad_getangle_cmd import QadGetAngleClass\nfrom qad_snapper import *\nfrom qad_getpoint import *\nfrom qad_lengthen_maptool import *\nfrom qad_textwindow import *\nfrom qad_msg import QadMsg\nimport qad_layer\nfrom qad_arc import *\nfrom qad_circle import *\nfrom qad_dim import QadDimStyles\nimport qad_grip\n\n\n# Classe che gestisce il comando LENGTHEN\nclass QadLENGTHENCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadLENGTHENCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"LENGTHEN\")\n\n def getEnglishName(self):\n return \"LENGTHEN\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runLENGTHENCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/lengthen.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_LENGTHEN\", \"Lengthen an object.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.OpMode = plugIn.lastOpMode_lengthen # \"DElta\" o \"Percent\" o \"Total\" o \"DYnamic\"\n self.OpType = None # \"length\" o \"Angle\"\n self.value = None \n\n self.startPt = None\n self.GetDistClass = None\n self.GetAngleClass = None\n self.entity = QadEntity()\n self.linearObjectList = None\n self.atSubGeom = None\n self.move_startPt = None\n \n self.nOperationsToUndo = 0\n\n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.GetDistClass is not None:\n del self.GetDistClass \n if self.GetAngleClass is not None:\n del self.GetAngleClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE): \n if self.step == 3: # quando si é in fase di richiesta distanza\n return self.GetDistClass.getPointMapTool()\n if self.step == 4: # quando si é in fase di richiesta angolo\n return self.GetAngleClass.getPointMapTool()\n elif (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_lengthen_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n def setInfo(self, entity, point):\n # setta: self.entity, self.linearObjectList, self.atSubGeom e self.move_startPt\n if self.linearObjectList is not None:\n del self.linearObjectList\n self.linearObjectList = None\n \n self.entity.set(entity.layer, entity.featureId)\n transformedPt = self.mapToLayerCoordinates(self.entity.layer, point)\n f = self.entity.getFeature()\n geom = self.entity.getGeometry()\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n res = False\n dummy = qad_utils.closestSegmentWithContext(transformedPt, geom)\n if dummy[2] is None:\n return False\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, self.atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2]) \n self.linearObjectList = qad_utils.QadLinearObjectList() \n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n \n if qad_utils.getDistance(self.linearObjectList.getStartPt(), transformedPt) <= \\\n qad_utils.getDistance(self.linearObjectList.getEndPt(), transformedPt):\n # si allunga dal punto iniziale\n self.move_startPt = True\n else:\n # si allunga dal punto finale\n self.move_startPt = False\n \n return True\n \n\n #============================================================================\n # lengthen\n #============================================================================\n def lengthen(self, point):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n geom = self.entity.getGeometry()\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n res = False\n if self.OpMode == \"DElta\":\n newLinearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n if self.OpType == \"length\":\n res = newLinearObjectList.lengthen_delta(self.move_startPt, self.value)\n elif self.OpType == \"Angle\":\n res = newLinearObjectList.lengthen_deltaAngle(self.move_startPt, self.value)\n elif self.OpMode == \"Percent\":\n newLinearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n value = newLinearObjectList.length() * self.value / 100\n value = value - newLinearObjectList.length()\n res = newLinearObjectList.lengthen_delta(self.move_startPt, value)\n elif self.OpMode == \"Total\":\n newLinearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n if self.OpType == \"length\":\n value = self.value - newLinearObjectList.length()\n res = newLinearObjectList.lengthen_delta(self.move_startPt, value)\n elif self.OpType == \"Angle\": \n if newLinearObjectList.qty() == 1:\n linearObject = newLinearObjectList.getLinearObjectAt(0)\n if linearObject.isArc() == True: # se è un arco\n value = self.value - linearObject.getArc().totalAngle()\n res = newLinearObjectList.lengthen_deltaAngle(self.move_startPt, value)\n elif self.OpMode == \"DYnamic\":\n newLinearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n transformedPt = self.mapToLayerCoordinates(layer, point)\n \n if self.move_startPt:\n linearObject = newLinearObjectList.getLinearObjectAt(0)\n else:\n linearObject = newLinearObjectList.getLinearObjectAt(-1)\n \n if linearObject.isSegment():\n newPt = qad_utils.getPerpendicularPointOnInfinityLine(linearObject.getStartPt(), linearObject.getEndPt(), transformedPt)\n else: # arco\n newPt = qad_utils.getPolarPointByPtAngle(linearObject.getArc().center, \\\n qad_utils.getAngleBy2Pts(linearObject.getArc().center, transformedPt), \\\n linearObject.getArc().radius) \n\n if newLinearObjectList.qty() > 1 and linearObject.isSegment():\n ang = linearObject.getTanDirectionOnStartPt()\n\n if self.move_startPt:\n linearObject.setStartPt(newPt)\n else:\n linearObject.setEndPt(newPt)\n \n if newLinearObjectList.qty() > 1 and linearObject.isSegment() and \\\n qad_utils.TanDirectionNear(ang, linearObject.getTanDirectionOnStartPt()) == False:\n res = False\n else:\n res = True\n\n if res == False: # allungamento impossibile\n return False\n \n pts = newLinearObjectList.asPolyline() \n updSubGeom = QgsGeometry.fromPolyline(pts)\n \n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return False\n f.setGeometry(updGeom)\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n\n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n return True\n\n\n \n def showLength(self, entity, pt):\n # visualizza la lunghezza dell'entità in unità di mappa\n geom = entity.getGeometry()\n if geom is None:\n self.showErr(QadMsg.translate(\"QAD\", \"\\nInvalid object.\"))\n return None\n \n # Trasformo il punto nel sistema di coordinate del layer\n convPt = self.mapToLayerCoordinates(entity.layer, pt)\n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(pt, geom)\n if dummy[2] is None:\n self.showErr(QadMsg.translate(\"QAD\", \"\\nInvalid object.\"))\n return None\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n \n LinearObjectListToMisure = qad_utils.QadLinearObjectList()\n pointList = subGeom.asPolyline()\n LinearObjectListToMisure.fromPolyline(pointList)\n # la trasformo in unità di mappa\n LinearObjectListToMisure.transformFromCRSToCRS(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) \n \n msg = QadMsg.translate(\"Command_LENGTHEN\", \"\\nCurrent length: {0}\")\n msg = msg.format(str(LinearObjectListToMisure.length()))\n\n arc = QadArc()\n startEndVertices = arc.fromPolyline(pointList, 0)\n # se la polilinea è composta solo da un arco\n if startEndVertices and startEndVertices[0] == 0 and startEndVertices[1] == len(pointList)-1:\n msg = msg + QadMsg.translate(\"Command_LENGTHEN\", \", included angle: {0}\")\n msg = msg.format(str(qad_utils.toDegrees(arc.totalAngle())))\n \n self.showMsg(msg)\n\n\n def waitForObjectSelToMisure(self):\n self.step = 1 \n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_OBJ_TO_MISURE)\n\n if self.plugIn.lastOpMode_lengthen == \"DElta\":\n self.defaultValue = QadMsg.translate(\"Command_LENGTHEN\", \"DElta\")\n elif self.plugIn.lastOpMode_lengthen == \"Percent\":\n self.defaultValue = QadMsg.translate(\"Command_LENGTHEN\", \"Percent\")\n elif self.plugIn.lastOpMode_lengthen == \"Total\":\n self.defaultValue = QadMsg.translate(\"Command_LENGTHEN\", \"Total\")\n elif self.plugIn.lastOpMode_lengthen == \"DYnamic\":\n self.defaultValue = QadMsg.translate(\"Command_LENGTHEN\", \"DYnamic\")\n else:\n self.defaultValue = None\n \n keyWords = QadMsg.translate(\"Command_LENGTHEN\", \"DElta\") + \"/\" + \\\n QadMsg.translate(\"Command_LENGTHEN\", \"Percent\") + \"/\" + \\\n QadMsg.translate(\"Command_LENGTHEN\", \"Total\") + \"/\" + \\\n QadMsg.translate(\"Command_LENGTHEN\", \"DYnamic\")\n if self.defaultValue is None:\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Select an object or [{0}] <{1}>: \").format(keyWords, self.defaultValue)\n else:\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Select an object or [{0}] <{1}>: \").format(keyWords, self.defaultValue)\n\n englishKeyWords = \"DElta\" + \"/\" + \"Percent\" + \"/\" + \"Total\" + \"/\" + \"DYnamic\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n self.defaultValue, \\\n keyWords, QadInputModeEnum.NONE)\n\n\n def waitForDelta(self):\n self.step = 2\n self.OpMode = \"DElta\"\n self.plugIn.setLastOpMode_lengthen(self.OpMode)\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_DELTA)\n\n keyWords = QadMsg.translate(\"Command_LENGTHEN\", \"Angle\")\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter delta length or [{0}] <{1}>: \").format(keyWords, str(self.plugIn.lastDelta_lengthen))\n\n englishKeyWords = \"Angle\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS | QadInputTypeEnum.FLOAT, \\\n self.plugIn.lastDelta_lengthen, \\\n keyWords, QadInputModeEnum.NONE)\n \n\n def waitForDeltaLength(self, msgMapTool, msg):\n self.step = 3\n self.OpType = \"length\"\n\n # si appresta ad attendere una distanza \n if self.GetDistClass is not None:\n del self.GetDistClass\n self.GetDistClass = QadGetDistClass(self.plugIn) \n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter delta length <{0}>: \")\n self.GetDistClass.msg = prompt.format(str(self.plugIn.lastDelta_lengthen))\n self.GetDistClass.startPt = self.startPt\n self.GetDistClass.dist = self.plugIn.lastDelta_lengthen\n self.GetDistClass.inputMode = QadInputModeEnum.NONE\n self.GetDistClass.run(msgMapTool, msg)\n\n\n def waitForDeltaAngle(self, msgMapTool, msg):\n self.step = 4\n self.OpType = \"Angle\"\n\n # si appresta ad attendere l'angolo di rotazione \n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter delta angle <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.plugIn.lastDeltaAngle_lengthen)))\n self.GetAngleClass.angle = self.plugIn.lastDeltaAngle_lengthen\n self.GetAngleClass.run(msgMapTool, msg) \n\n\n def waitForObjectSel(self):\n self.step = 5\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_OBJ_TO_LENGTHEN)\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di distanza o angolo\n self.getPointMapTool().OpType = self.OpType \n self.getPointMapTool().value = self.value\n\n keyWords = QadMsg.translate(\"Command_LENGTHEN\", \"Undo\")\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Select an object to change or [{0}]: \").format(QadMsg.translate(\"Command_LENGTHEN\", \"Undo\"))\n\n englishKeyWords = \"Undo\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n\n\n def waitForPercent(self):\n self.step = 6\n self.OpMode = \"Percent\"\n self.plugIn.setLastOpMode_lengthen(self.OpMode)\n\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_PERCENT)\n\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter percentage length <{0}>: \")\n prompt = prompt.format(str(self.plugIn.lastPerc_lengthen))\n # si appresta ad attendere un numero reale \n # msg, inputType, default, keyWords, valori positivi\n self.waitFor(prompt, QadInputTypeEnum.FLOAT, \\\n self.plugIn.lastPerc_lengthen, \"\", \\\n QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n\n \n def waitForTotal(self):\n self.step = 7\n self.OpMode = \"Total\"\n self.plugIn.setLastOpMode_lengthen(self.OpMode)\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_TOTAL)\n\n keyWords = QadMsg.translate(\"Command_LENGTHEN\", \"Angle\")\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Specify total length or [{0}] <{1}>: \").format(keyWords, str(self.plugIn.lastTotal_lengthen))\n\n englishKeyWords = \"Angle\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS | QadInputTypeEnum.FLOAT, \\\n self.plugIn.lastTotal_lengthen, \\\n keyWords, QadInputModeEnum.NOT_ZERO | QadInputModeEnum.NOT_NEGATIVE)\n \n\n def waitForTotalLength(self, msgMapTool, msg):\n self.step = 8\n self.OpType = \"length\"\n\n # si appresta ad attendere una distanza \n if self.GetDistClass is not None:\n del self.GetDistClass\n self.GetDistClass = QadGetDistClass(self.plugIn) \n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter total length <{0}>: \")\n self.GetDistClass.msg = prompt.format(str(self.plugIn.lastTotal_lengthen))\n self.GetDistClass.startPt = self.startPt\n self.GetDistClass.dist = self.plugIn.lastTotal_lengthen\n self.GetDistClass.inputMode = QadInputModeEnum.NONE\n self.GetDistClass.run(msgMapTool, msg)\n\n\n def waitForTotalAngle(self, msgMapTool, msg):\n self.step = 9\n self.OpType = \"Angle\"\n\n # si appresta ad attendere l'angolo di rotazione \n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Enter total angle <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.plugIn.lastTotalAngle_lengthen)))\n self.GetAngleClass.angle = self.plugIn.lastTotalAngle_lengthen\n self.GetAngleClass.run(msgMapTool, msg) \n\n\n def waitForDynamicPt(self):\n self.step = 10\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_DYNAMIC_POINT)\n\n prompt = QadMsg.translate(\"Command_LENGTHEN\", \"Specify new endpoint: \")\n\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D, \\\n None, \\\n \"\", QadInputModeEnum.NONE)\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTO\n if self.step == 0: # inizio del comando\n # si appresta ad attendere la selezione degli oggetti da estendere/tagliare\n self.waitForObjectSelToMisure()\n return False\n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI DA MISURARE\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.defaultValue\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_LENGTHEN\", \"DElta\") or value == \"DElta\":\n self.waitForDelta()\n return False\n elif value == QadMsg.translate(\"Command_LENGTHEN\", \"Percent\") or value == \"Percent\":\n self.waitForPercent()\n return False\n elif value == QadMsg.translate(\"Command_LENGTHEN\", \"Total\") or value == \"Total\":\n self.waitForTotal()\n return False\n elif value == QadMsg.translate(\"Command_LENGTHEN\", \"DYnamic\") or value == \"DYnamic\":\n self.OpMode = \"DYnamic\"\n self.plugIn.setLastOpMode_lengthen(self.OpMode)\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n return False\n\n elif type(value) == QgsPoint: # se é stato selezionato un punto\n if self.getPointMapTool().entity.isInitialized():\n self.showLength(self.getPointMapTool().entity, value)\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer di tipo lineari che non appartengano a quote o di tipo poligono \n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon:\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n feature = result[0]\n layer = result[1]\n self.showLength(QadEntity().set(layer, feature.id()), value)\n else:\n return True # fine comando\n \n # si appresta ad attendere la selezione degli oggetti da misurare\n self.waitForObjectSelToMisure()\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL DELTA (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.plugIn.lastDelta_lengthen # opzione di default \"spostamento\"\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_LENGTHEN\", \"Angle\") or value == \"Angle\":\n self.waitForDeltaAngle(msgMapTool, msg)\n elif type(value) == QgsPoint: # se é stato inserito un punto\n self.startPt = value\n self.waitForDeltaLength(msgMapTool, msg)\n elif type(value) == float: # se é stato inserito il delta\n self.plugIn.setLastDelta_lengthen(value)\n self.OpType = \"length\"\n self.value = value\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n\n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA LUNGHEZZA DEL DELTA (da step = 2)\n elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if self.GetDistClass.run(msgMapTool, msg) == True:\n if self.GetDistClass.dist is not None:\n self.plugIn.setLastDelta_lengthen(self.GetDistClass.dist)\n self.value = self.GetDistClass.dist\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELL'ANGOLO DEL DELTA (da step = 2)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if self.GetAngleClass.run(msgMapTool, msg) == True:\n if self.GetAngleClass.angle is not None:\n self.plugIn.setLastDeltaAngle_lengthen(self.GetAngleClass.angle)\n self.value = self.GetAngleClass.angle\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n\n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI DA ALLUNGARE\n elif self.step == 5:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_LENGTHEN\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n elif type(value) == QgsPoint: # se é stato selezionato un punto\n if self.getPointMapTool().entity.isInitialized():\n self.setInfo(self.getPointMapTool().entity, value)\n if self.OpMode != \"DYnamic\":\n self.lengthen(value)\n else:\n self.waitForDynamicPt()\n return False\n else:\n # cerco se ci sono entità nel punto indicato considerando\n # solo layer lineari editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n layerList)\n if result is not None:\n feature = result[0]\n layer = result[1]\n self.setInfo(QadEntity().set(layer, feature.id()), value)\n\n if self.OpMode != \"DYnamic\":\n self.lengthen(value)\n else:\n self.waitForDynamicPt()\n return False\n else:\n return True # fine comando\n\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PERCENTUALE (da step = 1)\n elif self.step == 6: # dopo aver atteso un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.plugIn.lastPerc_lengthen\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n return False\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == float: # é stata inserita la percentuale\n self.plugIn.setLastPerc_lengthen(value)\n self.value = value\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL TOTALE (da step = 1)\n elif self.step == 7: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = self.plugIn.lastTotal_lengthen\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_LENGTHEN\", \"Angle\") or value == \"Angle\":\n self.waitForTotalAngle(msgMapTool, msg)\n elif type(value) == QgsPoint: # se é stato inserito un punto\n self.startPt = value\n self.waitForTotalLength(msgMapTool, msg)\n elif type(value) == float: # se é stato inserito il delta\n self.plugIn.setLastTotal_lengthen(value)\n self.OpType = \"length\"\n self.value = value\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n\n return False \n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA LUNGHEZZA DEL TOTALE (da step = 7)\n elif self.step == 8: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if self.GetDistClass.run(msgMapTool, msg) == True:\n if self.GetDistClass.dist is not None:\n self.plugIn.setLastTotal_lengthen(self.GetDistClass.dist)\n self.value = self.GetDistClass.dist\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n return False\n \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELL'ANGOLO DEL DELTA (da step = 7)\n elif self.step == 9: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if self.GetAngleClass.run(msgMapTool, msg) == True:\n if self.GetAngleClass.angle is not None:\n self.plugIn.setLastTotalAngle_lengthen(self.GetAngleClass.angle)\n self.value = self.GetAngleClass.angle\n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA NUOVA ESTREMITA' IN MODO DINAMICO (da step = 5)\n elif self.step == 10: # dopo aver atteso un punto\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point \n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == QgsPoint: # se é stato inserito un punto\n self.lengthen(value)\n \n # si appresta ad attendere la selezione degli oggetti da allungare\n self.waitForObjectSel()\n \n return False\n\n\n\n\n#============================================================================\n# Classe che gestisce il comando LENGTHEN per i grip\n#============================================================================\nclass QadGRIPLENGTHENCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadGRIPLENGTHENCommandClass(self.plugIn)\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.entity = None\n self.skipToNextGripCommand = False\n self.copyEntities = False\n self.basePt = QgsPoint()\n self.nOperationsToUndo = 0\n \n self.linearObjectList = None\n self.atSubGeom = None\n self.move_startPt = None\n\n\n def __del__(self):\n QadCommandClass.__del__(self)\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE): \n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_lengthen_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n\n #============================================================================\n # setSelectedEntityGripPoints\n #============================================================================\n def setSelectedEntityGripPoints(self, entitySetGripPoints):\n # lista delle entityGripPoint con dei grip point selezionati\n # setta la prima entità con un grip selezionato\n self.entity = None\n for entityGripPoints in entitySetGripPoints.entityGripPoints:\n for gripPoint in entityGripPoints.gripPoints:\n # grip point selezionato\n if gripPoint.getStatus() == qad_grip.QadGripStatusEnum.SELECTED:\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entityGripPoints.entity.isDimensionComponent():\n return False\n if entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.ARC and \\\n entityGripPoints.entity.getEntityType() != QadEntityGeomTypeEnum.LINESTRING:\n return False\n \n # setta: self.entity, self.linearObjectList, self.atSubGeom e self.move_startPt\n self.entity = entityGripPoints.entity\n \n if self.linearObjectList is not None:\n del self.linearObjectList\n self.linearObjectList = None\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.entity.layer, self.entity.getGeometry())\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n res = False\n dummy = qad_utils.closestSegmentWithContext(gripPoint.getPoint(), geom)\n if dummy[2] is None:\n return False\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, self.atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2]) \n self.linearObjectList = qad_utils.QadLinearObjectList()\n\n self.linearObjectList.fromPolyline(subGeom.asPolyline())\n \n if qad_utils.getDistance(self.linearObjectList.getStartPt(), gripPoint.getPoint()) <= \\\n qad_utils.getDistance(self.linearObjectList.getEndPt(), gripPoint.getPoint()):\n # si allunga dal punto iniziale\n self.move_startPt = True\n else:\n # si allunga dal punto finale\n self.move_startPt = False\n\n # imposto il map tool\n if self.getPointMapTool().setInfo(self.entity, gripPoint.getPoint()) == False:\n return False\n \n return True\n return False\n\n\n #============================================================================\n # lengthen\n #============================================================================\n def lengthen(self, point):\n layer = self.entity.layer\n f = self.entity.getFeature()\n if f is None: # non c'è più la feature\n return False\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(layer, self.entity.getGeometry())\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n res = False\n newLinearObjectList = qad_utils.QadLinearObjectList(self.linearObjectList)\n \n if self.move_startPt:\n linearObject = newLinearObjectList.getLinearObjectAt(0)\n else:\n linearObject = newLinearObjectList.getLinearObjectAt(-1)\n \n if linearObject.isSegment():\n newPt = qad_utils.getPerpendicularPointOnInfinityLine(linearObject.getStartPt(), linearObject.getEndPt(), point)\n else: # arco\n newPt = qad_utils.getPolarPointByPtAngle(linearObject.getArc().center, \\\n qad_utils.getAngleBy2Pts(linearObject.getArc().center, point), \\\n linearObject.getArc().radius) \n\n if newLinearObjectList.qty() > 1 and linearObject.isSegment():\n ang = linearObject.getTanDirectionOnStartPt()\n\n if self.move_startPt:\n linearObject.setStartPt(newPt)\n else:\n linearObject.setEndPt(newPt)\n \n if newLinearObjectList.qty() > 1 and linearObject.isSegment() and \\\n qad_utils.TanDirectionNear(ang, linearObject.getTanDirectionOnStartPt()) == False:\n res = False\n else:\n res = True\n\n if res == False: # allungamento impossibile\n return False\n \n pts = newLinearObjectList.asPolyline() \n updSubGeom = QgsGeometry.fromPolyline(pts)\n \n updGeom = qad_utils.setSubGeom(geom, updSubGeom, self.atSubGeom)\n if updGeom is None:\n return False\n # trasformo la geometria nel crs del layer\n f.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n \n self.plugIn.beginEditCommand(\"Feature edited\", layer)\n \n if self.copyEntities == False:\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, f, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n else:\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, f, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return False\n \n self.plugIn.endEditCommand()\n self.nOperationsToUndo = self.nOperationsToUndo + 1\n \n return True\n\n\n def waitForDynamicPt(self):\n keyWords = QadMsg.translate(\"Command_GRIP\", \"Copy\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"Undo\") + \"/\" + \\\n QadMsg.translate(\"Command_GRIP\", \"eXit\")\n prompt = QadMsg.translate(\"Command_GRIPLENGTHEN\", \"Specify new endpoint or [{0}]: \").format(keyWords)\n\n englishKeyWords = \"Copy\" + \"/\" + \"Undo\" + \"/\" \"eXit\"\n keyWords += \"_\" + englishKeyWords\n\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n self.step = 1\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_lengthen_maptool_ModeEnum.ASK_FOR_DYNAMIC_POINT)\n\n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA SELEZIONE OGGETTO\n if self.step == 0: # inizio del comando\n self.waitForDynamicPt()\n return False\n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE OGGETTI DA MISURARE\n elif self.step == 1:\n ctrlKey = False\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n ctrlKey = self.getPointMapTool().ctrlKey\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_GRIP\", \"Copy\") or value == \"Copy\":\n # Copia entità lasciando inalterate le originali\n self.copyEntities = True \n\n self.waitForDynamicPt()\n elif value == QadMsg.translate(\"Command_GRIP\", \"Undo\") or value == \"Undo\":\n if self.nOperationsToUndo > 0: \n self.nOperationsToUndo = self.nOperationsToUndo - 1\n self.plugIn.undoEditCommand()\n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe command has been canceled.\")) \n\n self.waitForDynamicPt()\n elif value == QadMsg.translate(\"Command_GRIP\", \"eXit\") or value == \"eXit\":\n return True # fine comando\n elif type(value) == QgsPoint: # se é stato selezionato un punto\n if ctrlKey:\n self.copyEntities = True\n \n self.lengthen(value)\n\n if self.copyEntities == False:\n return True\n\n self.waitForDynamicPt()\n else:\n if self.copyEntities == False:\n self.skipToNextGripCommand = True\n return True # fine comando\n \n return False"
},
{
"alpha_fraction": 0.6792680025100708,
"alphanum_fraction": 0.7122561931610107,
"avg_line_length": 55.876712799072266,
"blob_id": "ea01d18aec89433b481c2b3bad90501e5cff14ff",
"content_id": "0f1a23b63c5442017791fdb69fe17613dc8e7e43",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4153,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 73,
"path": "/qad_dimstyle_new_ui.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qad_dimstyle_new.ui'\n#\n# Created: Tue Sep 08 15:55:21 2015\n# by: PyQt4 UI code generator 4.10.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_DimStyle_New_Dialog(object):\n def setupUi(self, DimStyle_New_Dialog):\n DimStyle_New_Dialog.setObjectName(_fromUtf8(\"DimStyle_New_Dialog\"))\n DimStyle_New_Dialog.resize(372, 142)\n self.label = QtGui.QLabel(DimStyle_New_Dialog)\n self.label.setGeometry(QtCore.QRect(10, 10, 221, 16))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.newDimStyleName = QtGui.QLineEdit(DimStyle_New_Dialog)\n self.newDimStyleName.setGeometry(QtCore.QRect(10, 30, 221, 20))\n self.newDimStyleName.setObjectName(_fromUtf8(\"newDimStyleName\"))\n self.label_2 = QtGui.QLabel(DimStyle_New_Dialog)\n self.label_2.setGeometry(QtCore.QRect(10, 90, 221, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.DimStyleNameFrom = QtGui.QComboBox(DimStyle_New_Dialog)\n self.DimStyleNameFrom.setGeometry(QtCore.QRect(10, 110, 221, 22))\n self.DimStyleNameFrom.setObjectName(_fromUtf8(\"DimStyleNameFrom\"))\n self.continueButton = QtGui.QPushButton(DimStyle_New_Dialog)\n self.continueButton.setGeometry(QtCore.QRect(290, 50, 75, 23))\n self.continueButton.setObjectName(_fromUtf8(\"continueButton\"))\n self.cancelButton = QtGui.QPushButton(DimStyle_New_Dialog)\n self.cancelButton.setGeometry(QtCore.QRect(290, 80, 75, 23))\n self.cancelButton.setObjectName(_fromUtf8(\"cancelButton\"))\n self.helpButton = QtGui.QPushButton(DimStyle_New_Dialog)\n self.helpButton.setGeometry(QtCore.QRect(290, 110, 75, 23))\n self.helpButton.setObjectName(_fromUtf8(\"helpButton\"))\n self.label_3 = QtGui.QLabel(DimStyle_New_Dialog)\n self.label_3.setGeometry(QtCore.QRect(10, 50, 221, 16))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.newDimStyleDescr = QtGui.QLineEdit(DimStyle_New_Dialog)\n self.newDimStyleDescr.setGeometry(QtCore.QRect(10, 70, 221, 20))\n self.newDimStyleDescr.setObjectName(_fromUtf8(\"newDimStyleDescr\"))\n\n self.retranslateUi(DimStyle_New_Dialog)\n QtCore.QObject.connect(self.DimStyleNameFrom, QtCore.SIGNAL(_fromUtf8(\"currentIndexChanged(int)\")), DimStyle_New_Dialog.DimStyleNameFromChanged)\n QtCore.QObject.connect(self.newDimStyleName, QtCore.SIGNAL(_fromUtf8(\"textEdited(QString)\")), DimStyle_New_Dialog.newStyleNameChanged)\n QtCore.QObject.connect(self.cancelButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_New_Dialog.reject)\n QtCore.QObject.connect(self.helpButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_New_Dialog.ButtonHELP_Pressed)\n QtCore.QObject.connect(self.continueButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_New_Dialog.ButtonBOX_continue)\n QtCore.QMetaObject.connectSlotsByName(DimStyle_New_Dialog)\n\n def retranslateUi(self, DimStyle_New_Dialog):\n DimStyle_New_Dialog.setWindowTitle(_translate(\"DimStyle_New_Dialog\", \"QAD - Create new dimension style\", None))\n self.label.setText(_translate(\"DimStyle_New_Dialog\", \"New style name:\", None))\n self.label_2.setText(_translate(\"DimStyle_New_Dialog\", \"Start with:\", None))\n self.continueButton.setText(_translate(\"DimStyle_New_Dialog\", \"Continue...\", None))\n self.cancelButton.setText(_translate(\"DimStyle_New_Dialog\", \"Cancel\", None))\n self.helpButton.setText(_translate(\"DimStyle_New_Dialog\", \"?\", None))\n self.label_3.setText(_translate(\"DimStyle_New_Dialog\", \"Description:\", None))\n\n"
},
{
"alpha_fraction": 0.636488676071167,
"alphanum_fraction": 0.6388100981712341,
"avg_line_length": 42.37313461303711,
"blob_id": "421c15f5200b27b14a4b283c5be2e9bf7324084c",
"content_id": "e006330c5da26b8a6fbd582a3b667839ae27d539",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11631,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 268,
"path": "/qad_dimstyle_dlg.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire la dialog per DIMSTYLE\n \n -------------------\n begin : 2015-05-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\nfrom qgis.utils import *\n\nimport qad_dimstyle_ui\n\nfrom qad_variables import *\nfrom qad_dim import *\nfrom qad_msg import QadMsg, qadShowPluginHelp\nfrom qad_dimstyle_new_dlg import QadDIMSTYLE_NEW_Dialog\nfrom qad_dimstyle_details_dlg import QadDIMSTYLE_DETAILS_Dialog, QadPreviewDim\nfrom qad_dimstyle_diff_dlg import QadDIMSTYLE_DIFF_Dialog\nimport qad_utils\n\n\n#######################################################################################\n# Classe che gestisce l'interfaccia grafica del comando DIMSTYLE\nclass QadDIMSTYLEDialog(QDialog, QObject, qad_dimstyle_ui.Ui_DimStyle_Dialog):\n def __init__(self, plugIn):\n self.plugIn = plugIn\n self.iface = self.plugIn.iface.mainWindow()\n QDialog.__init__(self, self.iface)\n \n self.selectedDimStyle = None\n \n self.setupUi(self)\n self.retranslateUi(self) # aggiungo alcune traduzioni personalizzate\n self.dimStyleList.setContextMenuPolicy(Qt.CustomContextMenu)\n \n # aggiungo il canvans di preview della quota chiamato QadPreviewDim \n # che eredita la posizione di previewDummy (che viene nascosto) \n self.previewDummy.setHidden(True)\n self.previewDim = QadPreviewDim(self.previewDummy.parent(), self.plugIn)\n self.previewDim.setGeometry(self.previewDummy.geometry())\n self.previewDim.setObjectName(\"previewDim\")\n \n self.init()\n\n\n def closeEvent(self, event):\n del self.previewDim # cancello il canvans di preview della quota chiamato QadPreviewDim \n return QDialog.closeEvent(self, event)\n\n def init(self):\n # Inizializzazione dello stile corrente\n currDimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n self.currentDimStyle.setText(\"\" if currDimStyleName is None else currDimStyleName)\n \n # Inizializzazione della lista degli stili\n model = QStandardItemModel(self.dimStyleList) \n for dimStyle in QadDimStyles.dimStyleList: # lista degli stili di quotatura caricati\n # Create an item with a caption\n item = QStandardItem(dimStyle.name)\n item.setEditable(True)\n item.setData(dimStyle)\n model.appendRow(item)\n\n self.dimStyleList.setModel(model)\n # sort\n self.dimStyleList.model().sort(0)\n # collego l'evento \"cambio di selezione\" alla funzione dimStyleListCurrentChanged\n self.dimStyleList.selectionModel().selectionChanged.connect(self.dimStyleListCurrentChanged)\n \n self.dimStyleList.itemDelegate().closeEditor.connect(self.dimStyleListcloseEditor)\n \n # seleziono il primo elemento della lista\n index = self.dimStyleList.model().index(0,0)\n if self.selectedDimStyle is not None:\n # seleziono l'elemento precedentemente selezionato\n item = self.dimStyleList.model().findItems(self.selectedDimStyle.name)[0]\n index = self.dimStyleList.model().indexFromItem(item)\n elif len(currDimStyleName) > 0:\n item = self.dimStyleList.model().findItems(currDimStyleName)[0]\n if item is not None:\n index = self.dimStyleList.model().indexFromItem(item)\n \n self.dimStyleList.selectionModel().setCurrentIndex(index, QItemSelectionModel.SelectCurrent)\n\n \n def retranslateUi(self, DimStyle_Dialog):\n qad_dimstyle_ui.Ui_DimStyle_Dialog.retranslateUi(self, self)\n # \"none\" viene tradotto in italiano in \"nessuno\" nel contesto \"currentDimStyle\"\n # \"none\" viene tradotto in italiano in \"nessuna\" nel contesto \"descriptionSelectedStyle\"\n # \"none\" viene tradotto in italiano in \"nessuno\" nel contesto \"selectedStyle\"\n self.currentDimStyle.setText(QadMsg.translate(\"DimStyle_Dialog\", \"none\", \"currentDimStyle\"))\n self.descriptionSelectedStyle.setText(QadMsg.translate(\"DimStyle_Dialog\", \"none\", \"descriptionSelectedStyle\"))\n self.selectedStyle.setText(QadMsg.translate(\"DimStyle_Dialog\", \"none\", \"selectedStyle\"))\n \n \n def dimStyleListCurrentChanged(self, current, previous):\n # leggo l'elemento selezionato\n index = current.indexes()[0]\n item = self.dimStyleList.model().itemFromIndex(index)\n self.selectedDimStyle = item.data()\n self.selectedStyle.setText(self.selectedDimStyle.name)\n self.descriptionSelectedStyle.setText(self.selectedDimStyle.description)\n \n self.previewDim.drawDim(self.selectedDimStyle)\n\n def dimStyleListcloseEditor(self, editor, hint):\n self.renSelectedDimStyle(editor.text())\n\n def setCurrentStyle(self):\n if self.selectedDimStyle is None:\n return\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"), self.selectedDimStyle.name)\n QadVariables.save()\n self.currentDimStyle.setText(self.selectedDimStyle.name)\n\n def renSelectedDimStyle(self, newName):\n if self.selectedDimStyle is None:\n return\n if QadDimStyles.renameDimStyle(self.selectedDimStyle.name, newName) == False:\n QMessageBox.critical(self, QadMsg.translate(\"QAD\", \"QAD\"), \\\n QadMsg.translate(\"DimStyle_Dialog\", \"Dimension style not renamed.\"))\n else:\n self.init()\n\n def updDescrSelectedDimStyle(self):\n if self.selectedDimStyle is None:\n return\n Title = QadMsg.translate(\"DimStyle_Dialog\", \"QAD - Editing dimension style description: \") + self.selectedDimStyle.name\n inputDlg = QInputDialog(self)\n inputDlg.setWindowTitle(Title) \n inputDlg.setInputMode(QInputDialog.TextInput) \n inputDlg.setLabelText(QadMsg.translate(\"DimStyle_Dialog\", \"New description:\"))\n inputDlg.setTextValue(self.selectedDimStyle.description)\n inputDlg.resize(600,100) \n if inputDlg.exec_(): \n self.selectedDimStyle.description = inputDlg.textValue() \n self.selectedDimStyle.save()\n self.init()\n \n def delSelectedDimStyle(self):\n if self.selectedDimStyle is None:\n return\n msg = QadMsg.translate(\"DimStyle_Dialog\", \"Remove dimension style {0} ?\").format(self.selectedDimStyle.name)\n res = QMessageBox.question(self, QadMsg.translate(\"QAD\", \"QAD\"), msg, \\\n QMessageBox.Yes | QMessageBox.No)\n if res == QMessageBox.Yes:\n if QadDimStyles.removeDimStyle(self.selectedDimStyle.name, True) == False:\n QMessageBox.critical(self, QadMsg.translate(\"QAD\", \"QAD\"), \\\n QadMsg.translate(\"DimStyle_Dialog\", \"Dimension style not removed.\"))\n else:\n self.selectedDimStyle = None\n self.init()\n\n def createNewStyle(self):\n self.previewDim.eraseDim()\n\n Form = QadDIMSTYLE_NEW_Dialog(self.plugIn, self.selectedDimStyle.name if self.selectedDimStyle is not None else None)\n if Form.exec_() == QDialog.Accepted:\n Form.dimStyle.path = \"\"\n QadDimStyles.addDimStyle(Form.dimStyle, True)\n self.selectedDimStyle = QadDimStyles.findDimStyle(Form.dimStyle.name)\n # setto lo stile corrente\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"), self.selectedDimStyle.name)\n self.init() \n \n self.previewDim.drawDim(self.selectedDimStyle)\n\n def modStyle(self):\n if self.selectedDimStyle is None:\n return\n self.previewDim.eraseDim()\n \n Form = QadDIMSTYLE_DETAILS_Dialog(self.plugIn, self.selectedDimStyle)\n title = QadMsg.translate(\"DimStyle_Dialog\", \"Modify dimension style: \") + self.selectedDimStyle.name\n Form.setWindowTitle(title)\n if Form.exec_() == QDialog.Accepted:\n self.selectedDimStyle.set(Form.dimStyle)\n self.selectedDimStyle.save()\n self.init()\n del Form # forzo la chiamata al distruttore per rimuovere il preview della quota\n \n self.previewDim.drawDim(self.selectedDimStyle)\n\n\n def temporaryModStyle(self):\n if self.selectedDimStyle is None:\n return\n self.previewDim.eraseDim()\n\n Form = QadDIMSTYLE_DETAILS_Dialog(self.plugIn, self.selectedDimStyle)\n title = QadMsg.translate(\"DimStyle_Dialog\", \"Set temporary overrides to dimension style: \") + self.selectedDimStyle.name\n Form.setWindowTitle(title)\n if Form.exec_() == QDialog.Accepted:\n self.selectedDimStyle.set(Form.dimStyle)\n self.init()\n \n self.previewDim.drawDim(self.selectedDimStyle)\n\n\n def showDiffBetweenStyles(self):\n Form = QadDIMSTYLE_DIFF_Dialog(self.plugIn, self.selectedDimStyle.name)\n Form.exec_()\n\n def startEditingItem(self):\n if self.selectedDimStyle is None:\n return\n item = self.dimStyleList.model().findItems(self.selectedDimStyle.name)[0]\n index = self.dimStyleList.model().indexFromItem(item)\n self.dimStyleList.edit(index)\n \n def ButtonBOX_Accepted(self): \n self.close()\n return True\n\n\n def ButtonHELP_Pressed(self):\n qadShowPluginHelp(QadMsg.translate(\"Help\", \"Dimensioning\"))\n\n #============================================================================\n # displayPopupMenu\n #============================================================================\n def displayPopupMenu(self, pos):\n if self.selectedDimStyle is None:\n return\n \n popupMenu = QMenu(self)\n action = QAction(QadMsg.translate(\"DimStyle_Dialog\", \"Set current\"), popupMenu)\n popupMenu.addAction(action)\n QObject.connect(action, SIGNAL(\"triggered()\"), self.setCurrentStyle)\n\n action = QAction(QadMsg.translate(\"DimStyle_Dialog\", \"Rename\"), popupMenu)\n popupMenu.addAction(action)\n QObject.connect(action, SIGNAL(\"triggered()\"), self.startEditingItem)\n\n action = QAction(QadMsg.translate(\"DimStyle_Dialog\", \"Modify description\"), popupMenu)\n popupMenu.addAction(action)\n QObject.connect(action, SIGNAL(\"triggered()\"), self.updDescrSelectedDimStyle)\n\n action = QAction(QadMsg.translate(\"DimStyle_Dialog\", \"Remove\"), popupMenu)\n currDimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n if self.selectedDimStyle.name == currDimStyleName:\n action.setDisabled(True)\n popupMenu.addAction(action)\n QObject.connect(action, SIGNAL(\"triggered()\"), self.delSelectedDimStyle)\n\n popupMenu.popup(self.dimStyleList.mapToGlobal(pos))\n\n "
},
{
"alpha_fraction": 0.5288482904434204,
"alphanum_fraction": 0.5326005220413208,
"avg_line_length": 55.7593994140625,
"blob_id": "485272995760988737b4bea6ea6718fe0a0d4127",
"content_id": "4abc4d0762c6206a31406af3cea1dd2911e54ced",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 22675,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 399,
"path": "/qad_line_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando PLINE per disegnare una linea\n \n -------------------\n begin : 2013-07-15\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_getpoint import *\nfrom qad_line_maptool import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nfrom qad_snapper import *\nimport qad_utils\nimport qad_layer\nfrom qad_rubberband import createRubberBand\n\n\n# Classe che gestisce il comando LINE\nclass QadLINECommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadLINECommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"LINE\")\n\n def getEnglishName(self):\n return \"LINE\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runLINECommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/line.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_LINE\", \"Creates straight line segments.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.vertices = []\n self.rubberBand = createRubberBand(self.plugIn.canvas, QGis.Line)\n self.firstPtTan = None\n self.firstPtPer = None \n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.virtualCmd = False\n\n def __del__(self):\n QadCommandClass.__del__(self)\n self.rubberBand.hide()\n self.plugIn.canvas.scene().removeItem(self.rubberBand)\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_line_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None \n\n def addVertex(self, point):\n self.vertices.append(point) \n self.addPointToRubberBand(point) \n self.plugIn.setLastPointAndSegmentAng(self.vertices[-1]) \n self.setTmpGeometriesToMapTool()\n \n def delLastVertex(self):\n if len(self.vertices) > 0:\n del self.vertices[-1] # cancello ultimo vertice\n self.removeLastPointToRubberBand()\n if len(self.vertices) > 0:\n self.plugIn.setLastPointAndSegmentAng(self.vertices[-1])\n self.setTmpGeometriesToMapTool() \n \n\n #============================================================================\n # addPointToRubberBand\n #============================================================================\n def addPointToRubberBand(self, point, doUpdate = True):\n numberOfVertices = self.rubberBand.numberOfVertices()\n \n if numberOfVertices == 2:\n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n adjustedPoint = qad_utils.getAdjustedRubberBandVertex(self.rubberBand.getPoint(0, 0), point) \n self.rubberBand.addPoint(adjustedPoint, doUpdate)\n else:\n self.rubberBand.addPoint(point, doUpdate)\n \n \n #============================================================================\n # removeLastPointToRubberBand\n #============================================================================\n def removeLastPointToRubberBand(self):\n self.rubberBand.removeLastPoint()\n\n def addLinesToLayer(self, layer):\n i = 1\n while i < len(self.vertices): \n qad_layer.addLineToLayer(self.plugIn, layer,\n [self.vertices[i - 1], self.vertices[i]])\n i = i + 1\n\n\n #============================================================================\n # setTmpGeometriesToMapTool\n #============================================================================\n def setTmpGeometriesToMapTool(self):\n self.getPointMapTool().clearTmpGeometries()\n i = 1\n while i < len(self.vertices): \n # per lo snap aggiungo questa geometria temporanea\n self.getPointMapTool().appendTmpGeometry(QgsGeometry.fromPolyline([self.vertices[i - 1], self.vertices[i]]))\n i = i + 1\n\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n currLayer, errMsg = qad_layer.getCurrLayerEditable(self.plugIn.canvas, QGis.Line)\n if currLayer is None:\n self.showErr(errMsg)\n return True # fine comando\n \n # RICHIESTA PRIMO PUNTO \n if self.step == 0: # inizio del comando\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)\n # si appresta ad attendere un punto o enter\n # msg, inputType, default, keyWords, nessun controllo \n self.waitFor(QadMsg.translate(\"Command_LINE\", \"Specify first point: \"), \\\n QadInputTypeEnum.POINT2D, None, \"\", QadInputModeEnum.NONE)\n self.step = 1\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO OPPURE MENU PRINCIPALE\n elif self.step == 1: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n if self.virtualCmd == False: # se si vuole veramente salvare in un layer \n self.addLinesToLayer(currLayer)\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n snapTypeOnSel = self.getPointMapTool().snapTypeOnSelection\n value = self.getPointMapTool().point\n entity = self.getPointMapTool().entity\n else: # il punto arriva come parametro della funzione\n value = msg\n snapTypeOnSel = QadSnapTypeEnum.NONE\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_LINE\", \"Undo\") or value == \"Undo\": \n self.delLastVertex() # cancello ultimo vertice\n # imposto il map tool\n if len(self.vertices) == 0:\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT)\n # si appresta ad attendere un punto o enter\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(QadMsg.translate(\"Command_LINE\", \"Specify first point: \"), \\\n QadInputTypeEnum.POINT2D, None, \"\", QadInputModeEnum.NONE)\n return False \n else:\n self.getPointMapTool().firstPt = self.vertices[-1]\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n elif value == QadMsg.translate(\"Command_LINE\", \"Close\") or VALUE == \"Close\":\n newPt = self.vertices[0]\n self.addVertex(newPt) # aggiungo un nuovo vertice\n if self.virtualCmd == False: # se si vuole veramente salvare in un layer \n self.addLinesToLayer(currLayer)\n return True # fine comando\n else:\n if len(self.vertices) == 0: # primo punto\n if value is None:\n if self.plugIn.lastPoint is not None:\n value = self.plugIn.lastPoint\n else:\n return True # fine comando\n \n # se é stato selezionato un punto con la modalità TAN_DEF é un punto differito\n if snapTypeOnSel == QadSnapTypeEnum.TAN_DEF and entity.isInitialized():\n # se era stato selezionato un punto esplicito\n if (self.firstPtTan is None) and (self.firstPtPer is None): \n self.firstPtPer = None\n self.firstPtTan = value\n self.firstGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n self.firstGeom.transform(coordTransform)\n # imposto il map tool\n self.getPointMapTool().tan1 = self.firstPtTan\n self.getPointMapTool().geom1 = self.firstGeom\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_TAN_KNOWN_ASK_FOR_SECOND_PT)\n # se era stato selezionato un punto con la modalità TAN_DEF \n elif self.firstPtTan is not None:\n secondGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n secondGeom.transform(coordTransform)\n tangent = qad_utils.lineFrom2TanPts(self.firstGeom, self.firstPtTan, secondGeom, value)\n if tangent is not None:\n # prendo il punto più vicino a value\n if qad_utils.getDistance(tangent[0], value) < qad_utils.getDistance(tangent[1], value): \n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[0]\n else:\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[1]\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n else:\n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo tangent possible\"))\n # se era stato selezionato un punto con la modalità PER_DEF \n elif self.firstPtPer is not None:\n secondGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n secondGeom.transform(coordTransform)\n tangent = qad_utils.lineFromTanPerPts(secondGeom, value, self.firstGeom, self.firstPtPer)\n if tangent is not None:\n # prendo il punto più vicino a value\n if qad_utils.getDistance(tangent[0], value) < qad_utils.getDistance(tangent[1], value): \n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[0]\n else:\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[1]\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n else:\n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo tangent possible\")) \n \n # se é stato selezionato un punto con la modalità PER_DEF é un punto differito\n elif snapTypeOnSel == QadSnapTypeEnum.PER_DEF and entity.isInitialized():\n # se era stato selezionato un punto esplicito\n if (self.firstPtTan is None) and (self.firstPtPer is None):\n self.firstPtTan = None\n self.firstPtPer = value\n self.firstGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n self.firstGeom.transform(coordTransform) \n # imposto il map tool\n self.getPointMapTool().per1 = self.firstPtPer\n self.getPointMapTool().geom1 = self.firstGeom\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PER_KNOWN_ASK_FOR_SECOND_PT) \n # se era stato selezionato un punto con la modalità TAN_DEF \n elif self.firstPtTan is not None:\n secondGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n secondGeom.transform(coordTransform)\n tangent = qad_utils.lineFromTanPerPts(self.firstGeom, self.firstPtTan, secondGeom, value)\n if tangent is not None:\n # prendo il punto più vicino a value\n if qad_utils.getDistance(tangent[0], value) < qad_utils.getDistance(tangent[1], value): \n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[0]\n else:\n self.addVertex(tangent[0]) # aggiungo un nuovo vertice\n self.addVertex(tangent[1]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = tangent[1]\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n else:\n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo perpendicular possible\"))\n # se era stato selezionato un punto con la modalità PER_DEF \n elif self.firstPtPer is not None:\n secondGeom = QgsGeometry(entity.getGeometry()) # duplico la geometria \n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n secondGeom.transform(coordTransform)\n line = qad_utils.lineFrom2PerPts(self.firstGeom, self.firstPtPer, secondGeom, value)\n if line is not None:\n # prendo il punto più vicino a value\n if qad_utils.getDistance(line[0], value) < qad_utils.getDistance(line[1], value): \n self.addVertex(line[1]) # aggiungo un nuovo vertice\n self.addVertex(line[0]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = line[0]\n else:\n self.addVertex(line[0]) # aggiungo un nuovo vertice\n self.addVertex(line[1]) # aggiungo un nuovo vertice\n self.getPointMapTool().firstPt = line[1]\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n else:\n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo perpendicular possible\"))\n else: # altrimenti é un punto esplicito\n # se era stato selezionato un punto con la modalità TAN_DEF\n if self.firstPtTan is not None:\n snapper = QadSnapper()\n snapper.setSnapPointCRS(self.plugIn.canvas.mapRenderer().destinationCrs())\n snapper.setSnapType(QadSnapTypeEnum.TAN)\n snapper.setStartPoint(value)\n oSnapPoints = snapper.getSnapPoint(self.firstGeom, self.firstPtTan, \n self.plugIn.canvas.mapRenderer().destinationCrs())\n # memorizzo il punto di snap in point (prendo il primo valido)\n for item in oSnapPoints.items():\n points = item[1]\n if points is not None:\n self.addVertex(points[0]) # aggiungo un nuovo vertice\n self.addVertex(value) # aggiungo un nuovo vertice\n break\n\n if len(self.vertices) == 0:\n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo tangent possible\")) \n # se era stato selezionato un punto con la modalità PER_DEF\n elif self.firstPtPer is not None:\n snapper = QadSnapper()\n snapper.setSnapPointCRS(self.plugIn.canvas.mapRenderer().destinationCrs())\n snapper.setSnapType(QadSnapTypeEnum.PER)\n snapper.setStartPoint(value)\n oSnapPoints = snapper.getSnapPoint(self.firstGeom, self.firstPtPer, \n self.plugIn.canvas.mapRenderer().destinationCrs())\n # memorizzo il punto di snap in point (prendo il primo valido)\n for item in oSnapPoints.items():\n points = item[1]\n if points is not None:\n self.addVertex(points[0]) # aggiungo un nuovo vertice\n self.addVertex(value) # aggiungo un nuovo vertice\n break\n\n if len(self.vertices) == 0: \n self.showMsg(QadMsg.translate(\"Command_LINE\", \"\\nNo perpendicular possible\"))\n else:\n self.addVertex(value) # aggiungo un nuovo vertice\n\n if len(self.vertices) > 0: \n # imposto il map tool\n self.getPointMapTool().firstPt = value\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n else: # secondo punto\n if value is None:\n if self.virtualCmd == False: # se si vuole veramente salvare in un layer \n self.addLinesToLayer(currLayer)\n return True # fine comando\n # se il primo punto é esplicito\n if len(self.vertices) > 0 is not None:\n self.addVertex(value) # aggiungo un nuovo vertice \n # imposto il map tool\n self.getPointMapTool().firstPt = value\n self.getPointMapTool().setMode(Qad_line_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n\n if len(self.vertices) > 2:\n keyWords = QadMsg.translate(\"Command_LINE\", \"Close\") + \"/\" + \\\n QadMsg.translate(\"Command_LINE\", \"Undo\")\n else:\n keyWords = QadMsg.translate(\"Command_LINE\", \"Undo\")\n prompt = QadMsg.translate(\"Command_LINE\", \"Specify next point or [{0}]: \").format(keyWords)\n \n englishKeyWords = \"Close\" + \"/\" + \"Undo\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n \n return False\n "
},
{
"alpha_fraction": 0.5602811574935913,
"alphanum_fraction": 0.5643316507339478,
"avg_line_length": 43.17894744873047,
"blob_id": "57bb66dff2d0ed3dc833a2411a49012ea95f78e2",
"content_id": "cdc33dd2f3cd0e36f0a1761e971ed04e122028a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8397,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 190,
"path": "/qad_offset_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando offset\n \n -------------------\n begin : 2013-10-04\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_highlight import QadHighlight\nfrom qad_dim import QadDimStyles\n\n\n#===============================================================================\n# Qad_offset_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_offset_maptool_ModeEnum():\n # si richiede il primo punto per calcolo offset \n ASK_FOR_FIRST_OFFSET_PT = 1 \n # noto il primo punto per calcolo offset si richiede il secondo punto\n FIRST_OFFSET_PT_KNOWN_ASK_FOR_SECOND_PT = 2 \n # nota la distanza di offset si richiede il punto per stabilire da che parte\n OFFSET_KNOWN_ASK_FOR_SIDE_PT = 3\n # si richiede il punto di passaggio per stabilire da che parte e a quale offset\n ASK_FOR_PASSAGE_PT = 4 \n # si richiede la selezione di un oggetto\n ASK_FOR_ENTITY_SELECTION = 5 \n\n#===============================================================================\n# Qad_offset_maptool class\n#===============================================================================\nclass Qad_offset_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.firstPt = None\n self.layer = None\n self.subGeom = None\n self.offSet = 0\n self.lastOffSetOnLeftSide = 0\n self.lastOffSetOnRightSide = 0\n self.gapType = 0 \n self.__highlight = QadHighlight(self.canvas)\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None \n \n def addOffSetGeometries(self, newPt):\n self.__highlight.reset() \n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(newPt, self.subGeom)\n if self.offSet < 0:\n afterVertex = dummy[2]\n pt = qad_utils.getPerpendicularPointOnInfinityLine(self.subGeom.vertexAt(afterVertex - 1), \\\n self.subGeom.vertexAt(afterVertex), \\\n newPt)\n offSetDistance = qad_utils.getDistance(newPt, pt)\n else: \n offSetDistance = self.offSet\n\n if dummy[3] < 0: # alla sinistra\n offSetDistance = offSetDistance + self.lastOffSetOnLeftSide\n else: # alla destra\n offSetDistance = offSetDistance + self.lastOffSetOnRightSide \n \n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n # uso il crs del canvas per lavorare con coordinate piane xy\n epsg = self.canvas.mapRenderer().destinationCrs().authid()\n lines = qad_utils.offSetPolyline(self.subGeom.asPolyline(), epsg, \\\n offSetDistance, \\\n \"left\" if dummy[3] < 0 else \"right\", \\\n self.gapType, \\\n tolerance2ApproxCurve)\n\n for line in lines:\n if self.layer.geometryType() == QGis.Polygon:\n if line[0] == line[-1]: # se é una linea chiusa\n offsetGeom = QgsGeometry.fromPolygon([line])\n else:\n offsetGeom = QgsGeometry.fromPolyline(line)\n else:\n offsetGeom = QgsGeometry.fromPolyline(line)\n\n self.__highlight.addGeometry(self.mapToLayerCoordinates(self.layer, offsetGeom), self.layer)\n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n # nota la distanza di offset si richiede il punto per stabilire da che parte\n if self.mode == Qad_offset_maptool_ModeEnum.OFFSET_KNOWN_ASK_FOR_SIDE_PT:\n self.addOffSetGeometries(self.tmpPoint) \n # si richiede il punto di passaggio per stabilire da che parte e a quale offset\n elif self.mode == Qad_offset_maptool_ModeEnum.ASK_FOR_PASSAGE_PT:\n self.addOffSetGeometries(self.tmpPoint) \n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__highlight.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.clear()\n self.mode = mode\n # si richiede il primo punto per calcolo offset\n if self.mode == Qad_offset_maptool_ModeEnum.ASK_FOR_FIRST_OFFSET_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.onlyEditableLayers = False\n # noto il primo punto per calcolo offset si richiede il secondo punto\n if self.mode == Qad_offset_maptool_ModeEnum.FIRST_OFFSET_PT_KNOWN_ASK_FOR_SECOND_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.firstPt)\n self.onlyEditableLayers = False\n # nota la distanza di offset si richiede il punto per stabilire da che parte\n elif self.mode == Qad_offset_maptool_ModeEnum.OFFSET_KNOWN_ASK_FOR_SIDE_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.onlyEditableLayers = False\n # si richiede il punto di passaggio per stabilire da che parte e a quale offset\n elif self.mode == Qad_offset_maptool_ModeEnum.ASK_FOR_PASSAGE_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.onlyEditableLayers = False\n # si richiede la selezione di un oggetto\n elif self.mode == Qad_offset_maptool_ModeEnum.ASK_FOR_ENTITY_SELECTION:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.onlyEditableLayers = True\n"
},
{
"alpha_fraction": 0.5432857871055603,
"alphanum_fraction": 0.5474792718887329,
"avg_line_length": 44.470340728759766,
"blob_id": "fd47b329901ea0d3b0147dbb438cc51bd8c56048",
"content_id": "69f96a51baef19dc560b576129a7a1b80a8ea668",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10738,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 236,
"path": "/qad_fillet_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando fillet\n \n -------------------\n begin : 2014-01-31\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_rubberband import QadRubberBand\nfrom qad_dim import QadDimStyles\n\n\n#===============================================================================\n# Qad_fillet_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_fillet_maptool_ModeEnum():\n # si richiede la selezione del primo oggetto\n ASK_FOR_FIRST_LINESTRING = 1 \n # si richiede la selezione del secondo oggetto\n ASK_FOR_SECOND_LINESTRING = 2 \n # non si richiede niente\n NONE = 3\n # si richiede la selezione della polilinea\n ASK_FOR_POLYLINE = 4 \n\n\n#===============================================================================\n# Qad_fillet_maptool class\n#===============================================================================\nclass Qad_fillet_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n\n self.filletMode = 1 # modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n self.radius = 0.0\n \n self.layer = None \n self.linearObjectList = qad_utils.QadLinearObjectList()\n self.partAt1 = 0\n self.vertexAt1 = 0\n \n self.tolerance2ApproxCurve = None\n\n self.__rubberBand = QadRubberBand(self.canvas)\n\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__rubberBand.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__rubberBand.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__rubberBand.reset()\n self.mode = None\n\n def setEntityInfo(self, layer, featureId, linearObjectList, partAt, pointAt):\n \"\"\"\n Setta self.entity, self.atSubGeom, self.linearObjectList, self.partAt, self.pointAt\n di primo o del secondo oggetto da raccordare (vedi <firstObj>)\n \"\"\"\n self.layer = layer\n self.featureId = featureId\n self.linearObjectList.set(linearObjectList)\n self.partAt = partAt\n self.pointAt = pointAt\n\n self.tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n\n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__rubberBand.reset()\n tmpLinearObjectList = None\n \n # si richiede la selezione del secondo oggetto\n if self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_SECOND_LINESTRING:\n if self.tmpEntity.isInitialized(): \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.tmpEntity.layer, self.tmpEntity.getGeometry())\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(self.tmpPoint, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2]) \n tmpLinearObjectList = qad_utils.QadLinearObjectList() \n tmpLinearObjectList.fromPolyline(subGeom.asPolyline())\n \n # la funzione ritorna una lista con (<minima distanza al quadrato>,\n # <punto più vicino>\n # <indice della parte più vicina> \n # <\"a sinistra di\">)\n dummy = tmpLinearObjectList.closestPartWithContext(self.tmpPoint)\n tmpPartAt = dummy[2]\n tmpPointAt = dummy[1]\n \n # stessa entità e stessa parte\n if self.layer.id() == self.tmpEntity.layer.id() and \\\n self.featureId == self.tmpEntity.featureId and \\\n self.partAt == tmpPartAt:\n return\n\n # uso il crs del canvas per lavorare con coordinate piane xy\n epsg = self.canvas.mapRenderer().destinationCrs().authid()\n \n if self.tmpShiftKey == True: # tasto shift premuto durante il movimento del mouse\n # filletMode = 1 # modalità di raccordo; 1=Taglia-estendi\n # raggio = 0\n res = qad_utils.getFilletLinearObjectList(self.linearObjectList, self.partAt, self.pointAt, \\\n tmpLinearObjectList, tmpPartAt, tmpPointAt,\\\n 1, 0, epsg)\n else: \n res = qad_utils.getFilletLinearObjectList(self.linearObjectList, self.partAt, self.pointAt, \\\n tmpLinearObjectList, tmpPartAt, tmpPointAt,\\\n self.filletMode, self.radius, epsg)\n if res is None: # raccordo non possibile\n return\n tmpLinearObjectList = res[0]\n \n # si richiede la selezione della polilinea\n elif self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_POLYLINE:\n if self.tmpEntity.isInitialized():\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.tmpEntity.layer, self.tmpEntity.getGeometry())\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(self.tmpPoint, geom)\n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2]) \n tmpLinearObjectList = qad_utils.QadLinearObjectList()\n tmpLinearObjectList.fromPolyline(subGeom.asPolyline())\n tmpLinearObjectList.fillet(self.radius)\n \n if tmpLinearObjectList is not None:\n pts = tmpLinearObjectList.asPolyline(self.tolerance2ApproxCurve)\n if self.layer.geometryType() == QGis.Polygon:\n geom = QgsGeometry.fromPolygon([pts])\n else:\n geom = QgsGeometry.fromPolyline(pts)\n \n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n geom = self.layerToMapCoordinates(self.layer, geom) \n self.__rubberBand.addGeometry(geom, self.layer)\n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__rubberBand.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__rubberBand.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n\n # si richiede la selezione del primo oggetto\n # si richiede la selezione del secondo oggetto\n if self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_FIRST_LINESTRING or \\\n self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_SECOND_LINESTRING:\n \n if self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_FIRST_LINESTRING:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n else:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC)\n\n # solo layer lineari editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line and layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n # non si richiede niente\n elif self.mode == Qad_fillet_maptool_ModeEnum.NONE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si richiede la selezione della polilinea\n elif self.mode == Qad_fillet_maptool_ModeEnum.ASK_FOR_POLYLINE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC)\n\n # solo layer lineari o poligono editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n (layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon) and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n"
},
{
"alpha_fraction": 0.5554901957511902,
"alphanum_fraction": 0.5593855381011963,
"avg_line_length": 44.81144714355469,
"blob_id": "6128ed7d7042eb7497d9a0ee1ecac7da5dd65da0",
"content_id": "7b3b91724eedabd78b2adf963e622f45c67b1617",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13617,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 297,
"path": "/qad_break_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando SPEZZA per tagliare un oggetto \n \n -------------------\n begin : 2014-01-09\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_snapper import *\nfrom qad_getpoint import *\nfrom qad_textwindow import *\nfrom qad_entsel_cmd import QadEntSelClass\nfrom qad_msg import QadMsg\nimport qad_layer\n\n# Classe che gestisce il comando BREAK\nclass QadBREAKCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadBREAKCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"BREAK\")\n\n def getEnglishName(self):\n return \"BREAK\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runBREAKCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/break.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_BREAK\", \"Breaks an object.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.EntSelClass = None \n self.firstPt = None\n self.secondPt = None\n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.EntSelClass is not None:\n self.EntSelClass.entity.deselectOnLayer()\n del self.EntSelClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 1: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n \n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass\n self.step = 1 \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_BREAK\", \"Select the object to break: \")\n # scarto la selezione di punti e poligoni\n self.EntSelClass.checkPointLayer = False\n self.EntSelClass.checkLineLayer = True\n self.EntSelClass.checkPolygonLayer = False\n self.EntSelClass.checkDimLayers = False \n self.EntSelClass.onlyEditableLayers = True \n\n self.EntSelClass.run(msgMapTool, msg)\n\n\n #============================================================================\n # breakFeatures\n #============================================================================\n def breakFeatures(self):\n f = self.EntSelClass.entity.getFeature()\n if f is None:\n return\n \n layer = self.EntSelClass.entity.layer\n LineTempLayer = None\n self.plugIn.beginEditCommand(\"Feature broken\", layer)\n \n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\")) \n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n g = self.layerToMapCoordinates(layer, f.geometry()) \n result = qad_utils.breakQgsGeometry(g, self.firstPt, self.secondPt, \\\n tolerance2ApproxCurve) \n if result is not None:\n line1 = result[0]\n line2 = result[1]\n atSubGeom = result[2]\n if layer.geometryType() == QGis.Line:\n if line1 is not None:\n updGeom = qad_utils.setSubGeom(g, line1, atSubGeom)\n if updGeom is None:\n self.plugIn.destroyEditCommand()\n return\n brokenFeature1 = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n brokenFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, brokenFeature1, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n if line2 is not None:\n brokenFeature2 = QgsFeature(f) \n # trasformo la geometria nel crs del layer\n brokenFeature2.setGeometry(self.mapToLayerCoordinates(layer, line2))\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(self.plugIn, layer, brokenFeature2, None, False, False) == False:\n self.plugIn.destroyEditCommand()\n return \n else:\n # aggiungo le linee nei layer temporanei di QAD\n if LineTempLayer is None:\n LineTempLayer = qad_layer.createQADTempLayer(self.plugIn, QGis.Line)\n self.plugIn.addLayerToLastEditCommand(\"Feature broken\", LineTempLayer)\n \n lineGeoms = []\n if line1 is not None:\n lineGeoms.append(line1)\n if line2 is not None:\n lineGeoms.append(line2)\n\n # trasformo la geometria in quella dei layer temporanei\n # plugIn, pointGeoms, lineGeoms, polygonGeoms, coord, refresh\n if qad_layer.addGeometriesToQADTempLayers(self.plugIn, None, lineGeoms, None, None, False) == False:\n self.plugIn.destroyEditCommand()\n return\n \n updGeom = qad_utils.delSubGeom(g, atSubGeom)\n\n if updGeom is None or updGeom.isGeosEmpty(): # da cancellare\n # plugIn, layer, feature id, refresh\n if qad_layer.deleteFeatureToLayer(self.plugIn, layer, f.id(), False) == False:\n self.plugIn.destroyEditCommand()\n return\n else:\n brokenFeature1 = QgsFeature(f)\n # trasformo la geometria nel crs del layer\n brokenFeature1.setGeometry(self.mapToLayerCoordinates(layer, updGeom))\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(self.plugIn, layer, brokenFeature1, False, False) == False:\n self.plugIn.destroyEditCommand()\n return\n\n self.plugIn.endEditCommand()\n\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n if self.step == 0: \n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n \n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN'ENTITA' (da step = 0)\n elif self.step == 1:\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized():\n layer = self.EntSelClass.entity.layer\n self.firstPt = self.EntSelClass.point\n self.plugIn.setLastPoint(self.firstPt)\n \n keyWords = QadMsg.translate(\"Command_BREAK\", \"First point\")\n prompt = QadMsg.translate(\"Command_BREAK\", \"Specify second break point or [{0}]: \").format(keyWords)\n \n self.step = 2\n self.getPointMapTool().refreshSnapType() # aggiorno lo snapType che può essere variato dal maptool di selezione entità\n \n englishKeyWords = \"First point\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE) \n return False\n else: \n self.showMsg(QadMsg.translate(\"Command_BREAK\", \"Non ci sono geometrie in questa posizione.\"))\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL SECONDO PUNTO DI INTERRUZIONE (da step = 1)\n elif self.step == 2: # dopo aver atteso un punto o una parola chiave si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n pass # opzione di default \"secondo punto\"\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None or type(value) == unicode:\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_BREAK\", \"Specify first break point: \")) \n self.step = 3\n elif type(value) == QgsPoint: # se é stato inserito il secondo punto\n self.secondPt = value\n self.plugIn.setLastPoint(self.secondPt)\n self.breakFeatures() \n return True\n \n return False \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL PRIMO PUNTO DI INTERRUZIONE (da step = 2)\n elif self.step == 3: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.firstPt = value\n self.plugIn.setLastPoint(self.firstPt)\n\n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_BREAK\", \"Specify second break point: \")) \n self.step = 4\n \n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL SECONDO PUNTO DI INTERRUZIONE (da step = 3)\n elif self.step == 4: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n self.secondPt = value\n self.plugIn.setLastPoint(self.secondPt)\n self.breakFeatures() \n \n return True\n"
},
{
"alpha_fraction": 0.5343422293663025,
"alphanum_fraction": 0.5379464030265808,
"avg_line_length": 46.27202224731445,
"blob_id": "969eaf68b93f96fdb874ec641b64f28283af969d",
"content_id": "260cd484ed62bfee080fb466b56107179ea7473d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 48876,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 1033,
"path": "/qad_dim_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando COPY per copiare oggetti\n \n -------------------\n begin : 2014-02-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_dim import *\nfrom qad_dim_maptool import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_getpoint import *\nfrom qad_textwindow import *\nfrom qad_entsel_cmd import QadEntSelClass\nfrom qad_getangle_cmd import QadGetAngleClass\nfrom qad_variables import *\nimport qad_utils\nimport qad_layer\n\n\n#============================================================================\n# FUNZIONI GENERICHE - INIZIO\n#============================================================================\n\n\n#============================================================================\n# getStartEndPointClosestPartWithContext\n#============================================================================\ndef getStartEndPointClosestPartWithContext(entity, point, destCrs):\n # legge il punto iniziale e finale della parte più vicina al punto di selezione\n # se non si tratta di cerchio altrimenti ritorna l'oggetto QadCircle\n geom = entity.getGeometry()\n\n # trasformo la geometria in screen coordinate\n coordTransform = QgsCoordinateTransform(entity.layer.crs(), destCrs) # trasformo la geometria\n geom.transform(coordTransform) \n\n return qad_utils.whatGeomIs(point, geom)\n\n\n#============================================================================\n# FUNZIONI GENERICHE - FINE\n#============================================================================\n\n\n# Classe che gestisce il comando DIMLINEAR\nclass QadDIMLINEARCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadDIMLINEARCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"DIMLINEAR\")\n\n def getEnglishName(self):\n return \"DIMLINEAR\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runDIMLINEARCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/dimLinear.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_DIM\", \"Creates an horizontal or vertical linear dimension.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.EntSelClass = None\n self.GetAngleClass = None\n \n self.dimPt1 = QgsPoint() # primo punto di quotatura esplicito\n self.dimPt2 = QgsPoint() # secondo punto di quotatura esplicito\n self.dimCircle = None # oggetto cerchio da quotare\n \n self.measure = None # misura della quota (se None viene calcolato)\n self.preferredAlignment = QadDimStyleAlignmentEnum.HORIZONTAL # allineamento della linea di quota\n # leggo lo stile di quotatura corrente\n dimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n self.forcedDimLineAlignment = None # allineamento della linea di quota forzato\n self.forcedDimLineRot = 0.0 # rotazione della linea di quota forzato\n \n _dimStyle = QadDimStyles.findDimStyle(dimStyleName)\n if _dimStyle is not None:\n self.dimStyle = QadDimStyle(_dimStyle) # ne faccio una copia perché può venire modificato dal comando\n self.dimStyle.dimType = QadDimTypeEnum.LINEAR\n else:\n self.dimStyle = None\n \n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.EntSelClass is not None:\n self.EntSelClass.entity.deselectOnLayer()\n del self.EntSelClass\n if self.GetAngleClass is not None:\n del self.GetAngleClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 2: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n # quando si é in fase di richiesta rotazione\n elif self.step == 6 or self.step == 7:\n return self.GetAngleClass.getPointMapTool()\n else:\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_dim_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n \n #============================================================================\n # addDimToLayers\n #============================================================================\n def addDimToLayers(self, linePosPt):\n return self.dimStyle.addLinearDimToLayers(self.plugIn, self.dimPt1, self.dimPt2, \\\n linePosPt, self.measure, self.preferredAlignment, \\\n self.forcedDimLineRot)\n \n \n #============================================================================\n # waitForFirstPt\n #============================================================================\n def waitForFirstPt(self):\n self.step = 1\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT) \n\n msg = QadMsg.translate(\"Command_DIM\", \"Specify first extension line origin or <select object>: \")\n \n # si appresta ad attendere un punto o enter \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(msg, \\\n QadInputTypeEnum.POINT2D, \\\n None, \\\n \"\", QadInputModeEnum.NONE)\n\n \n #============================================================================\n # waitForSecondPt\n #============================================================================\n def waitForSecondPt(self):\n self.step = 3\n # imposto il map tool\n self.getPointMapTool().dimPt1 = self.dimPt1\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_DIM\", \"Specify second extension line origin: \"))\n\n \n #============================================================================\n # waitForEntsel\n #============================================================================\n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass\n self.step = 2 \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_DIM\", \"Select the object to dimension: \")\n # scarto la selezione di punti\n self.EntSelClass.checkPointLayer = False\n self.EntSelClass.checkLineLayer = True\n self.EntSelClass.checkPolygonLayer = True\n self.EntSelClass.getPointMapTool().setSnapType(QadSnapTypeEnum.DISABLE) \n self.EntSelClass.run(msgMapTool, msg)\n\n \n #============================================================================\n # waitForDimensionLinePos\n #============================================================================\n def waitForDimensionLinePos(self):\n self.step = 4\n # imposto il map tool \n self.getPointMapTool().dimPt2 = self.dimPt2\n if self.getPointMapTool().dimPt1 is None: # in caso di selezione oggetto dimPt1 non era stato inizializzato\n self.getPointMapTool().dimPt1 = self.dimPt1\n self.getPointMapTool().dimCircle = self.dimCircle\n self.getPointMapTool().preferredAlignment = self.preferredAlignment\n self.getPointMapTool().forcedDimLineAlignment = self.forcedDimLineAlignment\n self.getPointMapTool().forcedDimLineRot = self.forcedDimLineRot \n self.getPointMapTool().dimStyle = self.dimStyle \n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.FIRST_SECOND_PT_KNOWN_ASK_FOR_LINEAR_DIM_LINE_POS) \n \n # si appresta ad attendere un punto o una parola chiave\n keyWords = QadMsg.translate(\"Command_DIM\", \"Text\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Horizontal\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Vertical\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Rotated\") \n prompt = QadMsg.translate(\"Command_DIM\", \"Specify dimension line location or [{0}]: \").format(keyWords)\n \n englishKeyWords = \"Text\" + \"/\" + \"Angle\" + \"/\" + \"Horizontal\" + \"/\" + \"Vertical\" + \"/\" + \"Rotated\"\n keyWords += \"_\" + englishKeyWords\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, \\\n QadInputModeEnum.NONE) \n \n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.dimStyle is None:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nDimension style not valid.\\nVerify the value of DIMSTYLE variable.\\n\"))\n return True # fine comando\n \n errMsg = self.dimStyle.getInValidErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n \n errMsg = self.dimStyle.getNotGraphEditableErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n\n\n #=========================================================================\n # RICHIESTA SELEZIONE ORIGINE PRIMA LINEA DI ESTENSIONE\n if self.step == 0: # inizio del comando \n self.waitForFirstPt()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ORIGINE PRIMA LINEA DI ESTENSIONE (da step = 0)\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = None # opzione di default None\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n self.waitForEntsel(msgMapTool, msg)\n else:\n self.dimPt1.set(value.x(), value.y())\n self.waitForSecondPt()\n\n return False\n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN'ENTITA' (da step = 1)\n elif self.step == 2:\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized():\n result = getStartEndPointClosestPartWithContext(self.EntSelClass.entity, \\\n self.EntSelClass.point, \\\n self.plugIn.canvas.mapRenderer().destinationCrs())\n if result is not None: \n if (type(result) == list or type(result) == tuple): # se é una lista di 2 punti\n self.dimPt1 = result[0] \n self.dimPt2 = result[1]\n else:\n objType = result.whatIs()\n if objType == \"ARC\": # se é arco\n self.dimPt1 = result.getStartPt() \n self.dimPt2 = result.getEndPt()\n elif objType == \"CIRCLE\": # se é cerchio\n self.dimCircle = result\n \n self.waitForDimensionLinePos()\n return False\n else: \n self.showMsg(QadMsg.translate(\"Command_DIM\", \"No geometries in this position.\"))\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ORIGINE SECONDA LINEA DI ESTENSIONE (da step = 1)\n elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n return True\n\n if type(value) == QgsPoint: # se é stato inserito il secondo punto\n self.dimPt2.set(value.x(), value.y())\n self.waitForDimensionLinePos()\n \n return False \n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA POSIZIONE DELLA LINEA DI QUOTA (da step = 2 e 3)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_DIM\", \"Text\") or value == \"Text\":\n prompt = QadMsg.translate(\"Command_DIM\", \"Enter dimension text <{0}>: \")\n dist = qad_utils.getDistance(self.dimPt1, self.dimPt2)\n self.waitForString(prompt.format(str(dist)), dist)\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.ASK_FOR_TEXT)\n self.step = 5 \n elif value == QadMsg.translate(\"Command_DIM\", \"Angle\") or value == \"Angle\":\n # si appresta ad attendere l'angolo di rotazione del testo\n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_DIM\", \"Specify angle of dimension text <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.dimStyle.textForcedRot)))\n self.GetAngleClass.angle = self.dimStyle.textForcedRot\n self.step = 6\n self.GetAngleClass.run(msgMapTool, msg) \n elif value == QadMsg.translate(\"Command_DIM\", \"Horizontal\") or value == \"Horizontal\":\n # allineamento della linea di quota orizzontale\n self.forcedDimLineAlignment = QadDimStyleAlignmentEnum.HORIZONTAL # allineamento della linea di quota forzato \n self.forcedDimLineRot = 0.0 \n self.waitForDimensionLinePos()\n elif value == QadMsg.translate(\"Command_DIM\", \"Vertical\") or value == \"Vertical\":\n # allineamento della linea di quota verticale \n self.forcedDimLineAlignment = QadDimStyleAlignmentEnum.VERTICAL # allineamento della linea di quota forzato\n self.forcedDimLineRot = 0.0 \n self.waitForDimensionLinePos()\n elif value == QadMsg.translate(\"Command_DIM\", \"Rotated\") or value == \"Rotated\":\n # si appresta ad attendere l'angolo di rotazionedella linea di quotatura\n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_DIM\", \"Specify angle of dimension line <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.forcedDimLineRot)))\n self.GetAngleClass.angle = self.forcedDimLineRot\n self.step = 7\n self.GetAngleClass.run(msgMapTool, msg) \n pass\n elif type(value) == QgsPoint: # se é stato inserito il punto di posizionamento linea quota\n self.preferredAlignment = self.getPointMapTool().preferredAlignment\n self.dimPt1 = self.getPointMapTool().dimPt1\n self.dimPt2 = self.getPointMapTool().dimPt2\n self.addDimToLayers(value)\n return True # fine comando\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL TESTO (da step = 4)\n elif self.step == 5: # dopo aver atteso una stringa si riavvia il comando\n if type(msg) == unicode:\n text = msg.strip()\n if len(text) > 0:\n self.measure = text\n self.getPointMapTool().measure = self.measure\n self.waitForDimensionLinePos()\n \n return False\n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ROTAZIONE DEL TESTO DI QUOTA (da step = 4)\n elif self.step == 6:\n if self.GetAngleClass.run(msgMapTool, msg) == True:\n if self.GetAngleClass.angle is not None:\n self.dimStyle.textRotMode = QadDimStyleTxtRotModeEnum.FORCED_ROTATION\n self.dimStyle.textForcedRot = self.GetAngleClass.angle \n self.waitForDimensionLinePos()\n\n return False\n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ROTAZIONE DELLA LINEA DI QUOTA (da step = 4)\n elif self.step == 7:\n if self.GetAngleClass.run(msgMapTool, msg) == True:\n if self.GetAngleClass.angle is not None:\n self.forcedDimLineRot = self.GetAngleClass.angle \n self.waitForDimensionLinePos()\n\n return False\n\n \n# Classe che gestisce il comando DIMALIGNED\nclass QadDIMALIGNEDCommandClass(QadCommandClass):\n \n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadDIMALIGNEDCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"DIMALIGNED\")\n\n def getEnglishName(self):\n return \"DIMALIGNED\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runDIMALIGNEDCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/dimAligned.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_DIM\", \"Creates an aligned linear dimension.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.EntSelClass = None\n self.GetAngleClass = None\n \n self.dimPt1 = QgsPoint()\n self.dimPt2 = QgsPoint()\n self.dimCircle = None # oggetto cerchio da quotare\n \n self.measure = None # misura della quota (se None viene calcolato)\n # leggo lo stile di quotatura corrente\n dimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n _dimStyle = QadDimStyles.findDimStyle(dimStyleName) \n if _dimStyle is not None:\n self.dimStyle = QadDimStyle(_dimStyle) # ne faccio una copia perché può venire modificato dal comando\n self.dimStyle.dimType = QadDimTypeEnum.ALIGNED\n else:\n self.dimStyle = None\n \n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.EntSelClass is not None:\n self.EntSelClass.entity.deselectOnLayer()\n del self.EntSelClass\n if self.GetAngleClass is not None:\n del self.GetAngleClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 2: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n # quando si é in fase di richiesta rotazione\n elif self.step == 6:\n return self.GetAngleClass.getPointMapTool()\n else:\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_dim_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n \n #============================================================================\n # addDimToLayers\n #============================================================================\n def addDimToLayers(self, linePosPt):\n return self.dimStyle.addAlignedDimToLayers(self.plugIn, self.dimPt1, self.dimPt2, \\\n linePosPt, self.measure)\n\n \n #============================================================================\n # waitForFirstPt\n #============================================================================\n def waitForFirstPt(self):\n self.step = 1\n # imposto il map tool\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT) \n\n msg = QadMsg.translate(\"Command_DIM\", \"Specify first extension line origin or <select object>: \")\n \n # si appresta ad attendere un punto o enter \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(msg, \\\n QadInputTypeEnum.POINT2D, \\\n None, \\\n \"\", QadInputModeEnum.NONE)\n\n \n #============================================================================\n # waitForSecondPt\n #============================================================================\n def waitForSecondPt(self):\n self.step = 3\n # imposto il map tool\n self.getPointMapTool().dimPt1 = self.dimPt1\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT) \n # si appresta ad attendere un punto\n self.waitForPoint(QadMsg.translate(\"Command_DIM\", \"Specify second extension line origin: \"))\n\n \n #============================================================================\n # waitForEntsel\n #============================================================================\n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass\n self.step = 2 \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_DIM\", \"Select the object to dimension: \")\n # scarto la selezione di punti\n self.EntSelClass.checkPointLayer = False\n self.EntSelClass.checkLineLayer = True\n self.EntSelClass.checkPolygonLayer = True\n self.EntSelClass.getPointMapTool().setSnapType(QadSnapTypeEnum.DISABLE) \n self.EntSelClass.run(msgMapTool, msg)\n\n \n #============================================================================\n # waitForDimensionLinePos\n #============================================================================\n def waitForDimensionLinePos(self):\n self.step = 4\n # imposto il map tool \n self.getPointMapTool().dimPt2 = self.dimPt2\n if self.getPointMapTool().dimPt1 is None: # in caso di selezione oggetto dimPt1 non era stato inizializzato\n self.getPointMapTool().dimPt1 = self.dimPt1\n self.getPointMapTool().dimCircle = self.dimCircle\n self.getPointMapTool().dimStyle = self.dimStyle \n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.FIRST_SECOND_PT_KNOWN_ASK_FOR_ALIGNED_DIM_LINE_POS) \n \n # si appresta ad attendere un punto o una parola chiave\n keyWords = QadMsg.translate(\"Command_DIM\", \"Text\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Angle\") \n prompt = QadMsg.translate(\"Command_DIM\", \"Specify dimension line location or [{0}]: \").format(keyWords)\n englishKeyWords = \"Text\" + \"/\" + \"Angle\"\n keyWords += \"_\" + englishKeyWords\n \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, \\\n QadInputModeEnum.NONE) \n \n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.dimStyle is None:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nDimension style not valid.\\nVerify the value of DIMSTYLE variable.\\n\"))\n return True # fine comando\n \n errMsg = self.dimStyle.getInValidErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n \n errMsg = self.dimStyle.getNotGraphEditableErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n\n\n #=========================================================================\n # RICHIESTA SELEZIONE ORIGINE PRIMA LINEA DI ESTENSIONE\n if self.step == 0: # inizio del comando \n self.waitForFirstPt()\n return False\n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ORIGINE PRIMA LINEA DI ESTENSIONE (da step = 0)\n elif self.step == 1:\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n value = None # opzione di default None\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n else:\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n self.waitForEntsel(msgMapTool, msg)\n else:\n self.dimPt1.set(value.x(), value.y())\n self.waitForSecondPt()\n\n return False\n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN'ENTITA' (da step = 1)\n elif self.step == 2:\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized():\n result = getStartEndPointClosestPartWithContext(self.EntSelClass.entity, \\\n self.EntSelClass.point, \\\n self.plugIn.canvas.mapRenderer().destinationCrs())\n if result is not None:\n if (type(result) == list or type(result) == tuple): # se é una lista di 2 punti\n self.dimPt1 = result[0] \n self.dimPt2 = result[1]\n else:\n objType = result.whatIs()\n if objType == \"ARC\": # se é arco\n self.dimPt1 = result.getStartPt() \n self.dimPt2 = result.getEndPt()\n elif objType == \"CIRCLE\": # se é cerchio\n self.dimCircle = result\n intPts = self.dimCircle.getIntersectionPointsWithInfinityLine(self.dimCircle.center, self.EntSelClass.point)\n if len(intPts) == 2:\n self.dimPt1 = intPts[0]\n self.dimPt2 = intPts[1] \n \n self.waitForDimensionLinePos()\n return False\n else: \n self.showMsg(QadMsg.translate(\"Command_DIM\", \"No geometries in this position.\"))\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ORIGINE SECONDA LINEA DI ESTENSIONE (da step = 1)\n elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n return True\n\n if type(value) == QgsPoint: # se é stato inserito il secondo punto\n self.dimPt2.set(value.x(), value.y())\n self.waitForDimensionLinePos()\n \n return False \n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA POSIZIONE DELLA LINEA DI QUOTA (da step = 2 e 3)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_DIM\", \"Text\") or value == \"Text\":\n prompt = QadMsg.translate(\"Command_DIM\", \"Enter dimension text <{0}>: \")\n dist = qad_utils.getDistance(self.dimPt1, self.dimPt2)\n self.waitForString(prompt.format(str(dist)), dist)\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.ASK_FOR_TEXT)\n self.step = 5 \n elif value == QadMsg.translate(\"Command_DIM\", \"Angle\") or value == \"Angle\":\n # si appresta ad attendere l'angolo di rotazione del testo\n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_DIM\", \"Specify angle of dimension text <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.dimStyle.textForcedRot)))\n self.GetAngleClass.angle = self.dimStyle.textForcedRot\n self.step = 6\n self.GetAngleClass.run(msgMapTool, msg) \n elif type(value) == QgsPoint: # se é stato inserito il punto di posizionamento linea quota\n self.dimPt1 = self.getPointMapTool().dimPt1\n self.dimPt2 = self.getPointMapTool().dimPt2\n self.addDimToLayers(value)\n return True # fine comando\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL TESTO (da step = 4)\n elif self.step == 5: # dopo aver atteso una stringa si riavvia il comando\n if type(msg) == unicode:\n text = msg.strip()\n if len(text) > 0:\n self.measure = text\n self.getPointMapTool().measure = self.measure\n self.waitForDimensionLinePos()\n \n return False\n\n \n# Classe che gestisce il comando DIMARC da finire\nclass QadDIMARCCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadDIMARCCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"DIMARC\")\n\n def getEnglishName(self):\n return \"DIMARC\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runDIMARCCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/dimArc.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando\n return QadMsg.translate(\"Command_DIM\", \"Creates an arc length dimension.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.EntSelClass = None\n self.GetAngleClass = None\n \n self.dimPt1 = QgsPoint()\n self.dimPt2 = QgsPoint()\n self.dimArc = None # oggetto arco da quotare\n \n self.measure = None # misura della quota (se None viene calcolato)\n self.leader = False\n # leggo lo stile di quotatura corrente\n dimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n self.dimStyle = QadDimStyles.findDimStyle(dimStyleName)\n if self.dimStyle is not None:\n self.dimStyle.dimType = QadDimTypeEnum.ALIGNED\n \n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.EntSelClass is not None:\n self.EntSelClass.entity.deselectOnLayer()\n del self.EntSelClass\n if self.GetAngleClass is not None:\n del self.GetAngleClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 1: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n # quando si é in fase di richiesta rotazione\n elif self.step == 6:\n return self.GetAngleClass.getPointMapTool()\n else:\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = Qad_dim_maptool(self.plugIn)\n return self.PointMapTool\n else:\n return None\n\n \n #============================================================================\n # addDimToLayers\n #============================================================================\n def addDimToLayers(self, linePosPt):\n return self.dimStyle.addAlignedDimToLayers(self.plugIn, self.dimPt1, self.dimPt2, \\\n linePosPt, self.measure)\n\n \n #============================================================================\n # waitForEntsel\n #============================================================================\n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass\n self.step = 1 \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_DIM\", \"Select arc or polyline arc segment: \")\n # scarto la selezione di punti\n self.EntSelClass.checkPointLayer = False\n self.EntSelClass.checkLineLayer = True\n self.EntSelClass.checkPolygonLayer = True\n self.EntSelClass.getPointMapTool().setSnapType(QadSnapTypeEnum.DISABLE) \n self.EntSelClass.run(msgMapTool, msg)\n\n \n #============================================================================\n # waitForDimensionLinePos\n #============================================================================\n def waitForDimensionLinePos(self):\n self.step = 4\n # imposto il map tool \n self.getPointMapTool().dimPt2 = self.dimPt2\n if self.getPointMapTool().dimPt1 is None: # in caso di selezione oggetto dimPt1 non era stato inizializzato\n self.getPointMapTool().dimPt1 = self.dimPt1\n self.getPointMapTool().dimCircle = self.dimCircle\n self.getPointMapTool().dimStyle = self.dimStyle \n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.FIRST_SECOND_PT_KNOWN_ASK_FOR_ALIGNED_DIM_LINE_POS) \n \n # si appresta ad attendere un punto o una parola chiave\n # si appresta ad attendere un punto o una parola chiave\n keyWords = QadMsg.translate(\"Command_DIM\", \"Text\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Angle\") + \"/\" + \\\n QadMsg.translate(\"Command_DIM\", \"Partial\") + \"/\"\n englishKeyWords = \"Text\" + \"/\" + \"2POints\" + \"/\" + \"Partial\" + \"/\"\n if self.leader:\n keyWords = keyWords + QadMsg.translate(\"Command_DIM\", \"Leader\")\n englishKeyWords = englishKeyWords + \"Leader\"\n else:\n keyWords = keyWords + QadMsg.translate(\"Command_DIM\", \"No leader\")\n englishKeyWords = englishKeyWords + \"No leader\"\n keyWords += \"_\" + englishKeyWordsAngle\n \n prompt = QadMsg.translate(\"Command_DIM\", \"Specify dimension location or [{0}]: \").format(keyWords)\n\n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(prompt, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, \\\n QadInputModeEnum.NONE) \n \n\n #============================================================================\n # run\n #============================================================================\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.dimStyle is None:\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nDimension style not valid.\\nVerify the value of DIMSTYLE variable.\\n\"))\n return True # fine comando\n \n errMsg = self.dimStyle.getInValidErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n \n errMsg = self.dimStyle.getNotGraphEditableErrMsg()\n if errMsg is not None:\n self.showMsg(errMsg)\n return True # fine comando\n\n\n #=========================================================================\n # RICHIESTA SELEZIONE ARCO DA QUOTARE\n if self.step == 0: # inizio del comando \n self.waitForEntsel(msgMapTool, msg)\n return False\n \n\n #=========================================================================\n # RISPOSTA ALLA SELEZIONE DI UN'ENTITA' (da step = 0)\n elif self.step == 1:\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized():\n result = getStartEndPointClosestPartWithContext(self.EntSelClass.entity, \\\n self.EntSelClass.point, \\\n self.plugIn.canvas.mapRenderer().destinationCrs())\n if result is not None:\n if (type(result) != list and type(result) != tuple): # se non é una lista di 2 punti\n objType = result.whatIs()\n if objType == \"ARC\": # se é arco\n self.dimArc = result\n return False\n \n self.showMsg(QadMsg.translate(\"Command_DIM\", \"Select an arc.\"))\n self.waitForEntsel(msgMapTool, msg) \n else: \n self.showMsg(QadMsg.translate(\"Command_DIM\", \"No geometries in this position.\"))\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA ORIGINE SECONDA LINEA DI ESTENSIONE (da step = 1)\n elif self.step == 3: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n return True\n\n if type(value) == QgsPoint: # se é stato inserito il secondo punto\n self.dimPt2.set(value.x(), value.y())\n self.waitForDimensionLinePos()\n \n return False \n \n \n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DELLA POSIZIONE DELLA LINEA DI QUOTA (da step = 2 e 3)\n elif self.step == 4: # dopo aver atteso un punto o un numero reale si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n value = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n value = msg\n\n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_DIM\", \"Text\") or value == \"Text\":\n prompt = QadMsg.translate(\"Command_DIM\", \"Enter dimension text <{0}>: \")\n dist = qad_utils.getDistance(self.dimPt1, self.dimPt2)\n self.waitForString(prompt.format(str(dist)), dist)\n self.getPointMapTool().setMode(Qad_dim_maptool_ModeEnum.ASK_FOR_TEXT)\n self.step = 5 \n elif value == QadMsg.translate(\"Command_DIM\", \"Angle\") or value == \"Angle\":\n # si appresta ad attendere l'angolo di rotazione del testo\n if self.GetAngleClass is not None:\n del self.GetAngleClass \n self.GetAngleClass = QadGetAngleClass(self.plugIn)\n prompt = QadMsg.translate(\"Command_DIM\", \"Specify angle of dimension text <{0}>: \")\n self.GetAngleClass.msg = prompt.format(str(qad_utils.toDegrees(self.dimStyle.textForcedRot)))\n self.GetAngleClass.angle = self.dimStyle.textForcedRot\n self.step = 6\n self.GetAngleClass.run(msgMapTool, msg) \n elif type(value) == QgsPoint: # se é stato inserito il punto di posizionamento linea quota\n self.dimPt1 = self.getPointMapTool().dimPt1\n self.dimPt2 = self.getPointMapTool().dimPt2\n self.addDimToLayers(value)\n return True # fine comando\n \n return False\n\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA DEL TESTO (da step = 4)\n elif self.step == 5: # dopo aver atteso una stringa si riavvia il comando\n if type(msg) == unicode:\n text = msg.strip()\n if len(text) > 0:\n self.measure = text\n self.getPointMapTool().measure = self.measure\n self.waitForDimensionLinePos()\n \n return False\n"
},
{
"alpha_fraction": 0.607061505317688,
"alphanum_fraction": 0.6092358827590942,
"avg_line_length": 39.75105667114258,
"blob_id": "eb2c796484dab5a831081010908cdf4572b4541f",
"content_id": "311502f83fa43058d1cedd380bc9cc9636f267e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9662,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 237,
"path": "/qad_generic_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe base per un comando\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nfrom qad_getpoint import *\n\n\n# Classe che gestisce un comando generico\nclass QadCommandClass():\n def showMsg(self, msg, displayPromptAfterMsg = False):\n if self.plugIn is not None:\n self.plugIn.showMsg(msg, displayPromptAfterMsg)\n \n def showErr(self, err):\n if self.plugIn is not None:\n self.plugIn.showErr(err)\n\n def showInputMsg(self, inputMsg, inputType, default = None, keyWords = \"\", \\\n inputMode = QadInputModeEnum.NONE):\n if self.plugIn is not None:\n self.plugIn.showInputMsg(inputMsg, inputType, default, keyWords, inputMode)\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if (self.plugIn is not None):\n if self.PointMapTool is None:\n self.PointMapTool = QadGetPoint(self.plugIn, drawMode) # per selezione di un punto\n return self.PointMapTool\n else:\n return None\n\n def hidePointMapToolMarkers(self):\n if self.PointMapTool is not None:\n self.PointMapTool.hidePointMapToolMarkers()\n\n def setMapTool(self, mapTool):\n if self.plugIn is not None:\n # setto il maptool per l'input via finestra grafica\n self.plugIn.canvas.setMapTool(mapTool)\n self.plugIn.mainAction.setChecked(True) \n\n def waitForPoint(self, msg = QadMsg.translate(\"QAD\", \"Specify point: \"), \\\n default = None, inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.POINT2D, default, \"\", inputMode)\n\n def waitForString(self, msg, default = None, inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.STRING, default, \"\", inputMode)\n\n def waitForInt(self, msg, default = None, inputMode = QadInputModeEnum.NOT_NULL):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.INT, default, \"\", inputMode)\n\n def waitForlong(self, msg, default = None, inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.LONG, default, \"\", inputMode)\n\n def waitForFloat(self, msg, default = None, inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.FLOAT, default, \"\", inputMode)\n\n def waitForBool(self, msg, default = None, inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.BOOL, default, \"\", inputMode)\n\n def waitForSelSet(self, msg = QadMsg.translate(\"QAD\", \"Select objects: \")):\n self.getPointMapTool().setDrawMode(QadGetPointDrawModeEnum.ELASTIC_RECTANGLE)\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, QadInputTypeEnum.POINT2D)\n\n def waitFor(self, msg, inputType, default = None, keyWords = \"\", \\\n inputMode = QadInputModeEnum.NONE):\n self.setMapTool(self.getPointMapTool())\n # setto l'input via finestra di testo\n self.showInputMsg(msg, inputType, default, keyWords, inputMode)\n\n def getCurrMsgFromTxtWindow(self):\n if self.plugIn is not None:\n return self.plugIn.getCurrMsgFromTxtWindow()\n else:\n return None\n \n def showEvaluateMsg(self, msg = None):\n if self.plugIn is not None:\n self.plugIn.showEvaluateMsg(msg)\n\n def runCommandAbortingTheCurrent(self):\n self.plugIn.runCommandAbortingTheCurrent(self.getName())\n \n def getToolTipText(self):\n text = self.getName()\n if self.getNote() > 0:\n text = text + \"\\n\\n\" + self.getNote()\n return text\n \n #============================================================================\n # funzioni da sovrascrivere con le classi ereditate da questa\n #============================================================================\n def getName(self):\n \"\"\" impostare il nome del comando in maiuscolo \"\"\"\n return \"\"\n\n def getEnglishName(self):\n \"\"\" impostare il nome del comando in inglese maiuscolo \"\"\"\n return \"\"\n\n def connectQAction(self, action):\n pass \n #QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runPLINECommand)\n\n def getIcon(self):\n # impostare l'icona del comando (es. QIcon(\":/plugins/qad/icons/pline.png\"))\n # ricordarsi di inserire l'icona in resources.qrc e di ricompilare le risorse\n return None\n\n def getNote(self):\n \"\"\" impostare le note esplicative del comando \"\"\"\n return \"\"\n \n def __init__(self, plugIn):\n self.plugIn = plugIn\n self.PointMapTool = None\n self.step = 0 \n self.isValidPreviousInput = True\n \n # inizializzare tutti i maptool necessari al comando\n # esempio di struttura di un comando che richiede\n # 1) un punto\n # self.mapTool = QadGetPoint(self.plugIn) # per selezione di un punto\n \n def __del__(self):\n \"\"\" distruttore \"\"\"\n self.hidePointMapToolMarkers()\n if self.PointMapTool:\n self.PointMapTool.removeItems()\n del self.PointMapTool\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return None\n \n def run(self, msgMapTool = False, msg = None):\n \"\"\"\n Esegue il comando. \n - msgMapTool; se True significa che arriva un valore da MapTool del comando\n se false significa che il valore é nel parametro msg\n - msg; valore in input al comando (usato quando msgMapTool = False)\n \n ritorna True se il comando é terminato altrimenti False\n \"\"\"\n # esempio di struttura di un comando che richiede\n # 1) un punto\n if self.step == 0: # inizio del comando\n self.waitForPoint() # si appresta ad attendere un punto\n self.step = self.step + 1\n return False\n elif self.step == 1: # dopo aver atteso un punto si riavvia il comando\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n\n pt = self.getPointMapTool().point\n else: # il punto arriva come parametro della funzione\n pt = msg\n \n return True\n\n def mapToLayerCoordinates(self, layer, point_geom):\n # transform point o geometry coordinates from output CRS to layer's CRS \n if self.plugIn is None:\n return None\n if type(point_geom) == QgsPoint:\n return self.plugIn.canvas.mapRenderer().mapToLayerCoordinates(layer, point_geom)\n elif type(point_geom) == QgsGeometry:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.plugIn.canvas.mapRenderer().destinationCrs(), layer.crs())\n g = QgsGeometry(point_geom)\n g.transform(coordTransform)\n return g\n else:\n return None\n\n def layerToMapCoordinates(self, layer, point_geom):\n # transform point o geometry coordinates from layer's CRS to output CRS \n if self.plugIn is None:\n return None\n if type(point_geom) == QgsPoint:\n return self.plugIn.canvas.mapRenderer().layerToMapCoordinates(layer, point_geom)\n elif type(point_geom) == QgsGeometry:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(layer.crs(), self.plugIn.canvas.mapRenderer().destinationCrs())\n g = QgsGeometry(point_geom)\n g.transform(coordTransform)\n return g\n else:\n return None\n"
},
{
"alpha_fraction": 0.5924269556999207,
"alphanum_fraction": 0.5940027236938477,
"avg_line_length": 44.568111419677734,
"blob_id": "60e801f1ca22d51388f6c9f4460ad1d449eedc1f",
"content_id": "3cb909097f51aa2fdc54abcddec0e1efcdbecd9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 43199,
"license_type": "no_license",
"max_line_length": 149,
"num_lines": 947,
"path": "/qad_getpoint.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool di richiesta di un punto\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_entity import *\nfrom qad_variables import *\nfrom qad_rubberband import *\n\n\n#===============================================================================\n# QadGetPointSelectionModeEnum class.\n#===============================================================================\nclass QadGetPointSelectionModeEnum():\n POINT_SELECTION = 0 # selezione di un punto\n ENTITY_SELECTION = 1 # selezione di una entità in modo statico (cerca l'entità solo con l'evento click)\n ENTITYSET_SELECTION = 2 # selezione di un gruppo di entità \n ENTITY_SELECTION_DYNAMIC = 3 # selezione di una entità in modo dinamico (cerca l'entità con l'evento click e \n # con l'evento mouse move)\n\n\n#===============================================================================\n# QadGetPointDrawModeEnum class.\n#===============================================================================\nclass QadGetPointDrawModeEnum():\n NONE = 0 # nessuno\n ELASTIC_LINE = 1 # linea elastica dal punto __startPoint\n ELASTIC_RECTANGLE = 2 # rettangolo elastico dal punto __startPoint \n\n\nfrom qad_dsettings_dlg import QadDSETTINGSDialog\n\n\n#===============================================================================\n# QadGetPoint get point class\n#===============================================================================\nclass QadGetPoint(QgsMapTool):\n \n def __init__(self, plugIn, drawMode = QadGetPointDrawModeEnum.NONE): \n QgsMapTool.__init__(self, plugIn.iface.mapCanvas())\n self.iface = plugIn.iface\n self.canvas = plugIn.iface.mapCanvas()\n self.plugIn = plugIn\n \n # cursore\n self.__csrRubberBand = None\n \n self.__QadSnapper = None\n self.__QadSnapPointsDisplayManager = None\n self.__oldSnapType = None\n self.__oldSnapProgrDist = None\n self.__geometryTypesAccordingToSnapType = (False, False, False)\n self.__startPoint = None\n self.tmpGeometries = [] # lista di geometria non ancora esistenti ma da contare per i punti di osnap (in map coordinates)\n # opzioni per limitare l'oggetto da selezionare\n self.onlyEditableLayers = False\n self.checkPointLayer = True\n self.checkLineLayer = True\n self.checkPolygonLayer = True\n self.layersToCheck = None\n \n self.__RubberBand = None\n self.__prevGeom = None\n \n self.__stopTimer = True\n \n # setto la modalità di selezione\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n\n self.setDrawMode(drawMode)\n\n self.__QadSnapper = QadSnapper()\n self.__QadSnapper.setSnapPointCRS(self.canvas.mapRenderer().destinationCrs())\n self.__QadSnapper.setSnapLayers(self.canvas.layers())\n self.__QadSnapper.setProgressDistance(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSPROGRDISTANCE\")))\n self.setSnapType(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\")))\n \n self.setOrthoMode() # setto secondo le variabili d'ambiente\n self.setAutoSnap() # setto secondo le variabili d'ambiente\n \n # leggo la tolleranza in unità di mappa\n ToleranceInMapUnits = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) * self.canvas.mapRenderer().mapUnitsPerPixel() \n self.__QadSnapper.setDistToExcludeNea(ToleranceInMapUnits)\n self.__QadSnapper.setToleranceExtParLines(ToleranceInMapUnits)\n\n self.__QadSnapPointsDisplayManager = QadSnapPointsDisplayManager(self.canvas)\n self.__QadSnapPointsDisplayManager.setIconSize(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSSIZE\")))\n self.__QadSnapPointsDisplayManager.setColor(QColor(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSCOLOR\"))))\n \n # output\n self.rightButton = False\n # tasto shift\n self.shiftKey = False\n self.tmpShiftKey = False\n # tasto ctrl\n self.ctrlKey = False\n self.tmpCtrlKey = False\n\n self.point = None # punto selezionato dal click\n self.tmpPoint = None # punto selezionato dal movimento del mouse\n \n self.entity = QadEntity() # entità selezionata dal click\n self.tmpEntity = QadEntity() # entità selezionata dal movimento del mouse\n \n self.snapTypeOnSelection = None # snap attivo al momento del click\n\n def __del__(self):\n self.removeItems()\n \n \n def removeItems(self):\n if self.__csrRubberBand is not None:\n self.__csrRubberBand.removeItems() # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__csrRubberBand\n self.__csrRubberBand = None\n \n if self.__RubberBand is not None:\n self.canvas.scene().removeItem(self.__RubberBand) # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__RubberBand\n self.__RubberBand = None\n \n del self.__QadSnapper\n self.__QadSnapper = None\n \n self.__QadSnapPointsDisplayManager.removeItems() # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__QadSnapPointsDisplayManager\n self.__QadSnapPointsDisplayManager = None\n \n \n def setDrawMode(self, drawMode):\n self.__drawMode = drawMode\n if self.__RubberBand is not None:\n self.__RubberBand.hide()\n self.canvas.scene().removeItem(self.__RubberBand) # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__RubberBand\n self.__RubberBand = None\n \n if self.__drawMode == QadGetPointDrawModeEnum.ELASTIC_LINE:\n self.refreshOrthoMode() # setto il default\n self.__RubberBand = createRubberBand(self.canvas, QGis.Line)\n self.__RubberBand.setLineStyle(Qt.DotLine)\n elif self.__drawMode == QadGetPointDrawModeEnum.ELASTIC_RECTANGLE:\n self.rectangleCrossingSelectionColor = getColorForCrossingSelectionArea()\n self.rectangleWindowSelectionColor = getColorForWindowSelectionArea()\n \n self.__RubberBand = createRubberBand(self.canvas, QGis.Polygon, False, None, self.rectangleCrossingSelectionColor)\n self.__RubberBand.setLineStyle(Qt.DotLine)\n \n\n def getDrawMode(self):\n return self.__drawMode\n\n\n def setSelectionMode(self, selectionMode):\n self.__selectionMode = selectionMode\n # setto il tipo di cursore\n if selectionMode == QadGetPointSelectionModeEnum.POINT_SELECTION:\n self.setCursorType(QadCursorTypeEnum.CROSS) # una croce usata per selezionare un punto\n elif selectionMode == QadGetPointSelectionModeEnum.ENTITY_SELECTION or \\\n selectionMode == QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC:\n self.entity.clear() # entità selezionata \n self.setCursorType(QadCursorTypeEnum.BOX) # un quadratino usato per selezionare entità\n elif selectionMode == QadGetPointSelectionModeEnum.ENTITYSET_SELECTION:\n self.setCursorType(QadCursorTypeEnum.CROSS) # una croce usata per selezionare un punto\n\n def getSelectionMode(self):\n return self.__selectionMode\n\n\n def hidePointMapToolMarkers(self):\n self.__QadSnapPointsDisplayManager.hide()\n if self.__RubberBand is not None:\n self.__RubberBand.hide()\n\n def showPointMapToolMarkers(self):\n if self.__RubberBand is not None:\n self.__RubberBand.show()\n\n def getPointMapToolMarkersCount(self):\n if self.__RubberBand is None:\n return 0\n else:\n return self.__RubberBand.numberOfVertices()\n \n def clear(self): \n self.hidePointMapToolMarkers()\n if self.__RubberBand is not None:\n self.canvas.scene().removeItem(self.__RubberBand) # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__RubberBand\n self.__RubberBand = None\n\n self.__QadSnapper.removeReferenceLines()\n self.__QadSnapper.setStartPoint(None)\n\n self.point = None # punto selezionato dal click\n self.tmpPoint = None # punto selezionato dal movimento del mouse\n \n self.entity.clear() # entità selezionata dal click\n self.tmpEntity.clear() # entità selezionata dal movimento del mouse\n \n self.snapTypeOnSelection = None # snap attivo al momento del click\n\n self.shiftKey = False\n self.tmpShiftKey = False # tasto shift premuto durante il movimento del mouse\n\n self.ctrlKey = False\n self.tmpCtrlKey = False # tasto ctrl premuto durante il movimento del mouse\n \n self.rightButton = False \n # opzioni per limitare l'oggetto da selezionare\n self.onlyEditableLayers = False\n self.checkPointLayer = True # usato solo per ENTITY_SELECTION\n self.checkLineLayer = True # usato solo per ENTITY_SELECTION\n self.checkPolygonLayer = True # usato solo per ENTITY_SELECTION\n self.layersToCheck = None\n \n self.__oldSnapType = None\n self.__oldSnapProgrDist = None\n self.__startPoint = None\n self.clearTmpGeometries()\n\n\n #============================================================================\n # tmpGeometries\n #============================================================================\n def clearTmpGeometries(self):\n del self.tmpGeometries[:] # svuoto la lista\n self.__QadSnapper.clearTmpGeometries()\n\n def setTmpGeometry(self, geom, CRS = None):\n self.clearTmpGeometries()\n self.appendTmpGeometry(geom, CRS)\n \n def appendTmpGeometry(self, geom, CRS = None):\n if geom is None:\n return\n if CRS is not None and CRS != self.canvas.mapRenderer().destinationCrs():\n g = QgsGeometry(geom)\n coordTransform = QgsCoordinateTransform(CRS, self.canvas.mapRenderer().destinationCrs()) # trasformo la geometria\n g.transform(coordTransform)\n self.tmpGeometries.append(g)\n else:\n self.tmpGeometries.append(geom)\n\n self.__QadSnapper.appendTmpGeometry(geom)\n \n\n def setTmpGeometries(self, geoms, CRS = None): \n self.clearTmpGeometries()\n for g in geoms:\n self.appendTmpGeometry(g, CRS)\n \n\n #============================================================================\n # SnapType\n #============================================================================\n def setSnapType(self, snapType = None):\n if snapType is None: \n self.__QadSnapper.setSnapType(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\")))\n else:\n self.__QadSnapper.setSnapType(snapType)\n \n self.__geometryTypesAccordingToSnapType = self.__QadSnapper.getGeometryTypesAccordingToSnapType()\n\n def getSnapType(self):\n return self.__QadSnapper.getSnapType()\n\n def forceSnapTypeOnce(self, snapType = None, snapParams = None):\n self.__oldSnapType = self.__QadSnapper.getSnapType()\n self.__oldSnapProgrDist = self.__QadSnapper.getProgressDistance()\n \n # se si vuole impostare lo snap perpendicolare e\n # non é stato impostato un punto di partenza\n if snapType == QadSnapTypeEnum.PER and self.__startPoint is None:\n # imposto lo snap perpendicolare differito\n self.setSnapType(QadSnapTypeEnum.PER_DEF)\n return\n # se si vuole impostare lo snap tangente e\n # non é stato impostato un punto di partenza\n if snapType == QadSnapTypeEnum.TAN and self.__startPoint is None:\n # imposto lo snap tangente differito\n self.setSnapType(QadSnapTypeEnum.TAN_DEF)\n return\n\n if snapParams is not None:\n for param in snapParams:\n if param[0] == QadSnapTypeEnum.PR:\n # se si vuole impostare una distanza lo snap progressivo\n self.__QadSnapper.setProgressDistance(param[1])\n \n self.setSnapType(snapType)\n\n def refreshSnapType(self):\n self.__oldSnapType = None\n self.__oldSnapProgrDist = None\n self.__QadSnapper.setProgressDistance(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSPROGRDISTANCE\")))\n self.setSnapType(QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\")))\n\n\n #============================================================================\n # OrthoMode\n #============================================================================\n def setOrthoMode(self, orthoMode = None):\n if orthoMode is None: \n self.__OrthoMode = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ORTHOMODE\"))\n else:\n self.__OrthoMode = orthoMode\n\n def getOrthoCoord(self, point):\n if math.fabs(point.x() - self.__startPoint.x()) < \\\n math.fabs(point.y() - self.__startPoint.y()):\n return QgsPoint(self.__startPoint.x(), point.y())\n else:\n return QgsPoint(point.x(), self.__startPoint.y())\n\n def refreshOrthoMode(self):\n self.setOrthoMode()\n\n\n #============================================================================\n # AutoSnap\n #============================================================================\n def setAutoSnap(self, autoSnap = None):\n if autoSnap is None: \n self.__AutoSnap = QadVariables.get(QadMsg.translate(\"Environment variables\", \"AUTOSNAP\"))\n self.__PolarAng = math.radians(QadVariables.get(QadMsg.translate(\"Environment variables\", \"POLARANG\")))\n else:\n self.__AutoSnap = autoSnap\n \n if (self.__AutoSnap & 8) == False: # puntamento polare non attivato\n self.__PolarAng = None\n\n def refreshAutoSnap(self):\n self.setAutoSnap()\n\n\n #============================================================================\n # CursorType\n #============================================================================\n def setCursorType(self, cursorType):\n if self.__csrRubberBand is not None:\n self.__csrRubberBand.removeItems() # prima lo stacco dal canvas altrimenti non si rimuove perchè usato da canvas\n del self.__csrRubberBand\n self.__csrRubberBand = QadCursorRubberBand(self.canvas, cursorType)\n self.__cursor = QCursor(Qt.BlankCursor) \n self.__cursorType = cursorType\n \n def getCursorType(self):\n return self.__cursorType\n\n \n #============================================================================\n # Elastic\n #============================================================================\n def moveElastic(self, point):\n numberOfVertices = self.__RubberBand.numberOfVertices()\n if numberOfVertices > 0: \n if numberOfVertices == 2:\n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n adjustedPoint = qad_utils.getAdjustedRubberBandVertex(self.__RubberBand.getPoint(0, 0), point) \n self.__RubberBand.movePoint(numberOfVertices - 1, adjustedPoint)\n else:\n p1 = self.__RubberBand.getPoint(0, 0)\n\n if point.x() > p1.x(): # se il punto è a destra di p1 (punto iniziale)\n self.__RubberBand.setFillColor(self.rectangleWindowSelectionColor)\n else:\n self.__RubberBand.setFillColor(self.rectangleCrossingSelectionColor)\n \n adjustedPoint = qad_utils.getAdjustedRubberBandVertex(p1, point) \n self.__RubberBand.movePoint(numberOfVertices - 3, QgsPoint(p1.x(), adjustedPoint.y()))\n self.__RubberBand.movePoint(numberOfVertices - 2, adjustedPoint)\n self.__RubberBand.movePoint(numberOfVertices - 1, QgsPoint(adjustedPoint.x(), p1.y())) \n\n \n #============================================================================\n # setStartPoint\n #============================================================================\n def setStartPoint(self, startPoint):\n self.__startPoint = startPoint\n self.__QadSnapper.setStartPoint(startPoint)\n \n if self.getDrawMode() == QadGetPointDrawModeEnum.ELASTIC_LINE:\n # previsto uso della linea elastica\n self.__RubberBand.reset(QGis.Line)\n #numberOfVertices = self.__RubberBand.numberOfVertices()\n #if numberOfVertices == 2:\n # self.__RubberBand.removeLastPoint()\n # self.__RubberBand.removeLastPoint()\n self.__RubberBand.addPoint(startPoint, False)\n \n point = self.toMapCoordinates(self.canvas.mouseLastXY()) # posizione\n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y\n point = qad_utils.getAdjustedRubberBandVertex(startPoint, point) \n \n self.__RubberBand.addPoint(point, True)\n elif self.getDrawMode() == QadGetPointDrawModeEnum.ELASTIC_RECTANGLE:\n # previsto uso del rettangolo elastico\n point = self.toMapCoordinates(self.canvas.mouseLastXY())\n\n self.__RubberBand.reset(QGis.Polygon)\n self.__RubberBand.addPoint(startPoint, False)\n \n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y\n point = qad_utils.getAdjustedRubberBandVertex(startPoint, point) \n \n self.__RubberBand.addPoint(QgsPoint(startPoint.x(), point.y()), False)\n self.__RubberBand.addPoint(point, False)\n self.__RubberBand.addPoint(QgsPoint(point.x(), startPoint.y()), True)\n \n self.__QadSnapPointsDisplayManager.setStartPoint(startPoint)\n\n\n def toggleReferenceLines(self, geom, point, crs):\n if self.__stopTimer == False and (geom is not None) and (point is not None):\n if self.__QadSnapper is not None:\n self.__QadSnapper.toggleReferenceLines(geom, point, crs)\n self.__QadSnapper.toggleIntExtLine(geom, point, crs)\n \n \n def canvasMoveEvent(self, event):\n self.tmpPoint = self.toMapCoordinates(event.pos())\n self.tmpEntity.clear()\n \n self.__csrRubberBand.moveEvent(self.tmpPoint)\n \n # se l'obiettivo é selezionare un'entità in modo dinamico\n if self.getSelectionMode() == QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC:\n result = qad_utils.getEntSel(event.pos(), self, \\\n self.layersToCheck, \\\n self.checkPointLayer, \\\n self.checkLineLayer, \\\n self.checkPolygonLayer, \\\n True, self.onlyEditableLayers)\n # se l'obiettivo é selezionare un punto\n elif self.getSelectionMode() == QadGetPointSelectionModeEnum.POINT_SELECTION:\n result = qad_utils.getEntSel(event.pos(), self, \\\n None, \\\n self.__geometryTypesAccordingToSnapType[0], \\\n self.__geometryTypesAccordingToSnapType[1], \\\n self.__geometryTypesAccordingToSnapType[2], \\\n True, \\\n self.onlyEditableLayers)\n else:\n result = None\n \n if result is not None:\n feature = result[0]\n layer = result[1]\n self.tmpEntity.set(layer, feature.id())\n geometry = feature.geometry()\n point = self.toLayerCoordinates(layer, event.pos())\n\n # se é stata selezionata una geometria diversa da quella selezionata precedentemente\n if (self.__prevGeom is None) or not self.__prevGeom.equals(geometry):\n self.__prevGeom = QgsGeometry(geometry)\n runToggleReferenceLines = lambda: self.toggleReferenceLines(self.__prevGeom, point, layer.crs())\n self.__stopTimer = False\n QTimer.singleShot(500, runToggleReferenceLines)\n \n oSnapPoints = self.__QadSnapper.getSnapPoint(geometry, point, \\\n layer.crs(), \\\n None, \\\n self.__PolarAng)\n\n # se l'obiettivo é selezionare un punto\n elif self.getSelectionMode() == QadGetPointSelectionModeEnum.POINT_SELECTION:\n # se non é stata trovato alcun oggetto allora verifico se una geometria di tmpGeometries rientra nel pickbox\n tmpGeometry = qad_utils.getGeomInPickBox(event.pos(),\n self, \\\n self.tmpGeometries, \\\n None, \\\n self.__geometryTypesAccordingToSnapType[0], \\\n self.__geometryTypesAccordingToSnapType[1], \\\n self.__geometryTypesAccordingToSnapType[2], \\\n True)\n if tmpGeometry is not None:\n # se é stata selezionata una geometria diversa da quella selezionata precedentemente\n if (self.__prevGeom is None) or not self.__prevGeom.equals(tmpGeometry):\n self.__prevGeom = QgsGeometry(tmpGeometry)\n runToggleReferenceLines = lambda: self.toggleReferenceLines(self.__prevGeom, self.tmpPoint, \\\n self.canvas.mapRenderer().destinationCrs())\n self.__stopTimer = False\n QTimer.singleShot(500, runToggleReferenceLines)\n\n self.__QadSnapper.clearCacheSnapPoints() # pulisco la cache perché tmpGeometry può essere variato\n oSnapPoints = self.__QadSnapper.getSnapPoint(tmpGeometry, self.tmpPoint, \\\n self.canvas.mapRenderer().destinationCrs(), \\\n None, \\\n self.__PolarAng,\n True) \n else: \n oSnapPoints = self.__QadSnapper.getSnapPoint(None, self.tmpPoint, \\\n self.canvas.mapRenderer().destinationCrs(), \\\n None, \\\n self.__PolarAng)\n \n self.__prevGeom = None\n self.__stopTimer = True\n\n oSnapPoint = None\n\n # se l'obiettivo é selezionare un punto\n if self.getSelectionMode() == QadGetPointSelectionModeEnum.POINT_SELECTION:\n # visualizzo il punto di snap\n self.__QadSnapPointsDisplayManager.show(oSnapPoints, \\\n self.__QadSnapper.getExtLines(), \\\n self.__QadSnapper.getExtArcs(), \\\n self.__QadSnapper.getParLines(), \\\n self.__QadSnapper.getIntExtLine(), \\\n self.__QadSnapper.getIntExtArc())\n \n self.point = None\n self.tmpPoint = None\n # memorizzo il punto di snap in point (prendo il primo valido)\n for item in oSnapPoints.items():\n points = item[1]\n if points is not None:\n self.tmpPoint = points[0]\n oSnapPoint = points[0]\n break\n \n if self.tmpPoint is None:\n self.tmpPoint = self.toMapCoordinates(event.pos())\n\n # tasto shift premuto durante il movimento del mouse\n self.tmpShiftKey = True if event.modifiers() & Qt.ShiftModifier else False\n\n # tasto ctrl premuto durante il movimento del mouse\n self.tmpCtrlKey = True if event.modifiers() & Qt.ControlModifier else False\n\n # se l'obiettivo é selezionare un punto\n if self.getSelectionMode() == QadGetPointSelectionModeEnum.POINT_SELECTION:\n if oSnapPoint is None:\n if self.__startPoint is not None: # c'é un punto di partenza\n if self.tmpShiftKey == False: # se non è premuto shift\n if self.__OrthoMode == 1: # orto attivato\n self.tmpPoint = self.getOrthoCoord(self.tmpPoint)\n else: # se non è premuto shift devo fare il toggle di ortho\n if self.__OrthoMode == 0: # se orto disattivato lo attivo temporaneamente\n self.tmpPoint = self.getOrthoCoord(self.tmpPoint)\n \n if self.getDrawMode() != QadGetPointDrawModeEnum.NONE:\n # previsto uso della linea elastica o rettangolo elastico\n self.moveElastic(self.tmpPoint)\n\n\n def canvasPressEvent(self, event):\n # volevo mettere questo evento nel canvasReleaseEvent\n # ma il tasto destro non genera quel tipo di evento\n if event.button() == Qt.RightButton:\n # Se é stato premuto il tasto CTRL (o META)\n if ((event.modifiers() & Qt.ControlModifier) or (event.modifiers() & Qt.MetaModifier)):\n self.displayPopupMenu(event.pos())\n else:\n # self.clear() da rivedere\n self.rightButton = True\n elif event.button() == Qt.LeftButton:\n if self.getSelectionMode() == QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC or \\\n self.getSelectionMode() == QadGetPointSelectionModeEnum.ENTITY_SELECTION:\n self.tmpPoint = self.toMapCoordinates(event.pos())\n result = qad_utils.getEntSel(event.pos(), self, \\\n self.layersToCheck, \\\n self.checkPointLayer, \\\n self.checkLineLayer, \\\n self.checkPolygonLayer, \\\n True, self.onlyEditableLayers)\n if result is not None:\n feature = result[0]\n layer = result[1]\n self.tmpEntity.set(layer, feature.id())\n \n self.__QadSnapper.removeReferenceLines()\n self.__QadSnapPointsDisplayManager.hide()\n \n self.__setPoint(event)\n \n self.rightButton = False\n \n if self.__oldSnapType is not None:\n self.setSnapType(self.__oldSnapType) # riporto il valore precedente\n self.__QadSnapper.setProgressDistance(self.__oldSnapProgrDist) \n \n # tasto shift premuto durante il click del mouse\n self.shiftKey = True if event.modifiers() & Qt.ShiftModifier else False\n\n # tasto ctrl premuto durante il click del mouse\n self.ctrlKey = True if event.modifiers() & Qt.ControlModifier else False\n\n self.plugIn.QadCommands.continueCommandFromMapTool()\n #self.plugIn.setStandardMapTool()\n\n def canvasReleaseEvent(self, event):\n # se l'obiettivo é selezionare un rettangolo\n if self.getDrawMode() == QadGetPointDrawModeEnum.ELASTIC_RECTANGLE: \n if event.button() == Qt.LeftButton:\n p1 = self.__RubberBand.getPoint(0, 0)\n # se il mouse é in una posizione diversa dal punto iniziale del rettangolo\n if p1 != self.toMapCoordinates(event.pos()):\n self.__QadSnapper.removeReferenceLines()\n self.__QadSnapPointsDisplayManager.hide()\n \n self.__setPoint(event)\n \n self.rightButton = False\n \n if self.__oldSnapType is not None:\n self.setSnapType(self.__oldSnapType) # riporto il valore precedente\n self.__QadSnapper.setProgressDistance(self.__oldSnapProgrDist)\n \n # tasto shift premuto durante il click del mouse\n self.shiftKey = True if event.modifiers() & Qt.ShiftModifier else False\n \n # tasto ctrl premuto durante il click del mouse\n self.ctrlKey = True if event.modifiers() & Qt.ControlModifier else False\n \n self.plugIn.QadCommands.continueCommandFromMapTool()\n #self.plugIn.setStandardMapTool()\n\n def __setPoint(self, event):\n # se non era mai stato mosso il mouse \n if self.tmpPoint is None: \n self.canvasMoveEvent(event)\n\n self.point = self.tmpPoint\n self.plugIn.setLastPoint(self.point)\n self.snapTypeOnSelection = self.getSnapType() # snap attivo al momento del click \n self.entity.set(self.tmpEntity.layer, self.tmpEntity.featureId)\n \n def keyPressEvent(self, event):\n self.plugIn.keyPressEvent(event) \n \n def activate(self):\n if self.__csrRubberBand is not None:\n # posizione corrente del mouse\n self.__csrRubberBand.moveEvent(self.toMapCoordinates(self.canvas.mouseLastXY()))\n self.__csrRubberBand.show()\n \n self.point = None\n self.tmpPoint = None\n\n self.entity = QadEntity() # entità selezionata dal click\n self.tmpEntity = QadEntity() # entità selezionata dal movimento del mouse\n \n self.snapTypeOnSelection = None # snap attivo al momento del click\n \n self.shiftKey = False\n self.tmpShiftKey = False # tasto shift premuto durante il movimento del mouse \n\n self.ctrlKey = False\n self.tmpCtrlKey = False # tasto ctrl premuto durante il movimento del mouse \n\n self.rightButton = False\n self.canvas.setCursor(self.__cursor)\n self.showPointMapToolMarkers()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n if self.__csrRubberBand is not None:\n self.__csrRubberBand.hide()\n self.hidePointMapToolMarkers()\n except:\n pass\n\n def isTransient(self):\n return False\n\n def isEditTool(self):\n return True\n \n\n #============================================================================\n # dispalyPopupMenu\n #============================================================================\n def displayPopupMenu(self, pos):\n popupMenu = QMenu(self.canvas)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Start / End\")\n icon = QIcon(\":/plugins/qad/icons/osnap_endLine.png\")\n if icon is None:\n addEndLineSnapTypeAction = QAction(msg, popupMenu)\n else:\n addEndLineSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addEndLineSnapTypeAction, SIGNAL(\"triggered()\"), self.addEndLineSnapTypeByPopupMenu) \n popupMenu.addAction(addEndLineSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Segment Start / End\")\n icon = QIcon(\":/plugins/qad/icons/osnap_end.png\")\n if icon is None:\n addEndSnapTypeAction = QAction(msg, popupMenu)\n else:\n addEndSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addEndSnapTypeAction, SIGNAL(\"triggered()\"), self.addEndSnapTypeByPopupMenu) \n popupMenu.addAction(addEndSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Middle point\")\n icon = QIcon(\":/plugins/qad/icons/osnap_mid.png\")\n if icon is None:\n addMidSnapTypeAction = QAction(msg, popupMenu)\n else:\n addMidSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addMidSnapTypeAction, SIGNAL(\"triggered()\"), self.addMidSnapTypeByPopupMenu) \n popupMenu.addAction(addMidSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Intersection\")\n icon = QIcon(\":/plugins/qad/icons/osnap_int.png\")\n if icon is None:\n addIntSnapTypeAction = QAction(msg, popupMenu)\n else:\n addIntSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addIntSnapTypeAction, SIGNAL(\"triggered()\"), self.addIntSnapTypeByPopupMenu) \n popupMenu.addAction(addIntSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Intersection on extension\")\n icon = QIcon(\":/plugins/qad/icons/osnap_extInt.png\")\n if icon is None:\n addExtIntSnapTypeAction = QAction(msg, popupMenu)\n else:\n addExtIntSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addExtIntSnapTypeAction, SIGNAL(\"triggered()\"), self.addExtIntSnapTypeByPopupMenu) \n popupMenu.addAction(addExtIntSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Extend\")\n icon = QIcon(\":/plugins/qad/icons/osnap_ext.png\")\n if icon is None:\n addExtSnapTypeAction = QAction(msg, popupMenu)\n else:\n addExtSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addExtSnapTypeAction, SIGNAL(\"triggered()\"), self.addExtSnapTypeByPopupMenu) \n popupMenu.addAction(addExtSnapTypeAction)\n\n popupMenu.addSeparator()\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Center\")\n icon = QIcon(\":/plugins/qad/icons/osnap_cen.png\")\n if icon is None:\n addCenSnapTypeAction = QAction(msg, popupMenu)\n else:\n addCenSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addCenSnapTypeAction, SIGNAL(\"triggered()\"), self.addCenSnapTypeByPopupMenu) \n popupMenu.addAction(addCenSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Quadrant\")\n icon = QIcon(\":/plugins/qad/icons/osnap_qua.png\")\n if icon is None:\n addQuaSnapTypeAction = QAction(msg, popupMenu)\n else:\n addQuaSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addQuaSnapTypeAction, SIGNAL(\"triggered()\"), self.addQuaSnapTypeByPopupMenu) \n popupMenu.addAction(addQuaSnapTypeAction)\n \n msg = QadMsg.translate(\"DSettings_Dialog\", \"Tangent\")\n icon = QIcon(\":/plugins/qad/icons/osnap_tan.png\")\n if icon is None:\n addTanSnapTypeAction = QAction(msg, popupMenu)\n else:\n addTanSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addTanSnapTypeAction, SIGNAL(\"triggered()\"), self.addTanSnapTypeByPopupMenu) \n popupMenu.addAction(addTanSnapTypeAction)\n\n popupMenu.addSeparator()\n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Perpendicular\")\n icon = QIcon(\":/plugins/qad/icons/osnap_per.png\")\n if icon is None:\n addPerSnapTypeAction = QAction(msg, popupMenu)\n else:\n addPerSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addPerSnapTypeAction, SIGNAL(\"triggered()\"), self.addPerSnapTypeByPopupMenu) \n popupMenu.addAction(addPerSnapTypeAction) \n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Parallel\")\n icon = QIcon(\":/plugins/qad/icons/osnap_par.png\")\n if icon is None:\n addParSnapTypeAction = QAction(msg, popupMenu)\n else:\n addParSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addParSnapTypeAction, SIGNAL(\"triggered()\"), self.addParSnapTypeByPopupMenu) \n popupMenu.addAction(addParSnapTypeAction) \n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Node\")\n icon = QIcon(\":/plugins/qad/icons/osnap_nod.png\")\n if icon is None:\n addNodSnapTypeAction = QAction(msg, popupMenu)\n else:\n addNodSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addNodSnapTypeAction, SIGNAL(\"triggered()\"), self.addNodSnapTypeByPopupMenu) \n popupMenu.addAction(addNodSnapTypeAction) \n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Near\")\n icon = QIcon(\":/plugins/qad/icons/osnap_nea.png\")\n if icon is None:\n addNeaSnapTypeAction = QAction(msg, popupMenu)\n else:\n addNeaSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addNeaSnapTypeAction, SIGNAL(\"triggered()\"), self.addNeaSnapTypeByPopupMenu) \n popupMenu.addAction(addNeaSnapTypeAction) \n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Progressive\")\n icon = QIcon(\":/plugins/qad/icons/osnap_pr.png\")\n if icon is None:\n addPrSnapTypeAction = QAction(msg, popupMenu)\n else:\n addPrSnapTypeAction = QAction(icon, msg, popupMenu) \n QObject.connect(addPrSnapTypeAction, SIGNAL(\"triggered()\"), self.addPrSnapTypeByPopupMenu) \n popupMenu.addAction(addPrSnapTypeAction) \n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"None\")\n icon = QIcon(\":/plugins/qad/icons/osnap_disable.png\")\n if icon is None:\n setSnapTypeToDisableAction = QAction(msg, popupMenu)\n else:\n setSnapTypeToDisableAction = QAction(icon, msg, popupMenu) \n QObject.connect(setSnapTypeToDisableAction, SIGNAL(\"triggered()\"), self.setSnapTypeToDisableByPopupMenu) \n popupMenu.addAction(setSnapTypeToDisableAction) \n\n popupMenu.addSeparator()\n\n msg = QadMsg.translate(\"DSettings_Dialog\", \"Object snap settings...\")\n icon = QIcon(\":/plugins/qad/icons/dsettings.png\")\n if icon is None:\n DSettingsAction = QAction(msg, popupMenu)\n else:\n DSettingsAction = QAction(icon, msg, popupMenu) \n QObject.connect(DSettingsAction, SIGNAL(\"triggered()\"), self.showDSettingsByPopUpMenu) \n popupMenu.addAction(DSettingsAction) \n \n popupMenu.popup(self.canvas.mapToGlobal(pos))\n \n\n #============================================================================\n # addSnapTypeByPopupMenu\n #============================================================================\n def addSnapTypeByPopupMenu(self, _snapType):\n value = QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\"))\n if value & QadSnapTypeEnum.DISABLE:\n value = value - QadSnapTypeEnum.DISABLE \n QadVariables.set(QadMsg.translate(\"Environment variables\", \"OSMODE\"), value | _snapType)\n QadVariables.save() \n self.refreshSnapType()\n \n def addEndLineSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.END_PLINE)\n def addEndSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.END)\n def addMidSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.MID)\n def addIntSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.INT) \n def addExtIntSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.EXT_INT)\n def addExtSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.EXT) \n def addCenSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.CEN) \n def addQuaSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.QUA)\n def addTanSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.TAN)\n def addPerSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.PER)\n def addParSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.PAR)\n def addNodSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.NOD)\n def addNeaSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.NEA)\n def addPrSnapTypeByPopupMenu(self):\n self.addSnapTypeByPopupMenu(QadSnapTypeEnum.PR)\n\n def setSnapTypeToDisableByPopupMenu(self):\n value = QadVariables.get(QadMsg.translate(\"Environment variables\", \"OSMODE\"))\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"OSMODE\"), value | QadSnapTypeEnum.DISABLE)\n QadVariables.save() \n self.refreshSnapType()\n\n def showDSettingsByPopUpMenu(self):\n d = QadDSETTINGSDialog(self.plugIn)\n d.exec_()\n self.refreshSnapType()\n\n\n def mapToLayerCoordinates(self, layer, point_geom):\n # transform point o geometry coordinates from output CRS to layer's CRS \n if self.canvas is None:\n return None\n if type(point_geom) == QgsPoint:\n return self.canvas.mapRenderer().mapToLayerCoordinates(layer, point_geom)\n elif type(point_geom) == QgsGeometry:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.canvas.mapRenderer().destinationCrs(), layer.crs())\n g = QgsGeometry(point_geom)\n g.transform(coordTransform)\n return g\n else:\n return None\n\n def layerToMapCoordinates(self, layer, point_geom):\n # transform point o geometry coordinates from layer's CRS to output CRS \n if self.canvas is None:\n return None\n if type(point_geom) == QgsPoint:\n return self.canvas.mapRenderer().layerToMapCoordinates(layer, point_geom)\n elif type(point_geom) == QgsGeometry:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(layer.crs(), self.canvas.mapRenderer().destinationCrs())\n g = QgsGeometry(point_geom)\n g.transform(coordTransform)\n return g\n else:\n return None\n"
},
{
"alpha_fraction": 0.5106163024902344,
"alphanum_fraction": 0.5127969980239868,
"avg_line_length": 44.56544494628906,
"blob_id": "19d2ce20d5ab5c763ffbd1decba44af51e943a7e",
"content_id": "507586a0d1f062e37acc6aa3db9348bfb4032522",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8722,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 191,
"path": "/qad_entsel_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando da inserire in altri comandi per la selezione di una feature\n \n -------------------\n begin : 2013-09-18\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nfrom qad_entity import *\nfrom qad_getpoint import *\nimport qad_utils\nfrom qad_dim import QadDimStyles\n\n\n#===============================================================================\n# QadEntSelClass\n#===============================================================================\nclass QadEntSelClass(QadCommandClass):\n \"\"\"\n Questa classe seleziona un'entità. Non è in grado di selezionare una quotatura ma solo un componente di una quotatura.\n \"\"\"\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadEntSelClass(self.plugIn)\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.entity = QadEntity()\n self.point = None\n # opzioni per limitare gli oggetti da selezionare\n self.onlyEditableLayers = False \n self.checkPointLayer = True\n self.checkLineLayer = True\n self.checkPolygonLayer = True\n self.checkDimLayers = True\n self.selDimEntity = False # per restituire o meno un oggetto QadDimEntity\n self.msg = QadMsg.translate(\"QAD\", \"Select object: \")\n \n def __del__(self):\n QadCommandClass.__del__(self)\n if self.entity.isInitialized():\n self.entity.deselectOnLayer()\n\n\n #============================================================================\n # setEntity\n #============================================================================\n def setEntity(self, layer, fid):\n del self.entity\n if self.selDimEntity: # se è possibile restituire un oggetto QadDimEntity\n # verifico se l'entità appartiene ad uno stile di quotatura\n self.entity = QadDimStyles.getDimEntity(layer, fid)\n if self.entity is None: # se non è una quota\n self.entity = QadEntity()\n self.entity.set(layer, fid)\n else:\n self.entity = QadEntity()\n self.entity.set(layer, fid)\n \n self.entity.selectOnLayer()\n\n\n #============================================================================\n # getLayersToCheck\n #============================================================================\n def getLayersToCheck(self): \n layerList = []\n for layer in self.plugIn.canvas.layers(): # Tutti i layer visibili visibili\n # considero solo i layer vettoriali che sono filtrati per tipo\n if (layer.type() == QgsMapLayer.VectorLayer) and \\\n ((layer.geometryType() == QGis.Point and self.checkPointLayer == True) or \\\n (layer.geometryType() == QGis.Line and self.checkLineLayer == True) or \\\n (layer.geometryType() == QGis.Polygon and self.checkPolygonLayer == True)) and \\\n (self.onlyEditableLayers == False or layer.isEditable()):\n # se devo includere i layers delle quotature\n if self.checkDimLayers == True or \\\n len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n return layerList\n\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA PUNTO o ENTITA'\n if self.step == 0: # inizio del comando\n # imposto il map tool\n self.getPointMapTool().setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n # imposto i layer da controllare sul maptool\n self.getPointMapTool().layersToCheck = self.getLayersToCheck()\n \n keyWords = QadMsg.translate(\"Command_ENTSEL\", \"Last\")\n \n englishKeyWords = \"Last\"\n keyWords += \"_\" + englishKeyWords\n # si appresta ad attendere un punto o enter o una parola chiave \n # msg, inputType, default, keyWords, nessun controllo\n self.waitFor(self.msg, \\\n QadInputTypeEnum.POINT2D | QadInputTypeEnum.KEYWORDS, \\\n None, \\\n keyWords, QadInputModeEnum.NONE)\n \n self.step = 1\n return False\n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO o ENTITA'\n elif self.step == 1: # dopo aver atteso un punto si riavvia il comando\n entity = None\n if msgMapTool == True: # il punto arriva da una selezione grafica\n # la condizione seguente si verifica se durante la selezione di un punto\n # é stato attivato un altro plugin che ha disattivato Qad\n # quindi stato riattivato il comando che torna qui senza che il maptool\n # abbia selezionato un punto \n if self.getPointMapTool().point is None: # il maptool é stato attivato senza un punto\n if self.getPointMapTool().rightButton == True: # se usato il tasto destro del mouse\n return True # fine comando\n else:\n self.setMapTool(self.getPointMapTool()) # riattivo il maptool\n return False\n \n value = self.getPointMapTool().point\n if self.getPointMapTool().entity.isInitialized():\n entity = self.getPointMapTool().entity \n else: # il punto arriva come parametro della funzione\n value = msg\n\n if value is None:\n return True # fine comando\n \n if type(value) == unicode:\n if value == QadMsg.translate(\"Command_ENTSEL\", \"Last\") or value == \"Last\":\n # Seleziona l'ultima entità inserita\n lastEnt = self.plugIn.getLastEntity()\n if lastEnt is not None:\n # controllo sul layer\n if self.onlyEditableLayers == False or lastEnt.layer.isEditable() == True:\n # controllo sul tipo\n if (self.checkPointLayer == True and lastEnt.layer.geometryType() == QGis.Point) or \\\n (self.checkLineLayer == True and lastEnt.layer.geometryType() == QGis.Line) or \\\n (self.checkPolygonLayer == True and lastEnt.layer.geometryType() == QGis.Polygon):\n # controllo su layer delle quotature\n if self.checkDimLayers == True or lastEnt.isDimensionComponent() == False:\n self.setEntity(lastEnt.layer, lastEnt.featureId)\n elif type(value) == QgsPoint:\n if entity is None:\n # cerco se ci sono entità nel punto indicato\n result = qad_utils.getEntSel(self.getPointMapTool().toCanvasCoordinates(value),\n self.getPointMapTool(), \\\n self.getLayersToCheck())\n if result is not None:\n feature = result[0]\n layer = result[1]\n self.setEntity(layer, feature.id()) \n else:\n self.setEntity(entity.layer, entity.featureId)\n\n self.point = value\n \n return True # fine comando\n \n"
},
{
"alpha_fraction": 0.5861193537712097,
"alphanum_fraction": 0.5889719724655151,
"avg_line_length": 31.606128692626953,
"blob_id": "9d906d68a2aac31998c5bf27ff1c3169d4ac77ff",
"content_id": "077af9b26325dbb8856a27331818cc0509f18ddc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 28771,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 881,
"path": "/qad_entity.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per la gestione delle entità\n \n -------------------\n begin : 2013-08-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nfrom qgis.utils import iface\nimport sys\n\n\nimport qad_utils\nfrom qad_arc import *\nfrom qad_circle import *\nimport qad_layer\nimport qad_stretch_fun\n\n\n#===============================================================================\n# QadEntityGeomTypeEnum class.\n#===============================================================================\nclass QadEntityGeomTypeEnum():\n NONE = 0\n SYMBOL = 1\n TEXT = 2\n ARC = 3\n CIRCLE = 4\n LINESTRING = 5\n\n\n#===============================================================================\n# QadEntity entity class\n#===============================================================================\nclass QadEntity():\n \n def __init__(self, entity = None):\n self.entityType = QadEntityGeomTypeEnum.NONE\n self.qadGeom = None # in crs del canvas per lavorare con coordinate piane xy\n self.dimStyle = None\n self.dimId = None\n \n if entity is not None:\n self.set(entity.layer, entity.featureId)\n else: \n self.layer = None\n self.featureId = None\n\n\n def whatIs(self):\n return \"ENTITY\"\n\n \n def isDimensionComponent(self):\n # se entityType non è già stato inizializzato\n if self.entityType == QadEntityGeomTypeEnum.NONE:\n self.__initQadInfo()\n\n return (self.dimStyle is not None) and (self.dimId is not None)\n\n\n def __fromPoyline(self, pointList): # funzione privata\n # restituisce entityType, qadGeom\n arc = QadArc()\n startEndVertices = arc.fromPolyline(pointList, 0)\n # se la polilinea è composta solo da un arco\n if startEndVertices and startEndVertices[0] == 0 and startEndVertices[1] == len(pointList)-1:\n return QadEntityGeomTypeEnum.ARC, arc # oggetto arco\n else:\n circle = QadCircle()\n startEndVertices = circle.fromPolyline(pointList, 0)\n # se la polilinea è composta solo da un cerchio\n if startEndVertices and startEndVertices[0] == 0 and startEndVertices[1] == len(pointList)-1:\n return QadEntityGeomTypeEnum.CIRCLE, circle # oggetto cerchio\n else:\n linearObjectList = qad_utils.QadLinearObjectList() # oggetto QadLinearObjectList\n linearObjectList.fromPolyline(pointList)\n return QadEntityGeomTypeEnum.LINESTRING, linearObjectList\n \n return QadEntityGeomTypeEnum.NONE, None\n\n\n def __initQadInfo(self):\n # inizializza entityType, qadGeom, dimStyle, dimId\n if self.isInitialized() == False:\n return QadEntityGeomTypeEnum.NONE\n\n self.dimStyle = None\n self.dimId = None\n\n g = self.getGeometry()\n if g is None:\n return QadEntityGeomTypeEnum.NONE\n\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.layer.crs(), iface.mapCanvas().mapRenderer().destinationCrs())\n g.transform(coordTransform)\n\n wkbType = g.wkbType()\n if wkbType == QGis.WKBPoint:\n from qad_dim import QadDimStyles # to avoid cyclic import\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimStyle, dimId = QadDimStyles.getDimIdByEntity(self)\n if (dimStyle is not None) and (dimId is not None):\n self.dimStyle = dimStyle # stile di quotatura di appartenenza\n self.dimId = dimId # codice quotatura di appartenenza\n \n if qad_layer.isTextLayer(self.layer):\n self.entityType = QadEntityGeomTypeEnum.TEXT\n elif qad_layer.isSymbolLayer(self.layer):\n self.entityType = QadEntityGeomTypeEnum.SYMBOL\n self.qadGeom = g.asPoint() # un punto\n\n if wkbType == QGis.WKBMultiPoint:\n if qad_layer.isTextLayer(self.layer):\n self.entityType = QadEntityGeomTypeEnum.TEXT\n elif qad_layer.isSymbolLayer(self.layer):\n self.entityType = QadEntityGeomTypeEnum.SYMBOL\n self.qadGeom = g.asMultiPoint() # lista di punti\n\n elif wkbType == QGis.WKBLineString:\n from qad_dim import QadDimStyles # to avoid cyclic import\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimStyle, dimId = QadDimStyles.getDimIdByEntity(self)\n if (dimStyle is not None) and (dimId is not None):\n self.entityType = QadEntityGeomTypeEnum.DIMENSION_COMPONENT\n self.dimStyle = dimStyle # stile di quotatura di appartenenza\n self.dimId = dimId # codice quotatura di appartenenza\n\n self.entityType, self.qadGeom = self.__fromPoyline(g.asPolyline())\n\n elif wkbType == QGis.WKBMultiLineString: \n self.entityType = []\n self.qadGeom = []\n lineList = g.asMultiPolyline() # vettore di linee\n for line in lineList:\n entityType, qadGeom = self.__fromPoyline(g.asPolyline())\n self.entityType.append(entityType)\n self.qadGeom.append(qadGeom)\n\n elif wkbType == QGis.WKBPolygon:\n self.entityType = []\n self.qadGeom = []\n polygon = g.asPolygon() # vettore di linee\n for line in polygon:\n entityType, qadGeom = self.__fromPoyline(line)\n self.entityType.append(entityType)\n self.qadGeom.append(qadGeom)\n\n elif wkbType == QGis.WKBMultiPolygon:\n self.entityType = []\n self.qadGeom = []\n polygonList = g.asMultiPolygon() # vettore di poligoni\n for polygon in polygonList:\n partialEntityType = []\n partialQadGeom = []\n for line in polygon:\n entityType, qadGeom = self.__fromPoyline(line)\n partialEntityType.append(entityType)\n partialQadGeom.append(qadGeom)\n self.entityType.append(partialEntityType)\n self.qadGeom.append(partialQadGeom)\n\n\n def getEntityType(self, atGeom = 0, atSubGeom = 0):\n # se entityType non è già stato inizializzato\n if self.entityType == QadEntityGeomTypeEnum.NONE:\n self.__initQadInfo()\n \n # se entityType è stato inizializzato\n if self.entityType != QadEntityGeomTypeEnum.NONE:\n if type(self.entityType) == list:\n if atGeom < len(self.entityType):\n if type(self.entityType[atGeom]) == list:\n if atSubGeom < len(self.entityType[atGeom]):\n return self.entityType[atGeom][atSubGeom]\n else:\n return QadEntityGeomTypeEnum.NONE\n else:\n return QadEntityGeomTypeEnum.NONE if atSubGeom != 0 else self.entityType[atGeom]\n else:\n return QadEntityGeomTypeEnum.NONE\n else:\n return QadEntityGeomTypeEnum.NONE if atGeom != 0 else self.entityType\n else:\n return QadEntityGeomTypeEnum.NONE\n\n\n def getQadGeom(self, atGeom = 0, atSubGeom = 0):\n # se entityType non è già stato inizializzato\n if self.qadGeom is None:\n self.__initQadInfo()\n \n # se qadGeom è stato inizializzato\n if self.qadGeom is not None:\n if type(self.qadGeom) == list:\n if atGeom < len(self.qadGeom):\n if type(self.qadGeom[atGeom]) == list:\n if atSubGeom < len(self.qadGeom[atGeom]):\n return self.qadGeom[atGeom][atSubGeom]\n else:\n return None\n else:\n return None if atSubGeom != 0 else self.qadGeom[atGeom]\n else:\n return None\n else:\n return None if atGeom != 0 else self.qadGeom\n else:\n return None\n\n\n def isInitialized(self):\n if (self.layer is None) or (self.featureId is None):\n return False\n else:\n return True\n\n\n def clear(self):\n self.layer = None\n self.featureId = None\n self.entityType = QadEntityGeomTypeEnum.NONE\n self.qadGeom = None\n self.dimStyle = None\n self.dimId = None\n \n \n def __eq__(self, entity):\n \"\"\"self == other\"\"\"\n if self.isInitialized() == False or entity.isInitialized() == False :\n return False\n\n if self.layerId() == entity.layerId() and self.featureId == entity.featureId: \n return True\n else:\n return False \n \n \n def __ne__(self, entity):\n \"\"\"self != other\"\"\"\n if self.isInitialized() == False or entity.isInitialized() == False:\n return True\n\n if self.layerId() != entity.layerId() or self.featureId != entity.featureId: \n return True\n else:\n return False\n\n\n def layerId(self):\n if self.isInitialized() == False:\n return None\n return self.layer.id()\n\n\n def set(self, layer, featureId):\n self.clear()\n self.layer = layer # il layer non si può copiare\n self.featureId = featureId # copio l'identificativo di feature\n return self\n\n\n def getFeature(self):\n if self.isInitialized() == False:\n return None\n \n return qad_utils.getFeatureById(self.layer, self.featureId)\n \n\n def exists(self):\n if self.getFeature() is None:\n return False\n else:\n return True\n\n\n def getGeometry(self):\n feature = self.getFeature()\n if feature is None:\n return None \n return QgsGeometry(feature.geometry()) # fa una copia\n\n\n def __getPtsFromQadGeom(self, qadGeom, tolerance2ApproxCurve):\n if type(qadGeom) == list: # entità composta da più geometrie\n res = []\n for subGeom in qadGeom:\n res.append(self.__getPtsFromQadGeom(subGeom, tolerance2ApproxCurve))\n return res\n else:\n if type(qadGeom) == QgsPoint:\n return qadGeom\n else:\n return qadGeom.asPolyline(tolerance2ApproxCurve)\n\n\n def __getGeomFromQadGeom(self, qadGeom, tolerance2ApproxCurve):\n Pts = self.__getPtsFromQadGeom(qadGeom, tolerance2ApproxCurve)\n if Pts is None:\n return None\n if self.layer.geometryType() == QGis.Point:\n if type(Pts) == list:\n g = QgsGeometry.fromMultiPoint(Pts)\n else:\n g = QgsGeometry.fromPoint(Pts)\n if self.layer.geometryType() == QGis.Line:\n if type(Pts[0]) == list:\n g = QgsGeometry.fromMultiPolyline(Pts)\n else:\n g = QgsGeometry.fromPolyline(Pts)\n if self.layer.geometryType() == QGis.Polygon:\n if type(Pts[0][0]) == list:\n g = QgsGeometry.fromMultiPolygon(Pts)\n else:\n g = QgsGeometry.fromPolygon(Pts)\n\n # trasformo la geometria nel crs del layer\n coordTransform = QgsCoordinateTransform(iface.mapCanvas().mapRenderer().destinationCrs(), self.layer.crs())\n g.transform(coordTransform)\n return g\n \n\n# questa funzione non ha senso perchè feature è una variabile locale temporanea a cui viene settata la geometria\n# ma poi, a fine funzione, viene distrutta.\n# def setGeometry(self, geom):\n# feature = self.getFeature()\n# if feature is None:\n# return None \n# return feature.setGeometry(geom)\n\n\n def getAttribute(self, attribName):\n feature = self.getFeature()\n if feature is None:\n return None\n try:\n return feature.attribute(attribName)\n except:\n return None\n\n \n def getAttributes(self):\n feature = self.getFeature()\n if feature is None:\n return None\n\n return feature.attributes()[:] # fa una copia\n\n\n def selectOnLayer(self, incremental = True):\n if self.isInitialized() == True:\n if incremental == False:\n self.layer.removeSelection()\n\n self.layer.select(self.featureId)\n\n\n def deselectOnLayer(self):\n if self.isInitialized() == False:\n return False\n\n self.layer.deselect(self.featureId)\n\n\n #===============================================================================\n # operazioni geometriche - inizio\n \n def gripStretch(self, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n # se entityType è già stato inizializzato\n if self.entityType == QadEntityGeomTypeEnum.NONE:\n self.__initQadInfo()\n \n return qad_stretch_fun.gripStretchQadGeometry(self.qadGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n\n def gripGeomStretch(self, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n newQadGeom = self.gripStretch(basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n if newQadGeom is None:\n return None\n return self.__getGeomFromQadGeom(newQadGeom, tolerance2ApproxCurve)\n\n\n# operazioni geometriche - fine\n#===============================================================================\n\n\n#===============================================================================\n# QadLayerEntitySet entities of a layer class\n#===============================================================================\nclass QadLayerEntitySet():\n \n def __init__(self, layerEntitySet = None):\n if layerEntitySet is not None:\n self.set(layerEntitySet.layer, layerEntitySet.featureIds)\n else: \n self.layer = None\n self.featureIds = []\n\n\n def whatIs(self):\n return \"LAYERENTITYSET\"\n\n\n def isInitialized(self):\n if self.layer is None:\n return False\n else:\n return True\n\n\n def isEmpty(self):\n if self.isInitialized() == False:\n return True\n return not self.featureIds\n\n\n def count(self):\n if self.isInitialized() == False:\n return 0\n return len(self.featureIds)\n\n\n def clear(self):\n if self.isInitialized() == False:\n return 0\n self.layer = None\n del self.featureIds[:] \n\n\n def layerId(self):\n if self.isInitialized() == False:\n return None\n return self.layer.id()\n\n\n def set(self, layer, features = None):\n if type(layer) == QgsVectorLayer:\n self.layer = layer # il layer non si può copiare\n self.featureIds = [] \n if features is not None:\n self.addFeatures(features)\n else: # layer è una entità\n return self.set(layer.layer, layer.featureIds)\n\n\n def initByCurrentQgsSelectedFeatures(self, layer):\n self.clear()\n self.layer = layer\n self.featureIds = self.layer.selectedFeaturesIds()\n\n\n def getFeature(self, featureId):\n if self.isInitialized() == False:\n return None\n return qad_utils.getFeatureById(self.layer, featureId)\n \n\n def getGeometry(self, featureId):\n feature = self.getFeature(featureId)\n if feature is None:\n return None \n return QgsGeometry(feature.geometry()) # fa una copia\n\n def setGeometry(self, featureId, geom):\n feature = self.getFeature(featureId)\n if feature is None:\n return None\n return feature.setGeometry(geom)\n\n\n def getGeometryCollection(self, destCRS = None):\n result = []\n if destCRS is not None:\n coordTransform = QgsCoordinateTransform(self.layer.crs(), destCRS) # trasformo la geometria\n for featureId in self.featureIds:\n g = self.getGeometry(featureId)\n if g is not None:\n if destCRS is not None:\n g.transform(coordTransform)\n\n # Per un baco sconosciuto quando trasformo la geometria se poi ne faccio un buffer\n # il calcolo dà un risultato sbagliato quando la geometria é nuova o modificata\n # (in cache del layer) e il sistema di coordinate é diverso de quello della mappa corrente \n wkbType = g.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D: \n g = QgsGeometry().fromPoint(g.asPoint())\n elif wkbType == QGis.WKBMultiPoint or wkbType == QGis.WKBMultiPoint25D:\n g = QgsGeometry().fromMultiPoint(g.asMultiPoint())\n elif wkbType == QGis.WKBLineString or wkbType == QGis.WKBLineString25D:\n g = QgsGeometry().fromPolyline(g.asPolyline())\n elif wkbType == QGis.WKBMultiLineString or wkbType == QGis.WKBMultiLineString25D:\n g = QgsGeometry().fromMultiPolyline(g.asMultiPolyline())\n elif wkbType == QGis.WKBPolygon or wkbType == QGis.WKBPolygon25D:\n g = QgsGeometry().fromPolygon(g.asPolygon())\n elif wkbType == QGis.WKBMultiPolygon or wkbType == QGis.WKBMultiPolygon25D:\n g = QgsGeometry().fromMultiPolygon(g.asMultiPolygon())\n \n result.append(g)\n return result\n\n\n def getFeatureCollection(self):\n result = []\n for featureId in self.featureIds:\n f = self.getFeature(featureId)\n if f is not None: \n result.append(f)\n return result\n\n \n def selectOnLayer(self, incremental = True):\n if self.isInitialized() == True: \n if len(self.featureIds) > 0:\n if incremental == False:\n self.layer.removeSelection()\n \n self.layer.select(self.featureIds)\n else:\n if incremental == False:\n self.layer.removeSelection()\n \n\n def deselectOnLayer(self):\n if self.isInitialized() == True:\n if len(self.featureIds) > 0:\n self.layer.deselect(self.featureIds)\n\n \n def containsFeature(self, feature):\n if self.isInitialized() == False:\n return False\n\n if type(feature) == QgsFeature: \n return feature.id() in self.featureIds\n else:\n return feature in self.featureIds\n \n\n def containsEntity(self, entity):\n if self.isInitialized() == False:\n return False\n \n if self.layerId() != entity.layerId(): \n return False\n return containsFeature(entity.featureId)\n \n \n def addFeature(self, feature):\n if self.isInitialized() == False:\n return False\n \n if type(feature) == QgsFeature:\n if self.containsFeature(feature.id()) == False: \n self.featureIds.append(feature.id())\n return True\n else:\n return False\n else:\n if self.containsFeature(feature) == False: \n self.featureIds.append(feature)\n return True\n else:\n return False\n\n\n def removeFeature(self, feature):\n if self.isInitialized() == False:\n return False\n \n try:\n if type(feature) == QgsFeature: \n return self.featureIds.remove(feature.id())\n else:\n return self.featureIds.remove(feature)\n except:\n return None\n\n\n def addEntity(self, entity):\n if self.isInitialized() == False:\n self.set(entity.layer)\n else:\n if self.layerId() != entity.layerId(): \n return\n \n self.addFeature(entity.featureId)\n\n\n def removeEntity(self, entity):\n if self.isInitialized() == False:\n return False\n\n if self.layerId() != entity.layerId(): \n return False\n \n return self.removeFeature(entity.featureId)\n\n\n def addFeatures(self, features):\n if self.isInitialized() == False:\n return None\n for feature in features:\n if type(feature) == QgsFeature:\n self.addFeature(feature.id())\n else:\n self.addFeature(feature) # featureId\n\n\n def addLayerEntitySet(self, layerEntitySet):\n if self.isInitialized() == False:\n self.set(layerEntitySet.layer)\n else:\n if self.layerId() != layerEntitySet.layerId():\n return\n self.addFeatures(layerEntitySet.featureIds)\n \n \n def unite(self, layerEntitySet):\n if self.isInitialized() == False:\n return\n \n if self.layerId() == layerEntitySet.layerId():\n self.featureIds = list(set.union(set(self.featureIds), set(layerEntitySet.featureIds)))\n\n\n def intersect(self, layerEntitySet):\n if self.isInitialized() == False:\n return\n \n if self.layerId() == layerEntitySet.layerId():\n self.featureIds = list(set(self.featureIds) & set(layerEntitySet.featureIds)) \n\n\n def subtract(self, layerEntitySet):\n if self.isInitialized() == False:\n return\n \n if self.layerId() == layerEntitySet.layerId(): \n self.featureIds = list(set(self.featureIds) - set(layerEntitySet.featureIds)) \n\n\n def getNotExistingFeaturedIds(self):\n featureIds = []\n if self.isInitialized() == True:\n feature = QadEntity()\n for featureId in self.featureIds:\n feature.set(self.layer, featureId)\n if not feature.exists():\n featureIds.append(featureId)\n return featureIds\n \n\n def removeNotExisting(self):\n featureIds = self.getNotExistingFeaturedIds()\n self.featureIds = list(set(self.featureIds) - set(featureIds)) \n \n\n#===============================================================================\n# QadEntitySet entities of a layers class\n#===============================================================================\nclass QadEntitySet():\n \n def __init__(self, entitySet = None):\n self.layerEntitySetList = []\n if entitySet is not None:\n self.set(entitySet)\n\n\n def whatIs(self):\n return \"ENTITYSET\"\n\n\n def isEmpty(self):\n for layerEntitySet in self.layerEntitySetList:\n if layerEntitySet.isEmpty() == False:\n return False\n return True\n\n\n def count(self):\n tot = 0\n for layerEntitySet in self.layerEntitySetList:\n tot = tot + layerEntitySet.count()\n return tot\n\n\n def clear(self):\n del self.layerEntitySetList[:] \n\n\n def set(self, entitySet): \n self.clear()\n for layerEntitySet in entitySet.layerEntitySetList:\n self.addLayerEntitySet(layerEntitySet)\n\n\n def initByCurrentQgsSelectedFeatures(self, layers):\n self.clear()\n\n for layer in layers:\n if layer.selectedFeatureCount() > 0:\n layerEntitySet = QadLayerEntitySet()\n layerEntitySet.initByCurrentQgsSelectedFeatures(layer)\n self.layerEntitySetList.append(layerEntitySet)\n\n\n def findLayerEntitySet(self, layer):\n if layer is None:\n return None\n if type(layer) == QgsVectorLayer: # layer\n return self.findLayerEntitySet(layer.id()) \n elif type(layer) == unicode: # id del layer\n for layerEntitySet in self.layerEntitySetList:\n if layerEntitySet.layerId() == layer:\n return layerEntitySet\n return None\n else: # QadLayerEntitySet\n return self.findLayerEntitySet(layer.layer) \n\n\n def getLayerList(self):\n layerList = []\n for layerEntitySet in self.layerEntitySetList:\n layerList.append(layerEntitySet.layer)\n return layerList\n \n\n def getGeometryCollection(self, destCRS = None):\n result = []\n for layerEntitySet in self.layerEntitySetList:\n partial = layerEntitySet.getGeometryCollection(destCRS)\n if partial is not None:\n result.extend(partial)\n return result\n \n\n def getFeatureCollection(self):\n result = []\n for layerEntitySet in self.layerEntitySetList:\n partial = layerEntitySet.getFeatureCollection()\n if partial is not None:\n result.extend(partial)\n return result\n\n\n def selectOnLayer(self, incremental = True):\n for layerEntitySet in self.layerEntitySetList:\n layerEntitySet.selectOnLayer(incremental)\n\n\n def deselectOnLayer(self):\n for layerEntitySet in self.layerEntitySetList:\n layerEntitySet.deselectOnLayer()\n\n\n def containsEntity(self, entity):\n layerEntitySet = self.findLayerEntitySet(entity.layer)\n if layerEntitySet is None: \n return False\n return layerEntitySet.containsFeature(entity.featureId)\n \n\n def addEntity(self, entity):\n if entity is None or entity.isInitialized() == False:\n return False\n layerEntitySet = self.findLayerEntitySet(entity.layer)\n if layerEntitySet is None: \n layerEntitySet = QadLayerEntitySet()\n layerEntitySet.set(entity.layer)\n self.layerEntitySetList.append(layerEntitySet)\n return layerEntitySet.addFeature(entity.featureId)\n \n\n def removeEntity(self, entity):\n layerEntitySet = self.findLayerEntitySet(entity.layer)\n if layerEntitySet is None:\n return False\n return layerEntitySet.removeFeature(entity.featureId)\n \n \n def removeLayerEntitySet(self, layer):\n i = 0\n for layerEntitySet in self.layerEntitySetList:\n if layerEntitySet.id() == layer.id():\n del layerEntitySet[i]\n return True\n i = i + 1\n return False\n\n\n def addLayerEntitySet(self, layerEntitySet): \n _layerEntitySet = self.findLayerEntitySet(layerEntitySet)\n if _layerEntitySet is None:\n _layerEntitySet = QadLayerEntitySet()\n _layerEntitySet.set(layerEntitySet.layer)\n self.layerEntitySetList.append(_layerEntitySet)\n _layerEntitySet.addFeatures(layerEntitySet.featureIds)\n \n \n def unite(self, entitySet):\n if entitySet is None:\n return\n for layerEntitySet in entitySet.layerEntitySetList:\n _layerEntitySet = self.findLayerEntitySet(layerEntitySet)\n if _layerEntitySet is None:\n _layerEntitySet = QadLayerEntitySet()\n _layerEntitySet.set(layerEntitySet.layer)\n self.layerEntitySetList.append(_layerEntitySet)\n _layerEntitySet.unite(layerEntitySet)\n \n\n def intersect(self, entitySet):\n if entitySet is None:\n return\n for i in xrange(len(self.layerEntitySetList) - 1, -1, -1):\n _layerEntitySet = self.layerEntitySetList[i]\n layerEntitySet = entitySet.findLayerEntitySet(_layerEntitySet)\n if layerEntitySet is None:\n del self.layerEntitySetList[i]\n else:\n _layerEntitySet.intersect(layerEntitySet)\n\n\n def subtract(self, entitySet):\n if entitySet is None:\n return\n for _layerEntitySet in self.layerEntitySetList: \n layerEntitySet = entitySet.findLayerEntitySet(_layerEntitySet)\n if layerEntitySet is not None:\n _layerEntitySet.subtract(layerEntitySet)\n\n\n def removeNotExisting(self):\n for layerEntitySet in self.layerEntitySetList: \n layerEntitySet.removeNotExisting()\n\n\n def removeNotEditable(self):\n for i in xrange(len(self.layerEntitySetList) - 1, -1, -1): \n layerEntitySet = self.layerEntitySetList[i]\n if layerEntitySet.layer.isEditable() == False:\n del self.layerEntitySetList[i]\n \n\n def removeGeomType(self, type):\n for i in xrange(len(self.layerEntitySetList) - 1, -1, -1): \n layerEntitySet = self.layerEntitySetList[i]\n if layerEntitySet.layer.geometryType() == type:\n del self.layerEntitySetList[i]\n\n\n def purge(self):\n # rimuove i layer con zero oggetti\n for i in xrange(len(self.layerEntitySetList) - 1, -1, -1): \n layerEntitySet = self.layerEntitySetList[i]\n if layerEntitySet.count() == 0:\n del self.layerEntitySetList[i]\n \n"
},
{
"alpha_fraction": 0.5358075499534607,
"alphanum_fraction": 0.5389779806137085,
"avg_line_length": 40.24615478515625,
"blob_id": "6d72a689791cc9f4ca2c22ad5a7ebf7649ae9ec8",
"content_id": "d7dbffbd7a89ffc60ddc8639989aeaf845db4899",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5365,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 130,
"path": "/qad_mbuffer_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando mbuffer\n \n -------------------\n begin : 2013-09-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_rubberband import QadRubberBand\n\n\n#===============================================================================\n# Qad_mbuffer_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_mbuffer_maptool_ModeEnum():\n # noto niente si richiede il primo punto\n NONE_KNOWN_ASK_FOR_FIRST_PT = 1 \n # noto il primo punto si richiede la larghezza del buffer\n FIRST_PT_ASK_FOR_BUFFER_WIDTH = 2 \n\n#===============================================================================\n# Qad_mbuffer_maptool class\n#===============================================================================\nclass Qad_mbuffer_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.startPtForBufferWidth = None\n # vedi il numero minimo di punti affinché venga riconosciuto un arco o un cerchio\n # nei files qad_arc.py e qad_circle.py\n self.segments = 12\n self.entitySet = QadEntitySet()\n self.geomType = QGis.Polygon\n self.__rubberBand = QadRubberBand(self.canvas, True)\n\n def setRubberBandColor(self, rubberBandBorderColor, rubberBandFillColor):\n if rubberBandBorderColor is not None:\n self.__rubberBand.setBorderColor(rubberBandBorderColor)\n if rubberBandFillColor is not None:\n self.__rubberBand.setFillColor(rubberBandFillColor)\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__rubberBand.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__rubberBand.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__rubberBand.reset()\n self.mode = None \n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__rubberBand.reset()\n \n # noto il primo punto si richiede la larghezza del buffer\n if self.mode == Qad_mbuffer_maptool_ModeEnum.FIRST_PT_ASK_FOR_BUFFER_WIDTH:\n width = qad_utils.getDistance(self.startPtForBufferWidth, self.tmpPoint)\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n \n for layerEntitySet in self.entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n geoms = layerEntitySet.getGeometryCollection()\n \n for geom in geoms:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n newGeom = self.layerToMapCoordinates(layer, geom)\n bufferGeom = qad_utils.ApproxCurvesOnGeom(newGeom.buffer(width, self.segments), \\\n self.segments, self.segments, \\\n tolerance)\n if bufferGeom:\n # trasformo la geometria nel crs del layer\n self.__rubberBand.addGeometry(self.mapToLayerCoordinates(layer, bufferGeom), layer)\n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__rubberBand.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__rubberBand.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n # noto niente si richiede il primo punto\n if self.mode == Qad_mbuffer_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_FIRST_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il primo punto si richiede la larghezza del buffer\n elif self.mode == Qad_mbuffer_maptool_ModeEnum.FIRST_PT_ASK_FOR_BUFFER_WIDTH:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.startPtForBufferWidth)\n"
},
{
"alpha_fraction": 0.503433883190155,
"alphanum_fraction": 0.5170825123786926,
"avg_line_length": 39.220279693603516,
"blob_id": "d32129073e9b0dcb3f858df02b6d5967c046b7a7",
"content_id": "cd35059fdb99f5ac8d63100410d636b15df16033",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11516,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 286,
"path": "/qad_vertexmarker.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire i simboli marcatori\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\n#===============================================================================\n# QadVertexmarkerIconTypeEnum class.\n#===============================================================================\nclass QadVertexmarkerIconTypeEnum():\n NONE = 0 # nessuno\n CROSS = 1 # croce\n X = 2 # una X \n BOX = 3 # un quadrato\n TRIANGLE = 4 # triangolo equilatero con punta in su\n CIRCLE = 5 # cerchio\n CIRCLE_X = 6 # cerchio con al centro una x\n RHOMBUS = 7 # rombo\n INFINITY_LINE = 8 # linea infinita (------ . .)\n DOUBLE_BOX = 9 # due quadrati sfalsati\n PERP = 10 # simbolo di \"perpendicolare\"\n TANGENT = 11 # un cerchio con una retta tangente sopra\n DOUBLE_TRIANGLE = 12 # due triangoli uno sull'altro con vertice al centro (clessidra)\n BOX_X = 13 # quadrato con al centro una x\n PARALLEL = 14 # due righe parallele a 45 gradi\n PROGRESS = 15 # linea con X e i puntini (----X-- . .)\n X_INFINITY_LINE = 16 # X e i puntini (X-- . .)\n PERP_DEFERRED = 17 # come perpendicolare con i puntini \n TANGENT_DEFERRED = 18 # come tangente con i puntini \n\n\nclass QadVertexMarker(QgsMapCanvasItem):\n \"\"\"\n Classe che gestisce i marcatori dei vertici\n \"\"\"\n \n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, mapCanvas):\n QgsMapCanvasItem.__init__(self, mapCanvas)\n self.__canvas = mapCanvas\n self.__iconType = QadVertexmarkerIconTypeEnum.X # icon to be shown\n self.__iconSize = 13 # size\n self.__center = QgsPoint(0, 0) # coordinates of the point in the center\n self.__color = QColor(255, 0, 0) # color of the marker\n self.__penWidth = 2 # pen width\n\n \n def __del__(self): \n self.removeItem()\n\n\n def removeItem(self): \n self.__canvas.scene().removeItem(self)\n \n\n def setCenter(self, point):\n self.__center = point\n pt = self.toCanvasCoordinates(self.__center)\n self.setPos(pt)\n\n\n def setIconType(self, iconType):\n self.__iconType = iconType\n\n\n def setIconSize(self, iconSize):\n self.__iconSize = iconSize\n\n\n def setColor(self, color):\n self.__color = color\n\n\n def setPenWidth(self, width):\n self.__penWidth = width\n\n \n def paint(self, painter, option, widget):\n \"\"\"\n p é un QPainter\n \"\"\"\n\n s = (self.__iconSize - 1) / 2\n\n pen = QPen(self.__color)\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n\n if self.__iconType == QadVertexmarkerIconTypeEnum.NONE:\n pass\n elif self.__iconType == QadVertexmarkerIconTypeEnum.CROSS:\n # croce\n painter.drawLine(QLineF(-s, 0, s, 0))\n painter.drawLine(QLineF( 0, -s, 0, s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.X:\n # una X \n painter.drawLine(QLineF(-s, -s, s, s))\n painter.drawLine(QLineF(-s, s, s, -s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.BOX:\n # un quadrato\n painter.drawLine(QLineF(-s, -s, s, -s))\n painter.drawLine(QLineF( s, -s, s, s))\n painter.drawLine(QLineF( s, s, -s, s))\n painter.drawLine(QLineF(-s, s, -s, -s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.TRIANGLE:\n # triangolo equilatero con punta in su\n painter.drawLine(QLineF(-s, s, s, s))\n painter.drawLine(QLineF( s, s, 0, -s))\n painter.drawLine(QLineF( 0, -s, -s, s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.CIRCLE:\n # cerchio\n # la linea é più sottile\n pen.setWidth(self.__penWidth / 2) \n painter.setPen(pen)\n painter.drawEllipse(QPointF(0, 0), s, s)\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n elif self.__iconType == QadVertexmarkerIconTypeEnum.CIRCLE_X:\n # cerchio con al centro una x\n # la linea é più sottile\n pen.setWidth(self.__penWidth / 2) \n painter.setPen(pen)\n painter.drawEllipse(QPointF(0, 0), s, s)\n painter.drawLine(QLineF(-s, -s, s, s))\n painter.drawLine(QLineF(-s, s, s, -s)) \n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n elif self.__iconType == QadVertexmarkerIconTypeEnum.RHOMBUS:\n # rombo\n painter.drawLine(QLineF( 0, -s, -s, 0))\n painter.drawLine(QLineF(-s, 0, 0, s))\n painter.drawLine(QLineF( 0, s, s, 0))\n painter.drawLine(QLineF( s, 0, 0, -s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.INFINITY_LINE:\n # linea infinita (------ . .)\n l = self.__penWidth\n painter.drawLine(QLineF(-s, 0, 0, 0))\n painter.drawLine(QLineF(2 * l, 0, 2 * l, 0))\n painter.drawLine(QLineF(4 * l, 0, 4 * l, 0))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.DOUBLE_BOX:\n # due quadrati sfalsati\n l = (s / 4)\n painter.drawLine(QLineF(-s, -s, -s, l))\n painter.drawLine(QLineF(-s, l, -l, l))\n painter.drawLine(QLineF(-l, l, -l, s))\n painter.drawLine(QLineF(-l, s, s, s))\n painter.drawLine(QLineF( s, s, s, -l))\n painter.drawLine(QLineF( s, -l, l, -l))\n painter.drawLine(QLineF( l, -l, l, -s))\n painter.drawLine(QLineF( l, -s, -s, -s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.PERP:\n # simbolo di \"perpendicolare\"\n painter.drawLine(QLineF(-s, -s, -s, s))\n painter.drawLine(QLineF(-s, s, s, s))\n painter.drawLine(QLineF(-s, 0, 0, 0))\n painter.drawLine(QLineF( 0, 0, 0, s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.TANGENT:\n # un cerchio con una retta tangente sopra\n # la linea é più sottile\n l = s - self.__penWidth\n pen.setWidth(self.__penWidth / 2) \n painter.setPen(pen)\n painter.drawEllipse(QPointF(0, 0), l + 1, l + 1)\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n painter.drawLine(QLineF(-s, -s, s, -s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.DOUBLE_TRIANGLE:\n # due triangoli uno sull'altro con vertice al centro (clessidra)\n # le linee oblique sono più sottili\n pen.setWidth(self.__penWidth / 2)\n painter.setPen(pen)\n painter.drawLine(QLineF(-s, -s, s, s))\n painter.drawLine(QLineF( s, -s, -s, s))\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n painter.drawLine(QLineF(-s, -s, s, -s))\n painter.drawLine(QLineF(-s, s, s, s))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.BOX_X:\n # quadrato con al centro una x\n painter.drawLine(QLineF(-s, -s, s, -s))\n painter.drawLine(QLineF( s, -s, s, s))\n painter.drawLine(QLineF( s, s, -s, s))\n painter.drawLine(QLineF(-s, s, -s, -s))\n # le linee oblique della x sono più sottili\n pen.setWidth(self.__penWidth / 2)\n painter.setPen(pen)\n painter.drawLine(QLineF(-s, -s, s, s))\n painter.drawLine(QLineF(-s, s, s, -s))\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n elif self.__iconType == QadVertexmarkerIconTypeEnum.PARALLEL:\n # due righe parallele a 45 gradi\n painter.drawLine(QLineF(-s, 0, 0, -s))\n painter.drawLine(QLineF( 0, s, s, 0))\n elif self.__iconType == QadVertexmarkerIconTypeEnum.PROGRESS:\n # linea con X e i puntini (----X-- . .)\n l = self.__penWidth\n painter.drawLine(QLineF(-s, 0, 0, 0))\n painter.drawLine(QLineF(2 * l, 0, 2 * l, 0))\n painter.drawLine(QLineF(4 * l, 0, 4 * l, 0))\n # le linee oblique della x sono più sottili\n pen.setWidth(self.__penWidth / 2)\n l = s / 2\n painter.setPen(pen)\n painter.drawLine(QLineF(-l, -l, l, l))\n painter.drawLine(QLineF(-l, l, l, -l))\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n elif self.__iconType == QadVertexmarkerIconTypeEnum.X_INFINITY_LINE:\n # linea con X e i puntini (X-- . .)\n l = self.__penWidth\n painter.drawLine(QLineF(2 * l, 0, 2 * l, 0))\n painter.drawLine(QLineF(4 * l, 0, 4 * l, 0))\n # le linee oblique della x sono più sottili\n pen.setWidth(self.__penWidth / 2)\n l = s / 2\n painter.setPen(pen)\n painter.drawLine(QLineF(-l, -l, l, l))\n painter.drawLine(QLineF(-l, l, l, -l))\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n elif self.__iconType == QadVertexmarkerIconTypeEnum.PERP_DEFERRED:\n painter.drawLine(QLineF(-s, -s, -s, s))\n painter.drawLine(QLineF(-s, s, s, s))\n painter.drawLine(QLineF(-s, 0, 0, 0))\n painter.drawLine(QLineF( 0, 0, 0, s))\n # simbolo di \"perpendicolare\" con i puntini\n l = s - self.__penWidth\n l = l + (self.__penWidth * 2)\n painter.drawLine(QLineF(l, 0, l, 0))\n l = l + (self.__penWidth * 2)\n painter.drawLine(QLineF(l, 0, l, 0)) \n elif self.__iconType == QadVertexmarkerIconTypeEnum.TANGENT_DEFERRED:\n # un cerchio con una retta tangente sopra\n # la linea é più sottile\n l = s - self.__penWidth\n pen.setWidth(self.__penWidth / 2) \n painter.setPen(pen)\n painter.drawEllipse(QPointF(0, 0), l + 1, l + 1)\n pen.setWidth(self.__penWidth)\n painter.setPen(pen)\n painter.drawLine(QLineF(-s, -s, s, -s))\n # come tangente con i puntini\n l = l + (self.__penWidth * 2)\n painter.drawLine(QLineF(l, 0, l, 0))\n l = l + (self.__penWidth * 2)\n painter.drawLine(QLineF(l, 0, l, 0)) \n \n\n def boundingRect(self):\n a = self.__iconSize / 2.0 + 1\n width = 2 * a + self.__penWidth * 2\n height = 2 * a\n return QRectF(-a, -a, width, height)\n\n\n def updatePosition(self):\n self.setCenter(self.__center)\n"
},
{
"alpha_fraction": 0.5779937505722046,
"alphanum_fraction": 0.5812880992889404,
"avg_line_length": 42.05673599243164,
"blob_id": "eec5c76c24c792d21b2b589050c2eac97b7c75de",
"content_id": "4212f00af774ce49fef43a57177b8ec9b1ad5aa3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6074,
"license_type": "no_license",
"max_line_length": 175,
"num_lines": 141,
"path": "/qad_mpolygon_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando MPOLYGON per disegnare un poligono\n \n -------------------\n begin : 2013-09-18\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_pline_cmd import QadPLINECommandClass\nfrom qad_msg import QadMsg\nfrom qad_textwindow import *\nfrom qad_getpoint import *\nimport qad_utils\nimport qad_layer\n\n\n# Classe che gestisce il comando MPOLYGON\nclass QadMPOLYGONCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadMPOLYGONCommandClass(self.plugIn)\n \n def getName(self):\n return QadMsg.translate(\"Command_list\", \"MPOLYGON\")\n\n def getEnglishName(self):\n return \"MPOLYGON\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runMPOLYGONCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/mpolygon.png\")\n\n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_MPOLYGON\", \"Draws a polygon by many methods.\\nA Polygon is a closed sequence of straight line segments,\\narcs or a combination of two.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.vertices = []\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare un poligono\n # che non verrà salvato su un layer\n self.virtualCmd = False\n self.rubberBandBorderColor = None\n self.rubberBandFillColor = None\n self.PLINECommand = None\n\n def __del__(self):\n QadCommandClass.__del__(self)\n del self.SSGetClass\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.PLINECommand is not None:\n self.PointMapTool = self.PLINECommand.getPointMapTool(drawMode)\n return self.PointMapTool\n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n\n\n def setRubberBandColor(self, rubberBandBorderColor, rubberBandFillColor):\n self.rubberBandBorderColor = rubberBandBorderColor\n self.rubberBandFillColor = rubberBandFillColor\n if self.PLINECommand is not None:\n self.PLINECommand.setRubberBandColor(rubberBandBorderColor, rubberBandFillColor)\n\n\n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n currLayer, errMsg = qad_layer.getCurrLayerEditable(self.plugIn.canvas, QGis.Polygon)\n if currLayer is None:\n self.showErr(errMsg)\n return True # fine comando\n\n #=========================================================================\n # RICHIESTA PRIMO PUNTO PER SELEZIONE OGGETTI\n if self.step == 0:\n self.PLINECommand = QadPLINECommandClass(self.plugIn, True)\n self.PLINECommand.setRubberBandColor(self.rubberBandBorderColor, self.rubberBandFillColor)\n # se questo flag = True il comando serve all'interno di un altro comando per disegnare una linea\n # che non verrà salvata su un layer\n self.PLINECommand.virtualCmd = True \n self.PLINECommand.asToolForMPolygon = True # per rubberband tipo poligono\n self.PLINECommand.run(msgMapTool, msg)\n self.step = 1\n return False # continua \n\n #=========================================================================\n # RISPOSTA ALLA RICHIESTA PUNTO (da step = 0 o 1)\n elif self.step == 1: # dopo aver atteso un punto si riavvia il comando\n if self.PLINECommand.run(msgMapTool, msg) == True:\n verticesLen = len(self.PLINECommand.vertices)\n if verticesLen >= 3:\n self.vertices = self.PLINECommand.vertices[:] # copio la lista\n firstVertex = self.vertices[0]\n # se l'ultimo vertice non é uguale al primo\n if self.vertices[verticesLen - 1] != firstVertex:\n # aggiungo un vertice con le stesse coordinate del primo\n self.vertices.append(firstVertex)\n if self.virtualCmd == False: # se si vuole veramente salvare la polylinea in un layer \n if qad_layer.addPolygonToLayer(self.plugIn, currLayer, self.vertices) == False: \n self.showMsg(QadMsg.translate(\"Command_MPOLYGON\", \"\\nPolygon not valid.\\n\"))\n del self.vertices[:] # svuoto la lista\n else:\n self.showMsg(QadMsg.translate(\"Command_MPOLYGON\", \"\\nPolygon not valid.\\n\"))\n \n del self.PLINECommand\n self.PLINECommand = None\n \n return True # fine\n \n return False\n"
},
{
"alpha_fraction": 0.5209630727767944,
"alphanum_fraction": 0.5285536646842957,
"avg_line_length": 41.13999938964844,
"blob_id": "fc967434623c80a4e31b643542a8f60faef3e3c7",
"content_id": "30a1cbf33d21b08bd3ee22aaf9c38577be103373",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16877,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 400,
"path": "/qad_snappointsdisplaymanager.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per visualizzare i punti di snap\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_snapper import *\nfrom qad_vertexmarker import *\nfrom qad_rubberband import createRubberBand\n\n\nclass QadSnapPointsDisplayManager():\n \"\"\"\n Classe che gestisce la visualizzazione dei punti di snap\n \"\"\"\n\n \n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, mapCanvas):\n self.__mapCanvas = mapCanvas\n self.__vertexMarkers = [] # lista dei marcatori puntuali visualizzati\n self.__startPoint = QgsPoint() \n self.__iconSize = 13 # size\n self.__color = QColor(255, 0, 0) # color of the marker\n self.__penWidth = 2 # pen width \n self.__lineMarkers = [] # lista dei RubberBand visualizzati\n \n #============================================================================\n # __del__\n #============================================================================\n def __del__(self):\n self.removeItems()\n\n\n def removeItems(self):\n self.hide()\n \n # svuoto la lista dei marker rimuovendoli dal canvas\n for vertexMarker in self.__vertexMarkers:\n vertexMarker.removeItem()\n del self.__vertexMarkers[:]\n\n # svuoto la linea di estensione rimuovendoli dal canvas\n for lineMarker in self.__lineMarkers:\n self.__mapCanvas.scene().removeItem(lineMarker)\n del self.__lineMarkers[:]\n\n\n def setIconSize(self, iconSize):\n self.__iconSize = iconSize\n\n\n def setColor(self, color):\n self.__color = color\n\n\n def setPenWidth(self, width):\n self.__penWidth = width\n\n\n def setStartPoint(self, point):\n \"\"\"\n Setta il punto di partenza per la modalità di snap PAR\n \"\"\"\n self.__startPoint = point\n\n\n def __getIconType(self, snapType): \n if snapType == QadSnapTypeEnum.END or snapType == QadSnapTypeEnum.END_PLINE:\n return QadVertexmarkerIconTypeEnum.BOX\n elif snapType == QadSnapTypeEnum.MID:\n return QadVertexmarkerIconTypeEnum.TRIANGLE\n elif snapType == QadSnapTypeEnum.CEN:\n return QadVertexmarkerIconTypeEnum.CIRCLE\n elif snapType == QadSnapTypeEnum.NOD:\n return QadVertexmarkerIconTypeEnum.CIRCLE_X\n elif snapType == QadSnapTypeEnum.QUA:\n return QadVertexmarkerIconTypeEnum.RHOMBUS\n elif snapType == QadSnapTypeEnum.INT:\n return QadVertexmarkerIconTypeEnum.X\n elif snapType == QadSnapTypeEnum.INS:\n return QadVertexmarkerIconTypeEnum.DOUBLE_BOX\n elif snapType == QadSnapTypeEnum.PER:\n return QadVertexmarkerIconTypeEnum.PERP\n elif snapType == QadSnapTypeEnum.TAN:\n return QadVertexmarkerIconTypeEnum.TANGENT\n elif snapType == QadSnapTypeEnum.NEA:\n return QadVertexmarkerIconTypeEnum.DOUBLE_TRIANGLE\n elif snapType == QadSnapTypeEnum.APP:\n return QadVertexmarkerIconTypeEnum.BOX_X\n elif snapType == QadSnapTypeEnum.EXT:\n return QadVertexmarkerIconTypeEnum.INFINITY_LINE\n elif snapType == QadSnapTypeEnum.PAR:\n return QadVertexmarkerIconTypeEnum.PARALLEL\n elif snapType == QadSnapTypeEnum.PR:\n return QadVertexmarkerIconTypeEnum.PROGRESS\n elif snapType == QadSnapTypeEnum.EXT_INT:\n return QadVertexmarkerIconTypeEnum.X_INFINITY_LINE\n elif snapType == QadSnapTypeEnum.PER_DEF:\n return QadVertexmarkerIconTypeEnum.PERP_DEFERRED\n elif snapType == QadSnapTypeEnum.TAN_DEF:\n return QadVertexmarkerIconTypeEnum.TANGENT_DEFERRED \n else:\n return QadVertexmarkerIconTypeEnum.NONE \n \n \n def hide(self):\n \"\"\"\n Nasconde i marcatori precedentemente visualizzati\n \"\"\"\n for vertexMarker in self.__vertexMarkers:\n vertexMarker.hide()\n \n for lineMarker in self.__lineMarkers:\n lineMarker.hide()\n\n \n def show(self, SnapPoints, \\\n extLines = None, extArcs = None, \\\n parLines = None, \\\n intExtLine = None, intExtArc = None):\n \"\"\"\n Visualizza i punti di snap, riceve un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n e\n lista delle linee da estendere (ogni elemento é una lista di 2 punti = linea) per la modalità di snap EXT\n lista degli archi da estendere (ogni elemento é un arco) per la modalità di snap EXT\n lista delle linee per modo parallelo (ogni elemento é una lista di 2 punti = linea) per la modalità di snap PAR\n linea per intersezione su estensione (lista di 2 punti = linea) per la modalità di snap EXT_INT\n arco per intersezione su estensione per la modalità di snap EXT_INT\n \"\"\"\n self.hide()\n\n # svuoto la lista dei marker\n for vertexMarker in self.__vertexMarkers:\n vertexMarker.removeItem()\n del self.__vertexMarkers[:]\n \n # svuoto la linea di estensione\n for lineMarker in self.__lineMarkers:\n self.__mapCanvas.scene().removeItem(lineMarker)\n del self.__lineMarkers[:]\n \n # punti di snap\n for snapPoint in SnapPoints.items():\n snapType = snapPoint[0]\n for point in snapPoint[1]:\n # disegno il marcatore di snap\n self.__vertexMarkers.append(self.getVertexMarker(snapType, point))\n\n # linee di estensione\n if snapType == QadSnapTypeEnum.EXT and (extLines is not None):\n for extLine in extLines:\n dummyPt = qad_utils.getPerpendicularPointOnInfinityLine(extLine[0], extLine[1], point)\n # se dummyPt e point sono così vicini da essere considerati uguali\n if qad_utils.ptNear(point, dummyPt):\n # prendo il vertice più vicino a point\n if qad_utils.getDistance(point, extLine[0]) < qad_utils.getDistance(point, extLine[1]):\n dummyPt = extLine[0]\n else:\n dummyPt = extLine[1]\n \n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n dummyPt = qad_utils.getAdjustedRubberBandVertex(point, dummyPt) \n # disegno la linea di estensione\n self.__lineMarkers.append(self.getLineMarker(point, dummyPt))\n \n # archi di estensione\n if snapType == QadSnapTypeEnum.EXT and (extArcs is not None):\n for extArc in extArcs:\n angle = qad_utils.getAngleBy2Pts(extArc.center, point)\n arc = QadArc(extArc)\n \n if qad_utils.getDistance(point, arc.getStartPt()) > \\\n qad_utils.getDistance(point, arc.getEndPt()):\n arc.endAngle = angle\n else:\n arc.startAngle = angle\n \n # disegno l'arco di estensione\n arcMarker = self.getArcMarker(arc)\n if arcMarker is not None:\n self.__lineMarkers.append(arcMarker) \n \n # linee di parallelismo\n if snapType == QadSnapTypeEnum.PAR and (self.__startPoint is not None):\n boundBox = self.__mapCanvas.extent()\n xMin = boundBox.xMinimum()\n yMin = boundBox.yMinimum()\n xMax = boundBox.xMaximum()\n yMax = boundBox.yMaximum()\n\n upperIntersX = qad_utils.getXOnInfinityLine(self.__startPoint, point, yMax)\n if upperIntersX > xMax or upperIntersX < xMin:\n upperIntersX = None\n \n lowerIntersX = qad_utils.getXOnInfinityLine(self.__startPoint, point, yMin)\n if lowerIntersX > xMax or lowerIntersX < xMin:\n lowerIntersX = None\n \n leftIntersY = qad_utils.getYOnInfinityLine(self.__startPoint, point, xMin)\n if leftIntersY > yMax or leftIntersY < yMin:\n leftIntersY = None\n\n rightIntersY = qad_utils.getYOnInfinityLine(self.__startPoint, point, xMax)\n if rightIntersY > yMax or rightIntersY < yMin:\n rightIntersY = None\n\n p1 = None\n p2 = None\n \n if upperIntersX is not None:\n p1 = QgsPoint(upperIntersX, yMax)\n \n if leftIntersY is not None:\n if leftIntersY != yMax:\n if p1 is None:\n p1 = QgsPoint(xMin, leftIntersY)\n else: \n p2 = QgsPoint(xMin, leftIntersY) \n \n if lowerIntersX is not None:\n if lowerIntersX != xMin:\n if p1 is None:\n p1 = QgsPoint(lowerIntersX, yMin)\n elif p2 is None: \n p2 = QgsPoint(lowerIntersX, yMin) \n\n if rightIntersY is not None:\n if rightIntersY != yMin:\n if p2 is None:\n p2 = QgsPoint(xMax, rightIntersY)\n\n if (p1 is not None) and (p2 is not None): \n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n p2 = qad_utils.getAdjustedRubberBandVertex(p1, p2) \n # disegno la linea parallela\n self.__lineMarkers.append(self.getLineMarker(p1, p2)) \n\n # linea per il puntamento polare\n if snapType == QadSnapTypeEnum.POLAR and (self.__startPoint is not None):\n boundBox = self.__mapCanvas.extent()\n xMin = boundBox.xMinimum()\n yMin = boundBox.yMinimum()\n xMax = boundBox.xMaximum()\n yMax = boundBox.yMaximum()\n\n p1 = self.__startPoint\n p2 = point\n \n x2 = None\n if p2.y() > p1.y(): # semiretta che va verso l'alto\n x2 = qad_utils.getXOnInfinityLine(p1, p2, yMax)\n elif p2.y() < p1.y(): # semiretta che va verso il basso\n x2 = qad_utils.getXOnInfinityLine(p1, p2, yMin) \n else: # semiretta retta orizzontale\n if p2.x() > p1.x(): # semiretta che va verso destra\n x2 = xMax\n elif p2.x() < p1.x(): # semiretta che va verso sinistra\n x2 = xMin\n\n y2 = None\n if p2.x() > p1.x(): # semiretta che va verso destra\n y2 = qad_utils.getYOnInfinityLine(p1, p2, xMax)\n elif p2.x() < p1.x(): # semiretta che va verso sinistra\n y2 = qad_utils.getYOnInfinityLine(p1, p2, xMin) \n else: # semiretta retta verticale\n if p2.y() > p1.y(): # semiretta che va verso l'alto\n y2 = yMax\n elif p2.y() < p1.y(): # semiretta che va verso il basso\n y2 = yMin\n\n if x2 is not None:\n if x2 > xMax:\n x2 = xMax\n elif x2 < xMin:\n x2 = xMin\n \n if y2 is not None:\n if y2 > yMax:\n y2 = yMax\n elif y2 < yMin:\n y2 = yMin\n \n if (x2 is not None) and (y2 is not None):\n p2 = QgsPoint(x2, y2) \n # per un baco non ancora capito: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y \n p2 = qad_utils.getAdjustedRubberBandVertex(p1, p2) \n # disegno la linea\n self.__lineMarkers.append(self.getLineMarker(p1, p2)) \n \n # punti medi delle linee marcate come da estendere\n if extLines is not None:\n for extLine in extLines:\n point = qad_utils.getMiddlePoint(extLine[0], extLine[1])\n # disegno il marcatore di estensione \n self.__vertexMarkers.append(self.getVertexMarker(QadSnapTypeEnum.EXT, point))\n\n # punti medi degli archi marcati come da estendere\n if extArcs is not None:\n for extArc in extArcs:\n point = extArc.getMiddlePt()\n # disegno il marcatore di estensione \n self.__vertexMarkers.append(self.getVertexMarker(QadSnapTypeEnum.EXT, point))\n\n # punti medi delle linee marcate come parallele\n if parLines is not None:\n for parLine in parLines:\n point = qad_utils.getMiddlePoint(parLine[0], parLine[1])\n # disegno il marcatore di parallelo \n self.__vertexMarkers.append(self.getVertexMarker(QadSnapTypeEnum.PAR, point))\n\n # punto medio della linea marcata come intersezione estesa\n if intExtLine is not None and len(intExtLine) > 1:\n point = qad_utils.getMiddlePoint(intExtLine[0], intExtLine[1])\n # disegno il marcatore\n self.__vertexMarkers.append(self.getVertexMarker(QadSnapTypeEnum.EXT_INT, point))\n \n # punto medio dell'arco marcato come intersezione estesa \n if intExtArc is not None and len(intExtArc) == 1:\n point = intExtArc[0].getMiddlePt()\n # disegno il marcatore\n self.__vertexMarkers.append(self.getVertexMarker(QadSnapTypeEnum.EXT_INT, point))\n \n \n def getVertexMarker(self, snapType, point):\n \"\"\"\n Crea un marcatore puntuale\n \"\"\"\n vertexMarker = QadVertexMarker(self.__mapCanvas)\n vertexMarker.setIconSize(self.__iconSize)\n vertexMarker.setColor(self.__color)\n vertexMarker.setPenWidth(self.__penWidth) \n vertexMarker.setIconType(self.__getIconType(snapType)) \n vertexMarker.setCenter(point)\n return vertexMarker\n\n\n def getLineMarker(self, pt1, pt2):\n \"\"\"\n Crea un marcatore lineare\n \"\"\"\n lineMarker = createRubberBand(self.__mapCanvas, QGis.Line, True)\n lineMarker.setColor(self.__color)\n lineMarker.setLineStyle(Qt.DotLine)\n lineMarker.addPoint(pt1, False)\n lineMarker.addPoint(pt2, True) \n return lineMarker\n\n\n def getArcMarker(self, arc):\n \"\"\"\n Crea un marcatore lineare x arco\n \"\"\"\n lineMarker = createRubberBand(self.__mapCanvas, QGis.Line, True)\n lineMarker.setColor(self.__color)\n lineMarker.setLineStyle(Qt.DotLine)\n points = arc.asPolyline()\n if points is None:\n return None\n tot = len(points)\n i = 0\n while i < (tot - 1):\n lineMarker.addPoint(points[i], False)\n i = i + 1\n lineMarker.addPoint(points[i], True)\n return lineMarker\n\n "
},
{
"alpha_fraction": 0.534634530544281,
"alphanum_fraction": 0.5410869717597961,
"avg_line_length": 40.87102508544922,
"blob_id": "f3ceec17acf423da2abc8d6184b2fa68a4d0c248",
"content_id": "4388bfb4890a88d50c39431de5b2d1a49d3021b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 68596,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 1636,
"path": "/qad_snapper.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire gli snap\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nimport os.path\nfrom qgis.core import *\nimport math\nimport sys\n\n\nimport qad_utils\nfrom qad_arc import *\nfrom qad_circle import *\n\n\n#===============================================================================\n# QadSnapTypeEnum class.\n#===============================================================================\nclass QadSnapTypeEnum():\n NONE = 0 # nessuno\n END = 1 # punti finali di ogni segmento\n MID = 2 # punto medio \n CEN = 4 # centro (centroide)\n NOD = 8 # oggetto punto\n QUA = 16 # punto quadrante\n INT = 32 # intersezione\n INS = 64 # punto di inserimento\n PER = 128 # punto perpendicolare\n TAN = 256 # tangente\n NEA = 512 # punto più vicino\n C = 1024 # pulisci all object snaps\n APP = 2048 # intersezione apparente\n EXT = 4096 # estensione\n PAR = 8192 # parallelo\n DISABLE = 16384 # osnap off \n PR = 65536 # distanza progressiva\n EXT_INT = 131072 # intersezione sull'estensione\n PER_DEF = 262144 # perpendicolare differita (come NEA)\n TAN_DEF = 524288 # tangente differita (come NEA)\n POLAR = 1048576 # puntamento polare\n END_PLINE = 2097152 # punti finali dell'intera polilinea\n\n#===============================================================================\n# QadSnapModeEnum class.\n#===============================================================================\nclass QadSnapModeEnum():\n ONE_RESULT = 0 # Viene restituito solo il punto più vicino\n RESULTS_FOR_SAME_POS = 1 # vengono restituiti diversi punti che hanno la stessa posizione.\n # Questo é utile per l'editing topologico\n ALL_RESULTS = 2 # Tutti i punti\n\n#===============================================================================\n# QadVertexSearchModeEnum class.\n#===============================================================================\nclass QadVertexSearchModeEnum():\n ALL = 0 # tutti i vertici\n EXCLUDE_START_END = 1 # escludi il punto iniziale e finale\n ONLY_START_END = 2 # solo il punto iniziale e finale\n\n\n#===============================================================================\n# Qad snapper class.\n#===============================================================================\nclass QadSnapper():\n \"\"\"\n Classe che gestisce i punti di snap\n \"\"\"\n \n \n #============================================================================\n # __init__\n #============================================================================\n def __init__(self):\n self.__snapType = QadSnapTypeEnum.NONE\n self.__snapLayers = None \n self.__snapMode = QadSnapModeEnum.ONE_RESULT \n self.__snapPointCRS = None # sistema di coordinate in cui memorizzare i punti di snap \n self.__startPoint = None\n self.__toleranceExtParlines = 0\n self.__extLines = [] # lista delle linee da estendere (ogni elemento é una lista di 2 punti = linea)\n self.__extArcs = [] # lista degli archi da estendere (ogni elemento é un arco)\n self.__parLines = [] # lista delle linee per modo parallelo (ogni elemento é una lista di 2 punti = linea)\n self.__intExtLine = [] # linea per intersezione su estensione (lista di 2 punti = linea) \n self.__intExtArc = [] # arco per intersezione su estensione\n self.__cacheSnapPoints = [] \n self.__progressDistance = 0.0 # distanza progressiva dall'inizio della linea\n self.__distToExcludeNea = 0.0 # distanza entro la quale se ci sono dei punti di snap\n # diversi da nearest questi hanno priorità su nearest\n # altrimenti nearest vincerebbe sempre\n self.tmpGeometries = [] # lista di geometria non ancora esistenti ma da contare per i punti di osnap (in map coordinates)\n\n\n #============================================================================\n # SnapType\n #============================================================================\n def setSnapType(self, snapType):\n \"\"\"\n Imposta il tipo di snapping\n \"\"\" \n if self.__snapType != snapType:\n self.__snapType = snapType\n self.clearCacheSnapPoints()\n self.removeReferenceLines() \n def getSnapType(self):\n \"\"\"\n Restituisce il tipo di snapping\n \"\"\"\n return self.__snapType\n\n\n #============================================================================\n # SnapType\n #============================================================================\n def getGeometryTypesAccordingToSnapType(self):\n \"\"\"\n Verifica quali geometrie vengono coinvolte dal tipo di snap impostato\n Ritorna una lista di 3 elementi: (point, line, polygon)\n - se il primo elemento é vero il tipo punto é coinvolto altrimenti falso\n - se il secondo elemento é vero il tipo linea é coinvolto altrimenti falso\n - se il terzo elemento é vero il tipo poligono é coinvolto altrimenti falso\n \"\"\"\n if self.getSnapType() == QadSnapTypeEnum.NONE or \\\n self.getSnapType() & QadSnapTypeEnum.DISABLE:\n return False, False, False\n \n point = False\n line = False\n polygon = False\n\n # <oggetto punto> o <punto di inserimento> o <punto più vicino>\n if self.getSnapType() & QadSnapTypeEnum.NOD or \\\n self.getSnapType() & QadSnapTypeEnum.INS or \\\n self.getSnapType() & QadSnapTypeEnum.NEA:\n point = True\n \n # <punto finale> o <punto medio> o <centro (centroide o centro arco)> o \n # <intersezione> o <punto perpendicolare> o <tangente> o\n # <punto più vicino> o <intersezione apparente> o <estensione>\n # <parallelo> o <distanza progressiva> o <intersezione sull'estensione>\n if self.getSnapType() & QadSnapTypeEnum.END or \\\n self.getSnapType() & QadSnapTypeEnum.END_PLINE or \\\n self.getSnapType() & QadSnapTypeEnum.MID or \\\n self.getSnapType() & QadSnapTypeEnum.CEN or \\\n self.getSnapType() & QadSnapTypeEnum.QUA or \\\n self.getSnapType() & QadSnapTypeEnum.INT or \\\n self.getSnapType() & QadSnapTypeEnum.PER or \\\n self.getSnapType() & QadSnapTypeEnum.TAN or \\\n self.getSnapType() & QadSnapTypeEnum.NEA or \\\n self.getSnapType() & QadSnapTypeEnum.APP or \\\n self.getSnapType() & QadSnapTypeEnum.EXT or \\\n self.getSnapType() & QadSnapTypeEnum.PAR or \\\n self.getSnapType() & QadSnapTypeEnum.PR or \\\n self.getSnapType() & QadSnapTypeEnum.EXT_INT or \\\n self.getSnapType() & QadSnapTypeEnum.PER_DEF or \\\n self.getSnapType() & QadSnapTypeEnum.TAN_DEF:\n line = True\n \n # <punto finale> o <punto medio> o <centro (centroide o centro arco)> o \n # <punto quadrante> o <intersezione> o <punto perpendicolare> o <tangente> o\n # <punto più vicino> o <intersezione apparente> o <estensione>\n # <parallelo> o <distanza progressiva> o <intersezione sull'estensione>\n if self.getSnapType() & QadSnapTypeEnum.END or \\\n self.getSnapType() & QadSnapTypeEnum.MID or \\\n self.getSnapType() & QadSnapTypeEnum.CEN or \\\n self.getSnapType() & QadSnapTypeEnum.QUA or \\\n self.getSnapType() & QadSnapTypeEnum.INT or \\\n self.getSnapType() & QadSnapTypeEnum.PER or \\\n self.getSnapType() & QadSnapTypeEnum.TAN or \\\n self.getSnapType() & QadSnapTypeEnum.NEA or \\\n self.getSnapType() & QadSnapTypeEnum.APP or \\\n self.getSnapType() & QadSnapTypeEnum.EXT or \\\n self.getSnapType() & QadSnapTypeEnum.PAR or \\\n self.getSnapType() & QadSnapTypeEnum.PR or \\\n self.getSnapType() & QadSnapTypeEnum.EXT_INT or \\\n self.getSnapType() & QadSnapTypeEnum.PER_DEF or \\\n self.getSnapType() & QadSnapTypeEnum.TAN_DEF:\n polygon = True\n\n return point, line, polygon\n\n\n #============================================================================\n # Snapmode\n #============================================================================\n def setSnapMode(self, snapMode):\n \"\"\"\n Imposta la modalità di snapping\n \"\"\" \n self.__snapMode = snapMode\n def getSnapMode(self):\n \"\"\"\n Restituisce il modo di snapping\n \"\"\"\n return self.__snapMode\n\n\n #============================================================================\n # SnapLayers\n #============================================================================\n def setSnapLayers(self, snapLayers):\n \"\"\"\n Imposta i layer da considerare nello snapping\n \"\"\" \n self.__snapLayers = snapLayers\n self.clearCacheSnapPoints()\n def getSnapLayers(self):\n \"\"\"\n Restituisce la lista dei layer da considerare per lo snapping\n \"\"\"\n return self.__snapLayers\n\n\n #============================================================================\n # SnapPointCRS\n #============================================================================\n def setSnapPointCRS(self, snapPointCRS):\n \"\"\"\n Imposta il sistema di coordinate in cui memorizzare i punti di snap\n CRS é QgsCoordinateReferenceSystem\n \"\"\" \n if self.__snapPointCRS != snapPointCRS:\n self.__snapPointCRS = snapPointCRS\n self.clearCacheSnapPoints()\n def getSnapPointCRS(self):\n \"\"\"\n Restituisce il sistema di coordinate in cui memorizzare i punti di snap\n \"\"\"\n return self.__snapPointCRS\n\n\n #============================================================================\n # setStartPoint\n #============================================================================\n def setStartPoint(self, startPoint, CRS = None):\n \"\"\"\n il punto é espresso in __snapPointCRS se CRS = None\n \"\"\"\n if startPoint is not None and CRS is not None:\n self.__startPoint = self.__transformPoint(startPoint, CRS, self.getSnapPointCRS()) # trasformo il punto\n else:\n self.__startPoint = startPoint \n\n\n #============================================================================\n # setDistToExcludeNea\n #============================================================================\n def setDistToExcludeNea(self, distToExcludeNea):\n \"\"\"\n setta la distanza entro la quale se ci sono dei punti di snap diversi da nearest \n questi hanno priorità su nearest altrimenti nearest vincerebbe sempre\n \"\"\"\n self.__distToExcludeNea = distToExcludeNea\n\n\n #===========================================================================\n # ReferenceLines\n #===========================================================================\n def toggleReferenceLines(self, geom, point, CRS = None):\n # usato solo per snap EXT o PAR\n if not(self.__snapType & QadSnapTypeEnum.EXT) and \\\n not(self.__snapType & QadSnapTypeEnum.PAR):\n return\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n # verifico se ci sono archi\n arc = None\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n info = arcList.arcAt(afterVertex)\n if info is not None:\n arc = info[0]\n \n # verifico se ci sono cerchi\n circle = None\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0:\n info = circleList.circleAt(afterVertex)\n if info is not None:\n circle = info[0]\n\n pt1 = g.vertexAt(afterVertex - 1) \n pt2 = g.vertexAt(afterVertex) \n \n if self.__snapType & QadSnapTypeEnum.EXT:\n if arc is not None: # se fa parte di un arco\n self.toggleExtArc(arc, CRS)\n elif circle is None: # se non fa parte di un cerchio\n self.toggleExtLine(pt1, pt2)\n if self.__snapType & QadSnapTypeEnum.PAR:\n if (arc is None) and (circle is None): # solo se non fa parte di un arco o di un cerchio\n self.toggleParLine(pt1, pt2)\n\n def removeReferenceLines(self):\n self.removeExtLines()\n self.removeExtArcs()\n self.removeParLines()\n self.removeIntExtLine()\n self.removeIntExtArc()\n \n\n #============================================================================\n # setToleranceExtParLines\n #============================================================================\n def setToleranceExtParLines(self, tolerance):\n self.__toleranceExtParlines = tolerance\n \n\n #============================================================================\n # tmpGeometries\n #============================================================================\n def clearTmpGeometries(self): \n del self.tmpGeometries[:] # svuoto la lista\n\n def setTmpGeometry(self, geom, CRS = None): \n self.clearTmpGeometries()\n self.appendTmpGeometry(geom)\n\n def appendTmpGeometry(self, geom, CRS = None):\n if geom is None:\n return\n if CRS is not None:\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n self.tmpGeometries.append(g)\n else:\n self.tmpGeometries.append(geom)\n\n def setTmpGeometries(self, geoms, CRS = None): \n self.clearTmpGeometries()\n for g in geoms:\n self.appendTmpGeometry(g, CRS)\n\n\n #===========================================================================\n # getSnapPoint\n #===========================================================================\n def getSnapPoint(self, geom, point, CRS, excludePoints = None, polarAng = None, isTemporaryGeom = False):\n \"\"\"\n Data una geometria ed un punto (posizione del cursore) nel sistema di coordinate CRS \n ottiene i punti di snap (con esclusione dei punti in excludePoints).\n Resituisce un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n - CRS = sistema di coordinate in cui é espressa la geom e il punto (QgsCoordinateReferenceSystem)\n - excludePoints = lista di punti da escludere espressa in __snapPointCRS\n - polarAng angolo in radianti per il puntamento polare\n - isTemporaryGeom flag che indica se geom é un oggetto temporaneo che ancora non esiste\n \"\"\"\n\n p = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto in coord dei punti di snap\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n\n # cerca nella cache i punti di snap statici per una geometria\n if geom is not None:\n staticSnapPoints = self.__getCacheSnapPoints(g)\n if staticSnapPoints is None:\n staticSnapPoints = self.getStaticSnapPoints(g, None, isTemporaryGeom)\n self.__setCacheSnapPoints(g, staticSnapPoints)\n else:\n staticSnapPoints = dict()\n \n # snap dinamici \n dynamicSnapPoints = self.getDynamicSnapPoints(g, p)\n\n allSnapPoints = staticSnapPoints\n for item in dynamicSnapPoints.items():\n allSnapPoints[item[0]] = item[1]\n \n # puntamento polare\n if (self.__startPoint is not None) and (polarAng is not None):\n allSnapPoints[QadSnapTypeEnum.POLAR] = self.getPolarCoord(point, polarAng)\n\n if self.__snapMode == QadSnapModeEnum.ONE_RESULT:\n # Viene restituito solo il punto più vicino\n result = self.__getNearestPoints(p, allSnapPoints)\n elif self.__snapMode == QadSnapModeEnum.RESULTS_FOR_SAME_POS:\n # take all snapping Results within a certain tolerance because rounding differences may occur \n result = self.__getNearestPoints(p, allSnapPoints, 0.000001)\n else:\n result = allSnapPoints # Vengono restituiti tutti i punti\n \n if excludePoints is not None: \n for p in excludePoints:\n self.__delPoint(p, result)\n \n return result\n\n #============================================================================\n # CacheSnapPoints\n #============================================================================\n def clearCacheSnapPoints(self): \n del self.__cacheSnapPoints[:] # svuota la cache\n def __getCacheSnapPoints(self, geom): \n # cerca i punti di snap per una geometria\n for item in self.__cacheSnapPoints:\n if geom.equals(item[0]) == True:\n return item[1]\n return None\n def __setCacheSnapPoints(self, geom, snapPoints):\n g = QgsGeometry(geom) # copy constructor will prompt a deep copy of the object\n self.__cacheSnapPoints.append([g, snapPoints])\n\n\n #============================================================================\n # getStaticSnapPoints\n #============================================================================\n def getStaticSnapPoints(self, geom, CRS = None, isTemporaryGeom = False):\n \"\"\"\n Data una geometria ottiene i punti di snap statici che non dipendono dalla \n posizione del cursore.\n Resituisce un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n - isTemporaryGeom flag che indica se geom é un oggetto temporaneo che ancora non esiste \n \"\"\"\n \n result = dict()\n\n if (self.__snapType & QadSnapTypeEnum.DISABLE):\n return result\n \n if self.__snapType & QadSnapTypeEnum.END:\n result[QadSnapTypeEnum.END] = self.getEndPoints(geom, CRS)\n if self.__snapType & QadSnapTypeEnum.END_PLINE:\n result[QadSnapTypeEnum.END_PLINE] = self.getEndPoints(geom, CRS, QadVertexSearchModeEnum.ONLY_START_END)\n if self.__snapType & QadSnapTypeEnum.MID:\n result[QadSnapTypeEnum.MID] = self.getMidPoints(geom, CRS)\n if self.__snapType & QadSnapTypeEnum.NOD:\n result[QadSnapTypeEnum.NOD] = self.getNodPoint(geom, CRS) \n if self.__snapType & QadSnapTypeEnum.QUA:\n result[QadSnapTypeEnum.QUA] = self.getQuaPoints(geom, CRS)\n if self.__snapType & QadSnapTypeEnum.INT:\n result[QadSnapTypeEnum.INT] = self.getIntPoints(geom, CRS, isTemporaryGeom)\n if self.__snapType & QadSnapTypeEnum.INS:\n result[QadSnapTypeEnum.INS] = self.getNodPoint(geom, CRS)\n if self.__snapType & QadSnapTypeEnum.APP:\n result[QadSnapTypeEnum.APP] = self.getIntPoints(geom, CRS, isTemporaryGeom)\n \n return result\n \n \n #============================================================================\n # getDynamicSnapPoints\n #============================================================================\n def getDynamicSnapPoints(self, geom, point, CRS = None):\n \"\"\"\n Data una geometria ottiene i punti di snap dinamici che dipendono dalla \n posizione del cursore (nel sistema di coordinate di geomLayer) o\n o da __startPoint (nel sistema di coordinate __snapPointCRS).\n Resituisce un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n - CRS = sistema di coordinate in cui sono espressi geom e point (QgsCoordinateReferenceSystem)\n \"\"\"\n \n result = dict()\n\n if (self.__snapType & QadSnapTypeEnum.DISABLE):\n return result\n \n if self.__snapType & QadSnapTypeEnum.CEN:\n result[QadSnapTypeEnum.CEN] = self.getCenPoint(geom, point, CRS) \n if self.__snapType & QadSnapTypeEnum.PER:\n result[QadSnapTypeEnum.PER] = self.getPerPoints(geom, point, CRS)\n if self.__snapType & QadSnapTypeEnum.TAN:\n result[QadSnapTypeEnum.TAN] = self.getTanPoints(geom, CRS)\n if self.__snapType & QadSnapTypeEnum.NEA:\n result[QadSnapTypeEnum.NEA] = self.getNeaPoints(geom, point, CRS)\n if self.__snapType & QadSnapTypeEnum.EXT:\n result[QadSnapTypeEnum.EXT] = self.getExtPoints(point, CRS)\n if self.__snapType & QadSnapTypeEnum.PAR:\n result[QadSnapTypeEnum.PAR] = self.getParPoints(point, CRS)\n if self.__snapType & QadSnapTypeEnum.PR:\n result[QadSnapTypeEnum.PR] = self.getProgressPoint(geom, point, CRS)[0]\n if self.__snapType & QadSnapTypeEnum.EXT_INT:\n result[QadSnapTypeEnum.EXT_INT] = self.getIntExtPoint(geom, point, CRS) \n if self.__snapType & QadSnapTypeEnum.PER_DEF:\n result[QadSnapTypeEnum.PER_DEF] = self.getNeaPoints(geom, point, CRS)\n if self.__snapType & QadSnapTypeEnum.TAN_DEF:\n if geom is not None:\n whatIs = qad_utils.whatGeomIs(point, geom)\n if (type(whatIs) != list and type(whatIs) != tuple): # se non é una linea\n result[QadSnapTypeEnum.TAN_DEF] = self.getNeaPoints(geom, point, CRS)\n \n return result\n\n\n #============================================================================\n # getEndPoints\n #============================================================================\n def getEndPoints(self, geom, CRS = None, VertexSearchMode = QadVertexSearchModeEnum.ALL):\n \"\"\"\n Cerca i punti iniziali e finali dei segmenti di una linea o di una multi-linea.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result\n \n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n geoms = qad_utils.asPointOrPolyline(g)\n for igeom in geoms:\n if (igeom.wkbType() == QGis.WKBLineString):\n # verifico se ci sono archi\n arcList = QadArcList()\n arcList.fromGeom(igeom) \n\n # verifico se ci sono cerchi\n circleList = QadCircleList()\n circleList.fromGeom(igeom) \n \n points = igeom.asPolyline() # vettore di punti\n i = 1\n vertexCount = len(points)\n for ipoint in points:\n _arc = arcList.arcAt(i - 1)\n _circle = circleList.circleAt(i - 1)\n \n if _arc is not None: # se questo punto appartiene ad un arco\n startEnd = _arc[1]\n # se il punto corrisponde al punto iniziale o finale dell'arco\n # (i - 1) perché arcAt vuole il secondo punto del segmento \n if i - 1 == startEnd[0] or i - 1 == startEnd[1]:\n inser = True\n else:\n inser = False \n elif _circle is not None: # se questo punto appartiene ad un cerchio\n inser = False\n else: # se questo punto non appartiene né ad un arco ne ad un cerchio \n inser = True\n \n if inser == True:\n if (VertexSearchMode == QadVertexSearchModeEnum.EXCLUDE_START_END):\n if (i != 1 and i != vertexCount):\n self.__appendUniquePoint(result, ipoint, CRS) # aggiungo senza duplicazione\n elif (VertexSearchMode == QadVertexSearchModeEnum.ONLY_START_END):\n if (i == 1 or i == vertexCount):\n self.__appendUniquePoint(result, ipoint) # aggiungo senza duplicazione\n else:\n self.__appendUniquePoint(result, ipoint) # aggiungo senza duplicazione\n \n i = i + 1 \n \n return result\n\n\n #============================================================================\n # getMidPoints\n #============================================================================\n def getMidPoints(self, geom, CRS = None):\n \"\"\"\n Cerca i punti medi dei segmenti di una linea o di una multi-linea.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result\n \n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n geoms = qad_utils.asPointOrPolyline(g)\n for igeom in geoms:\n if (igeom.wkbType() == QGis.WKBLineString):\n # verifico se ci sono archi\n arcList = QadArcList()\n if arcList.fromGeom(igeom) > 0:\n for arc in arcList.arcList:\n self.__appendUniquePoint(result, arc.getMiddlePt()) # senza duplicazione \n \n # verifico se ci sono cerchi\n circleList = QadCircleList()\n circleList.fromGeom(igeom) \n \n points = igeom.asPolyline() # vettore di punti\n first = True\n i = 0\n for ipoint in points:\n if first == True:\n first = False\n else:\n # se questo punto non appartiene ad un arco né ad un cerchio\n if (arcList.arcAt(i) is None) and (circleList.circleAt(i) is None): \n point = qad_utils.getMiddlePoint(prevPoint, ipoint)\n self.__appendUniquePoint(result, point) # senza duplicazione\n prevPoint = ipoint\n i = i + 1\n \n return result\n\n\n #============================================================================\n # getNodPoint\n #============================================================================\n def getNodPoint(self, geom, CRS = None):\n \"\"\"\n Cerca il punto di inserimento di un punto.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result\n \n wkbType = geom.wkbType()\n if wkbType != QGis.WKBPoint and wkbType != QGis.WKBMultiPoint:\n return result\n \n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n if wkbType == QGis.WKBPoint:\n self.__appendUniquePoint(result, g.asPoint()) # senza duplicazione\n elif wkbType == QGis.WKBMultiPoint:\n for point in g.asMultiPoint(): # vettore di punti \n self.__appendUniquePoint(result, point) # senza duplicazione\n return result \n\n\n #============================================================================\n # getQuaPoints\n #============================================================================\n def getQuaPoints(self, geom, CRS = None):\n \"\"\"\n Cerca i punti quadrante.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n \n if geom is None:\n return result\n \n wkbType = geom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBMultiPoint:\n return result\n \n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n\n if wkbType == QGis.WKBLineString or wkbType == QGis.WKBMultiLineString:\n # verifico se ci sono archi\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n for arc in arcList.arcList:\n points = arc.getQuadrantPoints()\n for point in points:\n self.__appendUniquePoint(result, point) # senza duplicazione\n else:\n # verifico se ci sono cerchi\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0: \n for circle in circleList.circleList:\n points = circle.getQuadrantPoints()\n for point in points:\n self.__appendUniquePoint(result, point) # senza duplicazione\n \n return result\n\n\n #============================================================================\n # getIntPoints\n #============================================================================\n def getIntPoints(self, geom, CRS = None, isTemporaryGeom = False):\n \"\"\"\n Cerca i punti di intersezione di un oggetto.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n - isTemporaryGeom flag che indica se geom é un oggetto temporaneo che ancora non esiste\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n for iLayer in self.__snapLayers: # ciclo sui layer da controllare\n if (iLayer.type() == QgsMapLayer.VectorLayer):\n iLayerCRS = iLayer.crs()\n geom_iLayerCoords = QgsGeometry(g)\n if CRS is None: # se non c'é CRS la geom si intende nel sistema di coord dei punti di snap\n coordTransform = QgsCoordinateTransform(self.getSnapPointCRS(), iLayerCRS) # trasformo in coord ilayer\n geom_iLayerCoords.transform(coordTransform)\n else:\n coordTransform = QgsCoordinateTransform(CRS, iLayerCRS) # trasformo in coord ilayer\n geom_iLayerCoords.transform(coordTransform)\n\n feature = QgsFeature()\n # cerco le entità che intersecano il rettangolo\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in iLayer.getFeatures(qad_utils.getFeatureRequest([], True, geom_iLayerCoords.boundingBox(), True)):\n g2 = self.__transformGeomToSnapPointCRS(feature.geometry(), iLayerCRS) # trasformo la geometria in coord dei punti di snap\n intersectionPoints = qad_utils.getIntersectionPoints(g, g2)\n if intersectionPoints is not None:\n for point in intersectionPoints:\n # trasformo il punto in coord layer\n self.__appendUniquePoint(result, point) # senza duplicazione\n \n if isTemporaryGeom:\n intersectionPoints = qad_utils.getIntersectionPoints(g, g)\n if intersectionPoints is not None:\n for point in intersectionPoints:\n # trasformo il punto in coord layer\n self.__appendUniquePoint(result, point) # senza duplicazione\n\n # lista di geometria non ancora esistenti ma da contare per i punti di osnap (in map coordinates)\n for tmpGeometry in self.tmpGeometries:\n intersectionPoints = qad_utils.getIntersectionPoints(g, tmpGeometry)\n if intersectionPoints is not None:\n for point in intersectionPoints:\n # trasformo il punto in coord layer\n self.__appendUniquePoint(result, point) # senza duplicazione\n \n return result\n \n\n #============================================================================\n # Inizio punti dinamici\n #============================================================================\n\n\n #============================================================================\n # getCenPoint\n #============================================================================\n def getCenPoint(self, geom, point, CRS = None):\n \"\"\"\n Cerca il punto centro di un arco o di un cerchio o il centroide di un poligono.\n - CRS = sistema di coordinate in cui é espressa la geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result\n\n wkbType = geom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBMultiPoint:\n return result\n elif wkbType == QGis.WKBPolygon or wkbType == QGis.WKBMultiPolygon:\n centroidGeom = geom.centroid()\n wkbType = centroidGeom.wkbType()\n if wkbType == QGis.WKBPoint:\n self.__appendUniquePoint(result, centroidGeom.asPoint()) # senza duplicazione\n elif wkbType == QGis.WKBMultiPoint:\n for centroidPt in centroidGeom.asMultiPoint(): # vettore di punti\n self.__appendUniquePoint(result, centroidGeom.asPoint()) # senza duplicazione \n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return result\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n # verifico se ci sono cerchi\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0:\n info = circleList.circleAt(afterVertex)\n if info is not None:\n circle = info[0]\n self.__appendUniquePoint(result, circle.center) # senza duplicazione \n\n # verifico se ci sono archi \n arcList = QadArcList()\n if arcList.fromGeom(g) > 0: \n info = arcList.arcAt(afterVertex)\n if info is not None:\n arc = info[0]\n self.__appendUniquePoint(result, arc.center) # senza duplicazione \n \n return result\n\n \n #============================================================================\n # getPerPoints\n #============================================================================\n def getPerPoints(self, geom, point, CRS = None):\n \"\"\"\n Cerca il punto proiezione perpendicolare di self.__startPoint \n (espresso in __snapPointCRS) sul lato di geom più vicino a point.\n - CRS = sistema di coordinate in cui sono espressi geom e point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint \n \"\"\" \n result = []\n \n if geom is None:\n return result\n \n if self.__startPoint is None:\n return result\n \n # trasformo il self.__startPoint dal sistema __snapPointCRS a quello della geometria\n startPointCRS = self.__transformPoint(self.__startPoint, self.getSnapPointCRS(), CRS)\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return result\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n\n # verifico se ci sono archi\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n info = arcList.arcAt(afterVertex)\n if info is not None:\n arc = info[0]\n PerpendicularPoints = arc.getPerpendicularPoints(startPointCRS)\n if PerpendicularPoints is not None:\n for PerpendicularPoint in PerpendicularPoints:\n # trasformo il punto in coord layer\n self.__appendUniquePoint(result, PerpendicularPoint) # senza duplicazione\n return result\n\n # verifico se ci sono cerchi\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0: \n info = circleList.circleAt(afterVertex)\n if info is not None:\n circle = info[0]\n PerpendicularPoints = circle.getPerpendicularPoints(startPointCRS)\n if PerpendicularPoints is not None:\n for PerpendicularPoint in PerpendicularPoints:\n # trasformo il punto in coord layer\n self.__appendUniquePoint(result, PerpendicularPoint) # senza duplicazione\n return result\n\n pt1 = g.vertexAt(afterVertex - 1) \n pt2 = g.vertexAt(afterVertex) \n PerpendicularPoint = qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, startPointCRS)\n self.__appendUniquePoint(result, PerpendicularPoint) # senza duplicazione\n\n return result\n\n\n #============================================================================\n # getTanPoints\n #============================================================================\n def getTanPoints(self, geom, CRS = None):\n \"\"\"\n Cerca i punti di un oggetto che sono tangenti alla retta passante per self.__startPoint \n (espresso in __snapPointCRS).\n - CRS = sistema di coordinate in cui sono espressi geom e point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n \n if geom is None:\n return result\n \n if self.__startPoint is None:\n return result\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n\n # verifico se ci sono archi\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n for arc in arcList.arcList:\n points = arc.getTanPoints(self.__startPoint)\n for point in points:\n self.__appendUniquePoint(result, point) # senza duplicazione\n\n # verifico se ci sono cerchi\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0:\n for circle in circleList.circleList:\n points = circle.getTanPoints(self.__startPoint)\n for point in points:\n self.__appendUniquePoint(result, point) # senza duplicazione\n\n return result\n\n\n #============================================================================\n # getNeaPoints\n #============================================================================\n def getNeaPoints(self, geom, point, CRS = None):\n \"\"\"\n Cerca il punto di un oggetto che é più vicino a point.\n - CRS = sistema di coordinate in cui sono espressi geom e point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result \n \n p = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto in coord dei punti di snap\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n # Riduco le geometrie in point o polyline\n geoms = qad_utils.asPointOrPolyline(g)\n\n first = True \n for g in geoms: \n if g.wkbType() == QGis.WKBPoint:\n pt = g.asPoint()\n else:\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(p, g)\n pt = dummy[1]\n\n dist = qad_utils.getDistance(p, pt)\n if first == True:\n first = False\n minDist = dist\n closestPoint = pt\n elif dist < minDist:\n minDist = dist\n closestPoint = pt\n \n self.__appendUniquePoint(result, closestPoint) # senza duplicazione\n \n return result\n\n\n #============================================================================\n # getExtPoints\n #============================================================================\n def toggleExtLine(self, pt1, pt2, CRS = None):\n \"\"\"\n Aggiunge una linea per la ricerca di punti con modalità EXT (estensione)\n se non ancora inserita in lista altrimenti la rimuove dalla lista\n pt1 e pt2 sono QgsPoint\n sourceCRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n self.toggleLine(QadSnapTypeEnum.EXT, pt1, pt2, CRS)\n\n def removeExtLines(self):\n \"\"\"\n Elimina tutte le linee per la ricerca di punti con modalità EXT (estensione)\n \"\"\"\n del self.__extLines[:] # svuoto la lista\n\n def getExtLines(self):\n return self.__extLines\n\n def toggleExtArc(self, arc, CRS = None):\n \"\"\"\n Aggiunge un arco per la ricerca di punti con modalità EXT (estensione)\n se non ancora inserito in lista altrimenti lo rimuove dalla lista\n sourceCRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n self.toggleArc(QadSnapTypeEnum.EXT, arc, CRS) \n\n def removeExtArcs(self):\n \"\"\"\n Elimina tutte gli archi per la ricerca di punti con modalità EXT (estensione)\n \"\"\"\n del self.__extArcs[:] # svuoto la lista\n\n def getExtArcs(self):\n return self.__extArcs\n\n def getExtPoints(self, point, CRS):\n \"\"\"\n Cerca i punti sui prolungamenti delle linee memorizzate nella lista __extLines e __extArcs.\n N.B. __extLines e point vanno espressi nello stesso sistema di coordinate\n - point é un QgsPoint\n - CRS = sistema di coordinate in cui é espresso point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n pt = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto\n \n if len(self.__extLines) > 0: \n for line in self.__extLines:\n ExtPoint = qad_utils.getPerpendicularPointOnInfinityLine(line[0], line[1], pt)\n if qad_utils.getDistance(pt, ExtPoint) <= self.__toleranceExtParlines:\n self.__appendUniquePoint(result, ExtPoint) # senza duplicazione\n\n if len(self.__extArcs) > 0:\n circle = QadCircle()\n for arc in self.__extArcs:\n circle.set(arc.center,arc.radius)\n ExtPoints = circle.getPerpendicularPoints(pt)\n if ExtPoints is not None:\n for ExtPoint in ExtPoints:\n if qad_utils.getDistance(pt, ExtPoint) <= self.__toleranceExtParlines:\n self.__appendUniquePoint(result, ExtPoint) # senza duplicazione\n \n return result\n\n \n #============================================================================\n # getParPoints\n #============================================================================ \n def toggleParLine(self, pt1, pt2, CRS = None):\n \"\"\"\n Aggiunge una linea per la ricerca di punti con modalità PAR (parallela)\n se non ancora inserita in lista altrimenti la rimuove dalla lista\n pt1 e pt2 sono QgsPoint\n sourceCRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n self.toggleLine(QadSnapTypeEnum.PAR, pt1, pt2, CRS) \n\n def removeParLines(self):\n \"\"\"\n Elimina tutte le linee per la ricerca di punti con modalità PAR (parallela)\n \"\"\"\n del self.__parLines[:] # svuoto la lista\n\n def getParLines(self):\n return self.__parLines\n \n def getParPoints(self, point, CRS):\n \"\"\"\n Cerca i punti sulle rette parallele alle linee memorizzate nella lista __partLines\n che passano per __startPoint e che sono più vicino a point.\n N.B. __parLines, __startPoint e point vanno espressi nello stesso sistema di coordinate\n - line é una lista di 2 punti\n - point é un QgsPoint\n - CRS = sistema di coordinate in cui é espresso point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n \n if (self.__startPoint is None) or len(self.__parLines) == 0:\n return result\n \n p2 = QgsPoint(0, 0)\n pt = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto\n \n for line in self.__parLines:\n pt1 = line[0]\n pt2 = line[1]\n diffX = pt2.x() - pt1.x()\n diffY = pt2.y() - pt1.y()\n \n if diffX == 0: # se la retta passante per pt1 e pt2 é verticale\n parPoint = QgsPoint(self.__startPoint.x(), pt.y())\n elif diffY == 0: # se la retta passante per pt1 e pt2 é orizzontle\n parPoint = QgsPoint(pt.x(), self.__startPoint.y())\n else:\n # Calcolo l'equazione della retta passante per __startPoint con coefficente angolare noto\n p2.setX(self.__startPoint.x() + diffX)\n p2.setY(self.__startPoint.y() + diffY)\n parPoint = qad_utils.getPerpendicularPointOnInfinityLine(self.__startPoint, p2, pt)\n\n if qad_utils.getDistance(pt, parPoint) <= self.__toleranceExtParlines:\n self.__appendUniquePoint(result, parPoint, CRS) # senza duplicazione\n\n return result\n\n\n #============================================================================\n # getProgressPoint\n #============================================================================\n def setProgressDistance(self, progressDistance):\n \"\"\"\n Setta la distanza progressiva dall'inizio nel sistema __snapPointCRS \n per la ricerca con modalità PR (progressiva)\n \"\"\"\n self.__progressDistance = progressDistance\n \n def getProgressDistance(self,):\n return self.__progressDistance\n\n\n def __getOverPoint(self, geom, points, pt1, pt2, dist):\n \"\"\"\n Cerca il punto sulla geometria che si estende oltre il punto pt2\n Ritorna il punto e il coeff. angolare in quel punto. usato da <getProgressPoint>\n \"\"\"\n # verifico se ci sono archi\n arc = None\n arcList = QadArcList()\n if arcList.fromGeom(geom) > 0:\n info = arcList.arcAt(len(points) - 1)\n if info is not None:\n arc = info[0]\n\n if arc is None: # se questo punto non appartiene ad un arco\n overPoint = qad_utils.getPolarPointBy2Pts(pt1, pt2, dist)\n overAngle = qad_utils.getAngleBy2Pts(pt1, pt2) \n else: # se questo punto appartiene ad un arco\n angle = dist / arc.radius\n if arc.getStartPt() == pt2:\n overPoint = qad_utils.getPolarPointByPtAngle(arc.center,\n arc.startAngle - angle,\n arc.radius)\n overAngle = angle - (math.pi / 2) \n else:\n overPoint = qad_utils.getPolarPointByPtAngle(arc.center,\n arc.endAngle + angle,\n arc.radius)\n overAngle = angle + (math.pi / 2) \n \n return [overPoint, overAngle]\n\n\n def getProgressPoint(self, geom, point, CRS = None):\n \"\"\"\n Cerca il punto sulla geometria ad un certa distanza dal vertice più vicino al punto\n (se la distanza >=0 significa verso dall'inizio alla fine della linea,\n se la distanza < 0 significa verso dalla fine all'inizio della linea.\n - CRS = sistema di coordinate in cui sono espressi geom e point (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint + una lista di coefficienti angolari dei segmenti\n su cui ricadono i punti\n \"\"\"\n result = [[],[]]\n if geom is None:\n return result \n\n if geom.wkbType() != QGis.WKBLineString:\n return result\n \n ProgressPoints = []\n segmentAngles = []\n \n p = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto in coord dei punti di snap\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n # Cerca i punti iniziali e finali dei segmenti di una linea.\n Vertexes = self.getEndPoints(g, CRS) \n \n # Cerco il vertice più vicino\n points = qad_utils.getNearestPoints(p, Vertexes)\n if len(points) == 0:\n return result\n nearestPoint = points[0]\n points = g.asPolyline() # vettore di punti\n i = 0\n for iPoint in points:\n if iPoint == nearestPoint:\n break\n i = i + 1\n \n if self.__progressDistance == 0:\n ProgressPoints.append(iPoint)\n if i == (len(points) - 1): # ultimo punto\n segmentAngles.append(qad_utils.getAngleBy2Pts(points[i - 1], points[i]))\n else:\n segmentAngles.append(qad_utils.getAngleBy2Pts(points[i], points[i + 1]))\n\n elif self.__progressDistance > 0:\n # dall'inizio della linea verso la fine\n remain = self.__progressDistance\n if i == len(points) - 1: # selezionato ultimo vertice\n pt1 = points[i - 1]\n pt2 = points[i]\n \n info = self.__getOverPoint(geom, points, pt1, pt2, remain)\n ProgressPoints.append(info[0])\n segmentAngles.append(info[1]) \n else: \n while remain > 0 and i < len(points) - 1:\n pt1 = points[i]\n pt2 = points[i + 1]\n segmentLength = qad_utils.getDistance(pt1, pt2)\n if segmentLength < remain:\n # vado al segmento successivo\n i = i + 1\n remain = remain - segmentLength\n if i == len(points) - 1: # ultimo segmento quindi vado oltre\n info = self.__getOverPoint(geom, points, pt1, pt2, remain)\n ProgressPoints.append(info[0])\n segmentAngles.append(info[1]) \n break\n elif segmentLength > remain:\n # é in questo segmento\n ProgressPoints.append(qad_utils.getPolarPointBy2Pts(pt1, pt2, remain))\n segmentAngles.append(qad_utils.getAngleBy2Pts(pt1, pt2)) \n break\n else: # era esattamente il punto p2\n ProgressPoints.append(p2)\n segmentAngles.append(qad_utils.getAngleBy2Pts(pt1, pt2)) \n break \n else: \n # dalla fine della linea verso l'inizio\n remain = self.__progressDistance * -1\n \n if i == 0: # selezionato primo vertice\n pt1 = points[1]\n pt2 = points[0]\n ProgressPoints.append(qad_utils.getPolarPointBy2Pts(pt2, pt1, -1 * remain))\n segmentAngles.append(qad_utils.getAngleBy2Pts(pt2, pt1)) \n else: \n while remain > 0 and i > 0:\n pt1 = points[i]\n pt2 = points[i - 1]\n segmentLength = qad_utils.getDistance(pt1, pt2)\n if segmentLength < remain:\n # vado al segmento precedente\n i = i - 1\n remain = remain - segmentLength\n if i == 0: # primo segmento quindi vado oltre\n info = self.__getOverPoint(geom, points, pt1, pt2, remain)\n ProgressPoints.append(info[0])\n segmentAngles.append(info[1]) \n break \n elif segmentLength > remain:\n # cerco nel segmento corrente\n ProgressPoints.append(qad_utils.getPolarPointBy2Pts(pt1, pt2, remain))\n segmentAngles.append(qad_utils.getAngleBy2Pts(pt2, pt1)) \n break\n else: # era esattamente il punto p2\n ProgressPoints.append(p2)\n segmentAngles.append(qad_utils.getAngleBy2Pts(pt2, pt1)) \n break\n \n return (ProgressPoints, segmentAngles)\n \n \n #============================================================================\n # toggleIntExtLine\n #============================================================================ \n def toggleIntExtLine(self, geom, point, CRS = None):\n \"\"\"\n Aggiunge una linea per la ricerca di punti con modalità EXT_INT (intersezione su estensione)\n se non ancora inserita altrimenti la rimuove dalla lista\n CRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n # usato solo per snap EXT_INT\n if not (self.__snapType & QadSnapTypeEnum.EXT_INT):\n return\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return result\n\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n\n # verifico se ci sono archi\n arc = None\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n info = arcList.arcAt(afterVertex)\n if info is not None:\n arc = info[0]\n \n circle = None\n\n if arc is not None: # se fa parte di un arco\n _arc = QadArc(arc)\n _arc.transformFromCRSToCRS(CRS, self.getSnapPointCRS()) # trasformo l'arco in coord layer\n\n # se non é stato selezionato alcun arco o alcuna linea lo aggiungo \n if len(self.__intExtArc) == 0 and len(self.__intExtLine) == 0:\n self.__intExtArc.append(_arc)\n elif len(self.__intExtArc) > 0:\n # se era già stato selezionato lo rimuovo\n if (_arc == self.__intExtArc[0]):\n self.removeIntExtArc()\n elif circle is None: # se non fa parte di un cerchio\n pt1 = g.vertexAt(afterVertex - 1) \n pt2 = g.vertexAt(afterVertex) \n \n if CRS is not None:\n __pt1 = self.__transformPoint(pt1, CRS, self.getSnapPointCRS()) # trasformo il punto in coord layer\n __pt2 = self.__transformPoint(pt2, CRS, self.getSnapPointCRS()) # trasformo il punto in coord layer\n else:\n __pt1 = pt1\n __pt2 = pt2\n \n # se non é stato selezionato alcun arco o alcuna linea la aggiungo \n if len(self.__intExtArc) == 0 and len(self.__intExtLine) == 0:\n self.__intExtLine.append(__pt1)\n self.__intExtLine.append(__pt2)\n elif len(self.__intExtLine) > 0:\n # se era già stata selezionata la rimuovo\n if (__pt1 == self.__intExtLine[0] or __pt1 == self.__intExtLine[1]) and \\\n (__pt2 == self.__intExtLine[0] or __pt2 == self.__intExtLine[1]):\n self.removeIntExtLine()\n\n\n def removeIntExtLine(self):\n \"\"\"\n Elimina la linea per la ricerca di punti con modalità EXT_INT (intersezione su estensione)\n \"\"\"\n del self.__intExtLine[:] # svuoto la lista\n\n def getIntExtLine(self):\n return self.__intExtLine\n\n def removeIntExtArc(self):\n \"\"\"\n Elimina l'arco per la ricerca di punti con modalità EXT_INT (intersezione su estensione)\n \"\"\"\n del self.__intExtArc[:] # svuoto la lista\n\n def getIntExtArc(self):\n return self.__intExtArc\n \n def getIntExtPoint(self, geom, point, CRS = None):\n \"\"\"\n Cerca il punto di intersezione tra la geometria e una linea memorizzata in __intExtLine\n - __intExtLine é lista di 2 punti = linea, > 2 punti = arco\n - CRS = sistema di coordinate in cui é espressa geom (QgsCoordinateReferenceSystem)\n Ritorna una lista di punti QgsPoint\n \"\"\"\n result = []\n\n if geom is None:\n return result \n \n # se non é stato selezionato alcun arco o alcuna linea\n if len(self.__intExtArc) == 0 and len(self.__intExtLine) == 0:\n return result\n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = qad_utils.closestSegmentWithContext(point, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return result\n g = self.__transformGeomToSnapPointCRS(geom, CRS) # trasformo la geometria in coord dei punti di snap\n \n # verifico se ci sono archi\n arc = None\n arcList = QadArcList()\n if arcList.fromGeom(g) > 0:\n info = arcList.arcAt(afterVertex)\n if info is not None:\n arc = info[0]\n\n if arc is None:\n # verifico se ci sono cerchi\n circle = None\n circleList = QadCircleList()\n if circleList.fromGeom(g) > 0:\n info = circleList.circleAt(afterVertex)\n if info is not None:\n circle = info[0]\n\n if (arc is None) and (circle is None): # nessun arco e cerchio\n p1 = self.__transformPoint(g.vertexAt(afterVertex - 1), CRS, self.getSnapPointCRS()) # trasformo il punto\n p2 = self.__transformPoint(g.vertexAt(afterVertex), CRS, self.getSnapPointCRS()) # trasformo il punto\n \n if len(self.__intExtArc) > 0:\n circle1 = QadCircle()\n circle1.set(self.__intExtArc[0].center, self.__intExtArc[0].radius)\n \n if arc is not None: # intersezione tra arco ed arco \n circle2 = QadCircle()\n circle2.set(arc.center, arc.radius) \n intExtPoints = circle1.getIntersectionPointsWithCircle(circle2)\n elif circle is not None: # intersezione tra cerchio ed arco\n intExtPoints = circle1.getIntersectionPointsWithCircle(circle)\n else: # intersezione tra linea ed arco\n intExtPoints = circle1.getIntersectionPointsWithInfinityLine(p1, p2) \n else:\n if arc is not None: # intersezione tra arco e linea \n circle1 = QadCircle()\n circle1.set(arc.center, arc.radius)\n intExtPoints = circle1.getIntersectionPointsWithInfinityLine(self.__intExtLine[0], self.__intExtLine[1])\n elif circle is not None: # intersezione tra cerchio e linea\n intExtPoints = circle.getIntersectionPointsWithInfinityLine(self.__intExtLine[0], self.__intExtLine[1])\n else: # intersezione tra linea e linea\n intExtPoints = []\n intExtPoint = qad_utils.getIntersectionPointOn2InfinityLines(self.__intExtLine[0], \\\n self.__intExtLine[1], \\\n p1, p2)\n if intExtPoint is not None:\n intExtPoints.append(intExtPoint)\n \n for intExtPoint in intExtPoints:\n self.__appendUniquePoint(result, intExtPoint, CRS) # senza duplicazione \n\n return result\n\n\n #============================================================================\n # utiliy functions\n #============================================================================\n def __appendUniquePoint(self, pointList, point, CRS = None):\n \"\"\"\n Aggiunge un punto alla lista verificando che non sia già presente.\n Resituisce True se l'inserimento é avvenuto False se il punto c'era già.\n \"\"\"\n _point = self.__transformPoint(point, CRS, self.getSnapPointCRS()) # trasformo il punto\n return qad_utils.appendUniquePointToList(pointList, _point)\n\n\n def __layerToMapCoordinatesPointList(self, pointList, layer, mQgsMapRenderer):\n \"\"\"\n Trasforma una lista punti da coordinate layer a coordinate map.\n \"\"\"\n i = 0\n for point in pointList:\n pointList[i] = mQgsMapRenderer.layerToMapCoordinates(layer, point)\n i = i + 1\n\n \n def __layerToMapCoordinatesRect(self, rect, layer, mQgsMapRenderer):\n \"\"\"\n Trasforma un rettangolo da coordinate layer a coordinate map.\n \"\"\"\n point = QgsPoint()\n point.set(rect.xMinimum(), rect.yMinimum())\n point = mQgsMapRenderer.layerToMapCoordinates(layer, point)\n rect.setXMinimum(point.x())\n rect.setYMinimum(point.y())\n point.set(rect.xMaximum(), rect.yMaximum())\n rect.setXMaximum(point.x())\n rect.setYMaximum(point.y())\n return rect\n\n def __transformPoint(self, point, sourceCRS, destCRS):\n \"\"\"\n Trasforma un punto dal sistema di coordinate sorgente a quello di destinazione.\n sourceCRS e destCRS sono QgsCoordinateReferenceSystem\n \"\"\" \n if (sourceCRS is not None) and (destCRS is not None) and sourceCRS != destCRS: \n coordTransform = QgsCoordinateTransform(sourceCRS, destCRS) # trasformo le coord\n return coordTransform.transform(point)\n else:\n return point\n\n def __transformGeomToSnapPointCRS(self, geom, CRS = None):\n \"\"\"\n Trasformala geometria nel sistema di coordinate dei punti di snap\n CRS é QgsCoordinateReferenceSystem della geometria\n \"\"\"\n if geom is None:\n return None\n \n g = QgsGeometry(geom)\n if (CRS is not None) and (self.getSnapPointCRS() is not None) and CRS != self.getSnapPointCRS(): \n coordTransform = QgsCoordinateTransform(CRS, self.getSnapPointCRS()) # trasformo la geometria\n g.transform(coordTransform)\n return g\n \n def __getNearestPoints(self, point, SnapPoints, tolerance = 0):\n \"\"\"\n Ritorna una lista con il primo elemento che é il tipo di snap e \n il secondo elemento é il punto più vicino a point.\n SnapPoints é un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n \"\"\" \n result = dict() \n minDist = sys.float_info.max\n \n if tolerance == 0: # solo il punto più vicino\n for item in SnapPoints.items():\n # escludo NEA che tratto dopo\n if (item[0] != QadSnapTypeEnum.NEA) and (item[1] is not None):\n for pt in item[1]:\n dist = qad_utils.getDistance(point, pt)\n if dist < minDist:\n minDist = dist\n snapType = item[0]\n NearestPoint = pt\n\n # se il punto trovato é più distante di <__distToExcludeNea> allora considero anche\n # eventuali punti NEA\n if minDist > self.__distToExcludeNea: \n # se é stato selezionato lo snap di tipo NEA\n if QadSnapTypeEnum.NEA in SnapPoints.keys():\n items = SnapPoints[QadSnapTypeEnum.NEA]\n if (items is not None):\n for pt in items:\n dist = qad_utils.getDistance(point, pt)\n if dist < minDist:\n minDist = dist\n snapType = QadSnapTypeEnum.NEA\n NearestPoint = pt\n\n if minDist != sys.float_info.max: # trovato\n result[snapType] = [NearestPoint]\n\n else:\n nearest = self.__getNearestPoints(point, SnapPoints) # punto più vicino\n dummy = nearest.items()\n dummy = dummy[0]\n NearestPoint = dummy[1]\n \n for item in SnapPoints.items():\n NearestPoints = []\n for pt in item[1]:\n dist = qad_utils.getDistance(NearestPoint, pt)\n if dist <= tolerance:\n NearestPoints.append(pt)\n\n if len(NearestPoints) > 0:\n snapType = item[0] \n result[snapType] = NearestPoint\n \n return result\n\n def __delPoint(self, point, SnapPoints):\n \"\"\"\n Cancella dalla lista SnapPoints il punto point (se esiste) \n SnapPoints é un dizionario di liste di punti di snap\n suddivisi per tipi di snap (es. {END : [pt1 .. ptn] MID : [pt1 .. ptn]})\n \"\"\" \n for item in SnapPoints.items():\n i = 0\n for pt in item[1]: \n if pt == point:\n del item[1][i]\n i = i + 1\n\n def toggleLine(self, snapType, pt1, pt2, CRS = None):\n \"\"\"\n Aggiunge una linea per la ricerca di punti con modalità EXT p PAR\n se non ancora inserita in lista altrimenti la rimuove dalla lista\n pt1 e pt2 sono QgsPoint\n CRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n __pt1 = QgsPoint(0, 0)\n __pt2 = QgsPoint(0, 0)\n \n if snapType == QadSnapTypeEnum.EXT:\n lines = self.__extLines\n elif snapType == QadSnapTypeEnum.PAR:\n lines = self.__parLines\n else:\n return\n \n if CRS is not None:\n __pt1 = self.__transformPoint(pt1, CRS, self.getSnapPointCRS()) # trasformo il punto in coord layer\n __pt2 = self.__transformPoint(pt2, CRS, self.getSnapPointCRS()) # trasformo il punto in coord layer\n else:\n __pt1 = pt1\n __pt2 = pt2\n \n # verifico che non ci sia già\n exist = False\n for line in lines:\n if (__pt1 == line[0] or __pt1 == line[1]) and (__pt2 == line[0] or __pt2 == line[1]):\n exist = True\n if __pt1 != line[0]:\n invertPoints = True\n else:\n invertPoints = False\n break\n \n if exist == False:\n # se non esiste ancora la aggiungo\n line = [__pt1, __pt2]\n lines.append(line)\n else:\n # se esiste di già la rimuovo\n if invertPoints == True:\n line = [__pt2, __pt1]\n else:\n line = [__pt1, __pt2]\n lines.remove(line) \n \n def toggleArc(self, snapType, arc, CRS = None):\n \"\"\"\n Aggiunge una linea per la ricerca di punti con modalità EXT p PAR\n se non ancora inserita in lista altrimenti la rimuove dalla lista\n pt1 e pt2 sono QgsPoint\n CRS é QgsCoordinateReferenceSystem opzionale\n \"\"\"\n if snapType == QadSnapTypeEnum.EXT:\n arcs = self.__extArcs\n else:\n return\n\n _arc = QadArc(arc)\n _arc.transformFromCRSToCRS(CRS, self.getSnapPointCRS()) # trasformo l'arco in coord layer\n \n # verifico che non ci sia già\n exist = False\n i = 0\n for iArc in arcs:\n if _arc == iArc:\n # se esiste di già lo rimuovo\n del arcs[i] \n return\n i = i + 1\n \n # se non esiste ancora lo aggiungo\n arcs.append(_arc)\n \n\n #============================================================================\n # getPolarCoord\n #============================================================================\n def getPolarCoord(self, point, polarAng):\n result = []\n\n angle = qad_utils.getAngleBy2Pts(self.__startPoint, point)\n value = math.modf(angle / polarAng) # ritorna una lista -> (<parte decimale> <parte intera>)\n if value[0] >= 0.5: # prendo intervallo successivo\n angle = (value[1] + 1) * polarAng\n else:\n angle = value[1] * polarAng\n\n dist = qad_utils.getDistance(self.__startPoint, point)\n pt2 = qad_utils.getPolarPointByPtAngle(self.__startPoint, angle, dist)\n\n polarPt = qad_utils.getPerpendicularPointOnInfinityLine(self.__startPoint, pt2, point)\n if qad_utils.getDistance(polarPt, point) <= self.__toleranceExtParlines:\n self.__appendUniquePoint(result, polarPt) # senza duplicazione\n\n return result\n"
},
{
"alpha_fraction": 0.664686381816864,
"alphanum_fraction": 0.6694480776786804,
"avg_line_length": 41.48747634887695,
"blob_id": "e9f502ef0c46feffae74500796b042dedc607625",
"content_id": "c2933ba3a499f1910bc3bfc6187866e6295daa31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 44105,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 1038,
"path": "/qad_dimstyle_details_dlg.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire la dialog per DIMSTYLE\n \n -------------------\n begin : 2015-05-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\nfrom qgis.utils import *\nfrom qgis.gui import *\n\nimport qad_dimstyle_details_ui\n\nfrom qad_variables import *\nfrom qad_dim import *\nfrom qad_msg import QadMsg, qadShowPluginHelp\nimport qad_layer\nimport qad_utils\n\n\n#######################################################################################\n# Classe che gestisce l'interfaccia grafica della funzione di creazione nuovo stile\nclass QadDIMSTYLE_DETAILS_Dialog(QDialog, QObject, qad_dimstyle_details_ui.Ui_DimStyle_Details_Dialog):\n def __init__(self, plugIn, dimStyle):\n self.plugIn = plugIn\n self.dimStyle = QadDimStyle(dimStyle) # copio lo stile di quotatura\n self.iface = self.plugIn.iface.mainWindow()\n QDialog.__init__(self, self.iface)\n\n self.onInit = False # vero se si è in fase di inizializzazione\n \n self.setupUi(self)\n \n self.init_db_tab()\n self.init_lines_tab()\n self.init_symbols_tab()\n self.init_text_tab()\n self.init_adjust_tab()\n self.init_primaryUnits_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def closeEvent(self, event):\n del self.previewDim # cancello il canvans di preview della quota chiamato QadPreviewDim \n return QDialog.closeEvent(self, event)\n \n def setupUi(self, Dialog):\n qad_dimstyle_details_ui.Ui_DimStyle_Details_Dialog.setupUi(self, self)\n # aggiungo il bottone di qgis QgsColorButtonV2 chiamato dimLineColor \n # che eredita la posizione di dimLineColorDummy (che viene nascosto)\n self.dimLineColorDummy.setHidden(True)\n self.dimLineColor = QgsColorButtonV2(self.dimLineColorDummy.parent()) \n self.dimLineColor.setGeometry(self.dimLineColorDummy.geometry())\n self.dimLineColor.setObjectName(\"dimLineColor\")\n QObject.connect(self.dimLineColor, SIGNAL(\"colorChanged(QColor)\"), self.dimLineColorChanged)\n \n # aggiungo il bottone di qgis QgsColorButtonV2 chiamato extLineColor \n # che eredita la posizione di extLineColorDummy (che viene nascosto) \n self.extLineColorDummy.setHidden(True)\n self.extLineColor = QgsColorButtonV2(self.extLineColorDummy.parent()) \n self.extLineColor.setGeometry(self.extLineColorDummy.geometry())\n self.extLineColor.setObjectName(\"extLineColor\")\n QObject.connect(self.extLineColor, SIGNAL(\"colorChanged(QColor)\"), self.extLineColorChanged)\n \n # aggiungo il bottone di qgis QgsColorButtonV2 chiamato textColor \n # che eredita la posizione di textColorDummy (che viene nascosto) \n self.textColorDummy.setHidden(True)\n self.textColor = QgsColorButtonV2(self.textColorDummy.parent()) \n self.textColor.setGeometry(self.textColorDummy.geometry())\n self.textColor.setObjectName(\"textColor\")\n QObject.connect(self.textColor, SIGNAL(\"colorChanged(QColor)\"), self.textColorChanged)\n\n # aggiungo il canvans di preview della quota chiamato QadPreviewDim \n # che eredita la posizione di previewDummy (che viene nascosto) \n self.previewDummy.setHidden(True)\n self.previewDim = QadPreviewDim(self.previewDummy.parent(), self.plugIn)\n self.previewDim.setGeometry(self.previewDummy.geometry())\n self.previewDim.setObjectName(\"previewDim\")\n\n self.tabWidget.setCurrentIndex(0)\n\n def currentTabChanged(self, index):\n self.previewDim.setParent(self.tabWidget.widget(index))\n self.previewDim.show()\n \n\n ####################################################################\n # Inizializzazione del TAB che riguarda i campi di database - inizio\n ####################################################################\n\n def init_db_tab(self):\n self.onInit = True \n # layer linee\n for index, layer in enumerate(self.plugIn.iface.legendInterface().layers()): \n if (layer.type() == QgsMapLayer.VectorLayer) and layer.geometryType() == QGis.Line:\n self.linearLayerName.addItem(layer.name(), index) \n # seleziono un elemento della lista\n if self.dimStyle.linearLayerName is not None:\n index = self.linearLayerName.findText(self.dimStyle.linearLayerName)\n self.linearLayerName.setCurrentIndex(index)\n self.linearLayerNameChanged(index)\n \n # layer simboli\n for index, layer in enumerate(self.plugIn.iface.legendInterface().layers()): \n if qad_layer.isSymbolLayer(layer):\n self.symbolLayerName.addItem(layer.name(), index)\n # seleziono un elemento della lista\n if self.dimStyle.symbolLayerName is not None:\n index = self.symbolLayerName.findText(self.dimStyle.symbolLayerName)\n self.symbolLayerName.setCurrentIndex(index)\n self.symbolLayerNameChanged(index)\n \n # layer testi\n for index, layer in enumerate(self.plugIn.iface.legendInterface().layers()): \n if qad_layer.isTextLayer(layer):\n self.textualLayerName.addItem(layer.name(), index)\n # seleziono un elemento della lista\n if self.dimStyle.textualLayerName is not None:\n index = self.textualLayerName.findText(self.dimStyle.textualLayerName)\n self.textualLayerName.setCurrentIndex(index)\n self.textualLayerNameChanged(index)\n self.onInit = False \n\n def accept_db_tab(self): \n # layer linee\n self.dimStyle.linearLayerName = self.linearLayerName.currentText()\n self.dimStyle.lineTypeFieldName = self.lineTypeFieldName.currentText()\n \n # layer simboli\n self.dimStyle.symbolLayerName = self.symbolLayerName.currentText()\n self.dimStyle.symbolFieldName = self.symbolFieldName.currentText() \n self.dimStyle.scaleFieldName = self.scaleFieldName.currentText()\n\n self.dimStyle.colorFieldName = self.colorFieldName.currentText()\n self.dimStyle.rotFieldName = self.rotFieldName.currentText()\n self.dimStyle.componentFieldName = self.componentFieldName.currentText()\n self.dimStyle.idParentFieldName = self.idParentFieldName.currentText()\n \n # layer testi\n self.dimStyle.textualLayerName = self.textualLayerName.currentText()\n self.dimStyle.idFieldName = self.idFieldName.currentText()\n self.dimStyle.dimStyleFieldName = self.dimStyleFieldName.currentText()\n self.dimStyle.dimTypeFieldName = self.dimTypeFieldName.currentText()\n\n def redrawDimOnDBTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_db_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def colorFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def componentFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def dimStyleFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def dimTypeFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def idFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def idParentFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def linetypeFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def linearLayerNameChanged(self, index):\n if index == -1:\n return\n # leggo l'elemento selezionato\n legendIndex = self.linearLayerName.itemData(index)\n layer = iface.legendInterface().layers()[legendIndex]\n if layer is not None:\n self.lineTypeFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.lineTypeFieldName.addItem(\"\")\n\n for field in layer.pendingFields():\n if field.type() == QVariant.String:\n self.lineTypeFieldName.addItem(field.name(), field)\n\n # seleziono un elemento della lista\n if self.dimStyle.lineTypeFieldName is not None:\n index = self.lineTypeFieldName.findText(self.dimStyle.lineTypeFieldName)\n self.lineTypeFieldName.setCurrentIndex(index)\n self.redrawDimOnDBTabChanged()\n\n def rotFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def scaleFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def symbolFieldNameChanged(self, index):\n self.redrawDimOnDBTabChanged()\n\n def symbolLayerNameChanged(self, index):\n if index == -1:\n return\n # leggo l'elemento selezionato\n legendIndex = self.symbolLayerName.itemData(index)\n layer = iface.legendInterface().layers()[legendIndex]\n if layer is not None:\n self.symbolFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.symbolFieldName.addItem(\"\")\n self.scaleFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.scaleFieldName.addItem(\"\")\n\n self.rotFieldName.clear() # remove all items\n self.componentFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.componentFieldName.addItem(\"\")\n self.idParentFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.idParentFieldName.addItem(\"\")\n \n for field in layer.pendingFields():\n if field.type() == QVariant.String:\n self.symbolFieldName.addItem(field.name(), field) \n self.componentFieldName.addItem(field.name(), field)\n elif qad_utils.isNumericField(field):\n self.scaleFieldName.addItem(field.name(), field)\n self.rotFieldName.addItem(field.name(), field)\n self.idParentFieldName.addItem(field.name(), field)\n \n # seleziono un elemento della lista\n if self.dimStyle.symbolFieldName is not None:\n index = self.symbolFieldName.findText(self.dimStyle.symbolFieldName)\n self.symbolFieldName.setCurrentIndex(index)\n if self.dimStyle.scaleFieldName is not None:\n index = self.scaleFieldName.findText(self.dimStyle.scaleFieldName)\n self.scaleFieldName.setCurrentIndex(index)\n \n if self.dimStyle.rotFieldName is not None:\n index = self.rotFieldName.findText(self.dimStyle.rotFieldName)\n self.rotFieldName.setCurrentIndex(index)\n if self.dimStyle.componentFieldName is not None:\n index = self.componentFieldName.findText(self.dimStyle.componentFieldName)\n self.componentFieldName.setCurrentIndex(index)\n if self.dimStyle.idParentFieldName is not None:\n index = self.idParentFieldName.findText(self.dimStyle.idParentFieldName)\n self.idParentFieldName.setCurrentIndex(index)\n self.redrawDimOnDBTabChanged()\n\n def textualLayerNameChanged(self, index):\n if index == -1:\n return\n # leggo l'elemento selezionato\n legendIndex = self.textualLayerName.itemData(index)\n layer = iface.legendInterface().layers()[legendIndex]\n if layer is not None:\n self.idFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.idFieldName.addItem(\"\")\n self.dimStyleFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.dimStyleFieldName.addItem(\"\")\n self.dimTypeFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.dimTypeFieldName.addItem(\"\")\n self.colorFieldName.clear() # remove all items and add an empty row (optional parameter)\n self.colorFieldName.addItem(\"\")\n \n for field in layer.pendingFields():\n if field.type() == QVariant.String:\n self.dimStyleFieldName.addItem(field.name(), field)\n self.dimTypeFieldName.addItem(field.name(), field)\n self.colorFieldName.addItem(field.name(), field)\n elif qad_utils.isNumericField(field):\n self.idFieldName.addItem(field.name(), field)\n\n # seleziono un elemento della lista\n if self.dimStyle.idFieldName is not None:\n index = self.idFieldName.findText(self.dimStyle.idFieldName)\n self.idFieldName.setCurrentIndex(index)\n if self.dimStyle.dimStyleFieldName is not None:\n index = self.dimStyleFieldName.findText(self.dimStyle.dimStyleFieldName)\n self.dimStyleFieldName.setCurrentIndex(index)\n if self.dimStyle.dimTypeFieldName is not None:\n index = self.dimTypeFieldName.findText(self.dimStyle.dimTypeFieldName)\n self.dimTypeFieldName.setCurrentIndex(index)\n if self.dimStyle.colorFieldName is not None:\n index = self.colorFieldName.findText(self.dimStyle.colorFieldName)\n self.colorFieldName.setCurrentIndex(index)\n self.redrawDimOnDBTabChanged()\n\n\n ####################################################################\n # Inizializzazione del TAB che riguarda i campi di database - fine\n # Inizializzazione del TAB che riguarda le linee di quotatura - inizio\n ####################################################################\n \n def init_lines_tab(self):\n self.onInit = True \n self.dimLineColor.setColor(QColor(self.dimStyle.dimLineColor))\n self.dimLineLineType.setText(self.dimStyle.dimLineLineType)\n self.dimLine1Hide.setChecked(not self.dimStyle.dimLine1Show)\n self.dimLine2Hide.setChecked(not self.dimStyle.dimLine2Show)\n \n self.extLineColor.setColor(QColor(self.dimStyle.extLineColor))\n self.extLine1LineType.setText(self.dimStyle.extLine1LineType)\n self.extLine2LineType.setText(self.dimStyle.extLine2LineType)\n self.extLine1Hide.setChecked(not self.dimStyle.extLine1Show)\n self.extLine2Hide.setChecked(not self.dimStyle.extLine2Show)\n self.extLineOffsetDimLine.setValue(self.dimStyle.extLineOffsetDimLine)\n self.extLineOffsetOrigPoints.setValue(self.dimStyle.extLineOffsetOrigPoints)\n self.extLineIsFixedLen.setChecked(self.dimStyle.extLineIsFixedLen)\n self.extLineFixedLen.setValue(self.dimStyle.extLineFixedLen)\n self.extLineIsFixedLenToggled(self.dimStyle.extLineIsFixedLen)\n self.onInit = False \n\n def accept_lines_tab(self): \n self.dimStyle.dimLineColor = self.dimLineColor.color().name()\n self.dimStyle.dimLineLineType = self.dimLineLineType.text()\n self.dimStyle.dimLine1Show = not self.dimLine1Hide.isChecked()\n self.dimStyle.dimLine2Show = not self.dimLine2Hide.isChecked()\n\n self.dimStyle.extLineColor = self.extLineColor.color().name()\n self.dimStyle.extLine1LineType = self.extLine1LineType.text()\n self.dimStyle.extLine2LineType = self.extLine2LineType.text()\n self.dimStyle.extLine1Show = not self.extLine1Hide.isChecked()\n self.dimStyle.extLine2Show = not self.extLine2Hide.isChecked()\n self.dimStyle.extLineOffsetDimLine = self.extLineOffsetDimLine.value()\n self.dimStyle.extLineOffsetOrigPoints = self.extLineOffsetOrigPoints.value()\n self.dimStyle.extLineIsFixedLen = self.extLineIsFixedLen.isChecked()\n self.dimStyle.extLineFixedLen = self.extLineFixedLen.value()\n\n def redrawDimOnLinesTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_lines_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def dimLine1HideToggled(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def dimLine2HideToggled(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def dimLineColorChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def dimLineLineTypeChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLineColorChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLineFixedLenChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLineIsFixedLenToggled(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLineOffsetDimLineChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLineOffsetOrigPointsChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLine1HideToggled(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLine1LineTypeChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLine2HideToggled(self, value):\n self.redrawDimOnLinesTabChanged()\n\n def extLine2LineTypeChanged(self, value):\n self.redrawDimOnLinesTabChanged()\n \n def extLineIsFixedLenToggled(self, value):\n self.extLineFixedLen.setEnabled(value)\n self.redrawDimOnLinesTabChanged()\n\n\n ####################################################################\n # Inizializzazione del TAB che riguarda le linee di quotatura - fine\n # Inizializzazione del TAB che riguarda i simboli di quotatura - inizio\n ####################################################################\n \n def init_symbols_tab(self):\n self.onInit = True \n self.block1Name.setText(self.dimStyle.block1Name)\n self.block2Name.setText(self.dimStyle.block2Name)\n self.blockLeaderName.setText(self.dimStyle.blockLeaderName)\n self.blockWidth.setValue(self.dimStyle.blockWidth)\n self.blockScale.setValue(self.dimStyle.blockScale)\n self.onInit = False \n\n def accept_symbols_tab(self):\n self.dimStyle.block1Name = self.block1Name.text()\n self.dimStyle.block2Name = self.block2Name.text()\n self.dimStyle.blockLeaderName = self.blockLeaderName.text()\n self.dimStyle.blockWidth = self.blockWidth.value() \n self.dimStyle.blockScale = self.blockScale.value() \n\n def redrawDimOnSymbolsTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_symbols_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def block1NameChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n def block2NameChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n def blockLeaderNameChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n def blockScaleNameChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n def blockWidthChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n def blockScaleChanged(self, value):\n self.redrawDimOnSymbolsTabChanged()\n\n \n ####################################################################\n # Inizializzazione del TAB che riguarda i simboli di quotatura - fine\n # Inizializzazione del TAB che riguarda i testi di quotatura - inizio\n ####################################################################\n\n def init_text_tab(self):\n self.onInit = True \n index = self.textFont.findText(self.dimStyle.textFont)\n self.textFont.setCurrentIndex(index)\n self.textColor.setColor(QColor(self.dimStyle.textColor))\n self.textHeight.setValue(self.dimStyle.textHeight)\n \n # textVerticalPos\n self.textVerticalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Centered\"))\n self.textVerticalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Above\"))\n self.textVerticalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Outside\"))\n self.textVerticalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Below\"))\n if self.dimStyle.textVerticalPos == QadDimStyleTxtVerticalPosEnum.CENTERED_LINE:\n self.textVerticalPos.setCurrentIndex(0)\n elif self.dimStyle.textVerticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE:\n self.textVerticalPos.setCurrentIndex(1)\n elif self.dimStyle.textVerticalPos == QadDimStyleTxtVerticalPosEnum.EXTERN_LINE:\n self.textVerticalPos.setCurrentIndex(2)\n elif self.dimStyle.textVerticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE:\n self.textVerticalPos.setCurrentIndex(3)\n \n # textHorizontalPos\n self.textHorizontalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Centered\"))\n self.textHorizontalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"At Ext Line 1\"))\n self.textHorizontalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"At Ext Line 2\"))\n self.textHorizontalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Over Ext Line 1\"))\n self.textHorizontalPos.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Over Ext Line 2\"))\n if self.dimStyle.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE:\n self.textHorizontalPos.setCurrentIndex(0)\n elif self.dimStyle.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE:\n self.textHorizontalPos.setCurrentIndex(1)\n elif self.dimStyle.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE:\n self.textHorizontalPos.setCurrentIndex(2) \n elif self.dimStyle.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE_UP:\n self.textHorizontalPos.setCurrentIndex(3) \n elif self.dimStyle.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE_UP:\n self.textHorizontalPos.setCurrentIndex(4) \n \n # textDirection\n self.textDirection.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Left-to-Right\"))\n self.textDirection.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"Right-to-Left\"))\n if self.dimStyle.textDirection == QadDimStyleTxtDirectionEnum.SX_TO_DX:\n self.textDirection.setCurrentIndex(0)\n elif self.dimStyle.textDirection == QadDimStyleTxtDirectionEnum.DX_TO_SX:\n self.textDirection.setCurrentIndex(1)\n \n self.textOffsetDist.setValue(self.dimStyle.textOffsetDist)\n \n # textForcedRot\n if self.dimStyle.textRotMode == QadDimStyleTxtRotModeEnum.HORIZONTAL:\n self.textRotModeHorizontal.setChecked(True) \n elif self.dimStyle.textRotMode == QadDimStyleTxtRotModeEnum.ALIGNED_LINE:\n self.textRotModeAligned.setChecked(True)\n elif self.dimStyle.textRotMode == QadDimStyleTxtRotModeEnum.ISO:\n self.textRotModeISO.setChecked(True)\n elif self.dimStyle.textRotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION:\n self.textRotModeFixedRot.setChecked(True)\n \n self.textForcedRot.setValue(self.dimStyle.textForcedRot)\n self.textRotModeFixedRotToggled(self.textRotModeFixedRot.isChecked())\n self.onInit = False \n\n def accept_text_tab(self):\n self.dimStyle.textFont = self.textFont.currentText()\n self.dimStyle.textColor = self.textColor.color().name()\n self.dimStyle.textHeight = self.textHeight.value()\n \n # textVerticalPos\n if self.textVerticalPos.currentIndex() == 0:\n self.dimStyle.textVerticalPos = QadDimStyleTxtVerticalPosEnum.CENTERED_LINE\n elif self.textVerticalPos.currentIndex() == 1:\n self.dimStyle.textVerticalPos = QadDimStyleTxtVerticalPosEnum.ABOVE_LINE\n elif self.textVerticalPos.currentIndex() == 2:\n self.dimStyle.textVerticalPos = QadDimStyleTxtVerticalPosEnum.EXTERN_LINE\n elif self.textVerticalPos.currentIndex() == 3:\n self.dimStyle.textVerticalPos = QadDimStyleTxtVerticalPosEnum.BELOW_LINE\n \n # textHorizontalPos\n if self.textHorizontalPos.currentIndex() == 0:\n self.dimStyle.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE\n elif self.textHorizontalPos.currentIndex() == 1:\n self.dimStyle.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE\n elif self.textHorizontalPos.currentIndex() == 2:\n self.dimStyle.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE\n elif self.textHorizontalPos.currentIndex() == 3:\n self.dimStyle.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE_UP\n elif self.textHorizontalPos.currentIndex() == 4:\n self.dimStyle.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE_UP\n \n # textDirection\n if self.textDirection.currentIndex() == 0:\n self.dimStyle.textDirection = QadDimStyleTxtDirectionEnum.SX_TO_DX\n elif self.textDirection.currentIndex() == 1:\n self.dimStyle.textDirection = QadDimStyleTxtDirectionEnum.DX_TO_SX\n \n self.dimStyle.textOffsetDist = self.textOffsetDist.value()\n \n # textForcedRot\n if self.textRotModeHorizontal.isChecked():\n self.dimStyle.textRotMode = QadDimStyleTxtRotModeEnum.HORIZONTAL\n elif self.textRotModeAligned.isChecked():\n self.dimStyle.textRotMode = QadDimStyleTxtRotModeEnum.ALIGNED_LINE\n elif self.textRotModeISO.isChecked():\n self.dimStyle.textRotMode = QadDimStyleTxtRotModeEnum.ISO\n elif self.textRotModeFixedRot.isChecked():\n self.dimStyle.textRotMode = QadDimStyleTxtRotModeEnum.FORCED_ROTATION\n \n self.dimStyle.textForcedRot = self.textForcedRot.value()\n\n def redrawDimOnTextTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_text_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n\n def textColorChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textDirectionChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textFontChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textForcedRotChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textHeightChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textHorizontalPosChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textOffsetDistChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textRotModeHorizontalToggled(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textRotModeAlignedToggled(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textRotModeISOToggled(self, value):\n self.redrawDimOnTextTabChanged()\n\n def textRotModeFixedRotToggled(self, value):\n self.textForcedRot.setEnabled(value)\n self.redrawDimOnTextTabChanged()\n\n def textVerticalPosChanged(self, value):\n self.redrawDimOnTextTabChanged()\n\n\n ####################################################################\n # Inizializzazione del TAB che riguarda i testi di quotatura - fine\n # Inizializzazione del TAB che riguarda l'adattamento dei componenti di quotatura - inizio\n ####################################################################\n\n def init_adjust_tab(self):\n self.onInit = True \n # self.textAdjustAlwaysInside in futuro\n \n if self.dimStyle.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.WHICHEVER_FITS_BEST: \n self.textBlockAdjustWhicheverFitsBestOutside.setChecked(True)\n elif self.dimStyle.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.FIRST_BLOCKS_THEN_TEXT: \n self.textBlockAdjustFirstSymbolOutside.setChecked(True)\n elif self.dimStyle.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.FIRST_TEXT_THEN_BLOCKS: \n self.textBlockAdjustFirstTextOutside.setChecked(True)\n elif self.dimStyle.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.BOTH_OUTSIDE_EXT_LINES: \n self.textBlockAdjustBothtOutside.setChecked(True)\n\n self.blockSuppressionForNoSpace.setChecked(self.dimStyle.blockSuppressionForNoSpace)\n self.onInit = False \n\n def accept_adjust_tab(self):\n if self.textBlockAdjustWhicheverFitsBestOutside.isChecked():\n self.dimStyle.textBlockAdjust = QadDimStyleTextBlocksAdjustEnum.WHICHEVER_FITS_BEST\n elif self.textBlockAdjustFirstSymbolOutside.isChecked():\n self.dimStyle.textBlockAdjust = QadDimStyleTextBlocksAdjustEnum.FIRST_BLOCKS_THEN_TEXT\n elif self.textBlockAdjustFirstTextOutside.isChecked():\n self.dimStyle.textBlockAdjust = QadDimStyleTextBlocksAdjustEnum.FIRST_TEXT_THEN_BLOCKS\n elif self.textBlockAdjustBothOutside.isChecked():\n self.dimStyle.textBlockAdjust = QadDimStyleTextBlocksAdjustEnum.BOTH_OUTSIDE_EXT_LINES\n\n self.dimStyle.blockSuppressionForNoSpace = self.blockSuppressionForNoSpace.isChecked()\n\n def redrawDimOnAdjustTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_adjust_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def blockSuppressionForNoSpaceToggled(self, value):\n self.redrawDimOnAdjustTabChanged()\n \n def textBlockAdjustWhicheverFitsBestOutsideToggled(self, value):\n self.redrawDimOnAdjustTabChanged()\n\n def textBlockAdjustFirstSymbolOutsideToggled(self, value):\n self.redrawDimOnAdjustTabChanged()\n\n def textBlockAdjustFirstTextOutsideToggled(self, value):\n self.redrawDimOnAdjustTabChanged()\n\n def textBlockAdjustBothOutsideToggled(self, value):\n self.redrawDimOnAdjustTabChanged()\n\n\n ####################################################################\n # Inizializzazione del TAB che riguarda l'adattamento dei componenti di quotatura - fine\n # Inizializzazione del TAB che riguarda le unità primarie di quotatura - inizio\n ####################################################################\n\n def init_primaryUnits_tab(self):\n self.onInit = True \n # textDecimals\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.0\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.00\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.000\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.0000\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.00000\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.000000\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.0000000\"))\n self.textDecimals.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"0.00000000\"))\n self.textDecimals.setCurrentIndex(self.dimStyle.textDecimals)\n \n # textDecimalSep\n self.textDecimalSep.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"'.' Period\"))\n self.textDecimalSep.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"',' Comma\"))\n self.textDecimalSep.addItem(QadMsg.translate(\"DimStyle_Details_Dialog\", \"' ' Space\"))\n if self.dimStyle.textDecimalSep == \".\": # punto\n self.textDecimalSep.setCurrentIndex(0)\n elif self.dimStyle.textDecimalSep == \",\": # virgola\n self.textDecimalSep.setCurrentIndex(1)\n elif self.dimStyle.textDecimalSep == \" \": # spazio\n self.textDecimalSep.setCurrentIndex(2)\n \n self.textPrefix.setText(self.dimStyle.textPrefix)\n self.textSuffix.setText(self.dimStyle.textSuffix)\n \n self.textSuppressLeadingZeros.setChecked(self.dimStyle.textSuppressLeadingZeros)\n self.textDecimalZerosSuppression.setChecked(self.dimStyle.textDecimalZerosSuppression)\n self.onInit = False \n\n def accept_primaryUnits_tab(self):\n # textDecimals\n self.dimStyle.textDecimals = self.textDecimals.currentIndex()\n \n # textDecimalSep\n if self.textDecimalSep.currentIndex() == 0: # punto\n self.dimStyle.textDecimalSep = \".\"\n elif self.textDecimalSep.currentIndex() == 1: # virgola \n self.dimStyle.textDecimalSep = \",\"\n elif self.textDecimalSep.currentIndex() == 2: # spazio \n self.dimStyle.textDecimalSep = \" \"\n \n self.dimStyle.textPrefix = self.textPrefix.text()\n self.dimStyle.textSuffix = self.textSuffix.text() \n \n self.dimStyle.textSuppressLeadingZeros = self.textSuppressLeadingZeros.isChecked()\n self.dimStyle.textDecimalZerosSuppression = self.textDecimalZerosSuppression.isChecked()\n\n def redrawDimOnPrimaryUnitsTabChanged(self):\n if self.onInit == True: # esco se sono in fase di inizializzazione\n return \n self.accept_primaryUnits_tab()\n self.previewDim.drawDim(self.dimStyle)\n\n def textDecimalsChanged(self, index):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n def textDecimalSepChanged(self, index):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n def textDecimalZerosSuppressionToggled(self, value):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n def textPrefixChanged(self, value):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n def textSuffixChanged(self, value):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n def textSuppressLeadingZerosToggled(self, value):\n self.redrawDimOnPrimaryUnitsTabChanged()\n\n\n ####################################################################\n # Inizializzazione del TAB che riguarda le unità primarie di quotatura - fine\n ####################################################################\n\n def ButtonHELP_Pressed(self):\n qadShowPluginHelp(QadMsg.translate(\"Help\", \"Dimensioning\"))\n\n def accept(self):\n self.accept_db_tab()\n self.accept_lines_tab()\n self.accept_symbols_tab()\n self.accept_text_tab()\n self.accept_adjust_tab()\n self.accept_primaryUnits_tab()\n errMsg = self.dimStyle.getInValidErrMsg()\n if errMsg is not None:\n errMsg += QadMsg.translate(\"DimStyle_Details_Dialog\", \"\\nDo you want to accepts these settings ?\")\n res = QMessageBox.question(self, QadMsg.translate(\"QAD\", \"QAD\"), errMsg, \\\n QMessageBox.Yes | QMessageBox.No)\n if res == QMessageBox.No:\n return\n QDialog.accept(self)\n \n \n#######################################################################################\n# Classe che gestisce il widget per visualizzare il preview della quota\nclass QadPreviewDim(QgsMapCanvas):\n\n def __init__(self, parent, plugIn):\n QgsMapCanvas.__init__(self, parent)\n self.plugIn = plugIn\n self.setAttribute(Qt.WA_DeleteOnClose)\n\n self.iface = self.plugIn.iface\n self.layerId2canvasLayer = {}\n self.canvasLayers = []\n\n self.setupUi()\n self.bookmark = False\n self.dimStyle = None\n \n\n def __del__(self):\n self.eraseDim()\n\n \n def setupUi(self):\n self.setObjectName(\"QadPreviewCanvas\")\n\n settings = QSettings()\n red = settings.value(\"/qgis/default_canvas_color_red\", 255, type=int)\n green = settings.value(\"/qgis/default_canvas_color_green\", 255, type=int)\n blue = settings.value(\"/qgis/default_canvas_color_blue\", 255, type=int)\n self.setCanvasColor(QColor(red, green, blue))\n self.enableAntiAliasing( settings.value( \"/qgis/enable_anti_aliasing\", False, type=bool ))\n self.useImageToRender( settings.value( \"/qgis/use_qimage_to_render\", False, type=bool ))\n action = settings.value( \"/qgis/wheel_action\", 0, type=int)\n zoomFactor = settings.value( \"/qgis/zoom_factor\", 2.0, type=float )\n self.setWheelAction( QgsMapCanvas.WheelAction(action), zoomFactor )\n\n self.onExtentsChanged()\n self.onCrsChanged()\n self.onCrsTransformEnabled( self.iface.mapCanvas().hasCrsTransformEnabled() )\n\n def onExtentsChanged(self):\n prevFlag = self.renderFlag()\n self.setRenderFlag(False)\n\n self.setExtent(self.iface.mapCanvas().extent())\n \n self.setRenderFlag( prevFlag )\n\n def onCrsChanged(self):\n prevFlag = self.renderFlag()\n self.setRenderFlag( False )\n\n renderer = self.iface.mapCanvas().mapRenderer()\n self._setRendererCrs( self.mapRenderer(), self._rendererCrs(renderer) )\n self.mapRenderer().setMapUnits( renderer.mapUnits() )\n\n self.setRenderFlag( prevFlag )\n\n def onCrsTransformEnabled(self, enabled):\n prevFlag = self.renderFlag()\n self.setRenderFlag( False )\n\n self.mapRenderer().setProjectionsEnabled( enabled )\n\n self.setRenderFlag( prevFlag )\n\n\n def getLayerSet(self):\n return map(lambda x: self._layerId(x.layer()), self.canvasLayers)\n\n def setLayerSet(self, layerIds=None):\n prevFlag = self.renderFlag()\n self.setRenderFlag( False )\n\n if layerIds == None:\n self.layerId2canvasLayer = {}\n self.canvasLayers = []\n QgsMapCanvas.setLayerSet(self, [])\n\n else:\n for lid in layerIds:\n self.addLayer( lid )\n\n self.onExtentsChanged()\n self.setRenderFlag( prevFlag )\n\n\n def addLayer(self, layerId=None):\n if layerId == None:\n layer = self.iface.activeLayer()\n else:\n layer = QgsMapLayerRegistry.instance().mapLayer( layerId )\n\n if layer == None:\n return\n\n prevFlag = self.renderFlag()\n self.setRenderFlag( False )\n \n # add the layer to the map canvas layer set\n self.canvasLayers = []\n id2cl_dict = {}\n for l in self.iface.legendInterface().layers():\n lid = self._layerId(l)\n if self.layerId2canvasLayer.has_key( lid ): # previously added\n cl = self.layerId2canvasLayer[ lid ]\n elif l == layer: # selected layer\n cl = QgsMapCanvasLayer( layer )\n else:\n continue\n\n id2cl_dict[ lid ] = cl\n self.canvasLayers.append( cl )\n\n self.layerId2canvasLayer = id2cl_dict\n QgsMapCanvas.setLayerSet(self, self.canvasLayers )\n\n self.onExtentsChanged()\n self.setRenderFlag( prevFlag )\n\n def delLayer(self, layerId=None):\n if layerId == None:\n layer = self.iface.activeLayer()\n if layer == None:\n return\n layerId = self._layerId(layer)\n\n # remove the layer from the map canvas layer set\n if not self.layerId2canvasLayer.has_key( layerId ):\n return\n\n prevFlag = self.renderFlag()\n self.setRenderFlag( False )\n\n cl = self.layerId2canvasLayer[ layerId ]\n del self.layerId2canvasLayer[ layerId ]\n self.canvasLayers.remove( cl )\n QgsMapCanvas.setLayerSet(self, self.canvasLayers )\n del cl\n\n self.onExtentsChanged()\n self.setRenderFlag( prevFlag )\n\n\n def _layerId(self, layer):\n if hasattr(layer, 'id'):\n return layer.id()\n return layer.getLayerID() \n\n def _rendererCrs(self, renderer):\n if hasattr(renderer, 'destinationCrs'):\n return renderer.destinationCrs()\n return renderer.destinationSrs()\n\n def _setRendererCrs(self, renderer, crs):\n if hasattr(renderer, 'setDestinationCrs'):\n return renderer.setDestinationCrs( crs )\n return renderer.setDestinationSrs( crs )\n\n def zoomOnRect(self, zoomRect):\n mapSettings = self.mapSettings()\n canvasSize = mapSettings.outputSize()\n sfx = zoomRect.width() / canvasSize.width()\n sfy = zoomRect.height() / canvasSize.height()\n sf = max(sfx, sfy)\n\n prevFlag = self.renderFlag()\n self.setRenderFlag(False)\n\n self.setExtent(zoomRect)\n self.setCenter(zoomRect.center())\n\n self.setRenderFlag( prevFlag )\n \n def drawDim(self, dimStyle):\n if dimStyle is None:\n return\n\n self.dimStyle = dimStyle\n self.eraseDim()\n \n if self.plugIn.insertBookmark() == True:\n self.bookmark = True\n\n for layerId in self.getLayerSet(): # tolgo tutti i layer\n self.delLayer(layerId)\n # inserisco i layer della quotatura\n self.isEditableTextualLayer = None\n layer = self.dimStyle.getTextualLayer()\n if layer is not None:\n self.isEditableTextualLayer = layer.isEditable()\n if self.isEditableTextualLayer == False:\n layer.startEditing()\n self.addLayer(layer.id())\n \n self.isEditableSymbolLayer = None\n layer = self.dimStyle.getSymbolLayer()\n if layer is not None:\n self.isEditableSymbolLayer = layer.isEditable()\n if self.isEditableSymbolLayer == False:\n layer.startEditing()\n self.addLayer(layer.id())\n \n self.isEditableLinearLayer = None\n layer = self.dimStyle.getLinearLayer()\n if layer is not None:\n self.isEditableLinearLayer = layer.isEditable()\n if self.isEditableLinearLayer == False:\n layer.startEditing()\n self.addLayer(layer.id())\n\n if self.dimStyle.getInValidErrMsg() is not None:\n return\n\n\n ###########################\n # quota lineare orizzontale\n dimPt1 = QgsPoint(0, 0)\n dimPt2 = QgsPoint(13.45, 0)\n linePosPt = QgsPoint(0, 10)\n \n # calcolo il rettangolo di occupazione della quota\n dimEntity, textOffsetRectGeom = self.dimStyle.getLinearDimFeatures(self.plugIn.canvas, \\\n dimPt1, dimPt2, linePosPt)\n rect = textOffsetRectGeom.boundingBox()\n for g in dimEntity.getLinearGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n for g in dimEntity.getSymbolGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n \n self.dimStyle.addLinearDimToLayers(self.plugIn, dimPt1, dimPt2, linePosPt)\n \n ###########################\n # quota lineare verticale\n dimPt1 = QgsPoint(0, 0)\n dimPt2 = QgsPoint(0, -15.7)\n linePosPt = QgsPoint(-9, 0)\n \n # calcolo il rettangolo di occupazione della quota\n dimEntity, textOffsetRectGeom = self.dimStyle.getLinearDimFeatures(self.plugIn.canvas, \\\n dimPt1, dimPt2, linePosPt, None, \\\n QadDimStyleAlignmentEnum.VERTICAL)\n rect.combineExtentWith(textOffsetRectGeom.boundingBox())\n for g in dimEntity.getLinearGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n for g in dimEntity.getSymbolGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n \n self.dimStyle.addLinearDimToLayers(self.plugIn, dimPt1, dimPt2, linePosPt, None, \\\n QadDimStyleAlignmentEnum.VERTICAL)\n\n ###########################\n # quota allineata obliqua\n dimPt1 = QgsPoint(13.45, 0)\n dimPt2 = QgsPoint(23, -20)\n linePosPt = QgsPoint(23, 0)\n \n # calcolo il rettangolo di occupazione della quota\n dimEntity, textOffsetRectGeom = self.dimStyle.getAlignedDimFeatures(self.plugIn.canvas, \\\n dimPt1, dimPt2, linePosPt)\n rect.combineExtentWith(textOffsetRectGeom.boundingBox())\n for g in dimEntity.getLinearGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n for g in dimEntity.getSymbolGeometryCollection():\n rect.combineExtentWith(g.boundingBox())\n \n self.dimStyle.addAlignedDimToLayers(self.plugIn, dimPt1, dimPt2, linePosPt, None)\n\n self.zoomOnRect(rect)\n\n def eraseDim(self):\n if self.bookmark == True:\n self.plugIn.undoUntilBookmark()\n self.bookmark = False\n \n for layerId in self.getLayerSet(): # tolgo tutti i layer\n self.delLayer(layerId)\n"
},
{
"alpha_fraction": 0.5189605355262756,
"alphanum_fraction": 0.5286245346069336,
"avg_line_length": 67.52444458007812,
"blob_id": "e837c118a40dc2a79329bd3337a762f1fdf5edc2",
"content_id": "836903d6ea4a41e142455467f8624c07f5935c6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 46267,
"license_type": "no_license",
"max_line_length": 291,
"num_lines": 675,
"path": "/qad_variables.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire le variabili di ambiente\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nimport os.path\nfrom qgis.core import *\n\n\nimport qad_utils\nfrom qad_msg import QadMsg\n\n\n#===============================================================================\n# Qad variable class.\n#===============================================================================\nclass QadVariableTypeEnum():\n UNKNOWN = 0 # sconosciuto (non gestito da QAD)\n STRING = 1 # caratteri\n COLOR = 2 # colore espresso in caratteri (es. rosso = \"#FF0000\")\n INT = 3 # numero intero\n FLOAT = 4 # nmer con decimali\n BOOL = 5 # booleano (True o False)\n\n\n#===============================================================================\n# Qad variable class.\n#===============================================================================\nclass QadVariable():\n \"\"\"\n Classe che gestisce le variabili di ambiente di Qad\n \"\"\"\n\n def __init__(self, name, value, typeValue, minNum = None, maxNum = None, descr = \"\"):\n self.name = name\n self.value = value\n self.typeValue = typeValue\n self.default = value\n self.minNum = minNum\n self.maxNum = maxNum\n self.descr = descr\n\n\n#===============================================================================\n# Qad variables class.\n#===============================================================================\nclass QadVariablesClass():\n \"\"\"\n Classe che gestisce le variabuili di ambiente di Qad\n \"\"\" \n \n def __init__(self):\n \"\"\"\n Inizializza un dizionario con le variabili e i loro valori di default \n \"\"\"\n self.__VariableValuesDict = dict() # variabile privata <nome variabile>-<valore variabile>\n \n # ARCMINSEGMENTQTY (int): numero minimo di segmenti perché venga riconosciuto un arco\n VariableName = QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Minimum number of segments to approximate an arc.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(12), \\\n QadVariableTypeEnum.INT, \\\n 4, 999, \\\n VariableDescr)\n \n # AUTOSNAP (int): attiva il puntamento polare (somma di bit):\n # 8 = Attiva il puntamento polare\n VariableName = QadMsg.translate(\"Environment variables\", \"AUTOSNAP\")\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the display of the AutoSnap marker, tooltip, and magnet.\" + \\\n \"\\nAlso turns on polar and object snap tracking, and controls the display of polar tracking, object snap tracking, and Ortho mode tooltips.\" + \\\n \"\\nThe setting is stored as a bitcode using the sum of the following values:\" + \\\n \"\\n0 = Turns off the AutoSnap marker, tooltips, and magnet. Also turns off polar tracking, object snap tracking, and tooltips for polar tracking, object snap tracking, and Ortho mode.\" + \\\n \"\\n1 = Turns on the AutoSnap mark.\" + \\\n \"\\n2 = Turns on the AutoSnap tooltips.\" + \\\n \"\\n4 = Turns on the AutoSnap magnet.\" + \\\n \"\\n8 = Turns on polar tracking.\" + \\\n \"\\n16 = Turns on object snap tracking.\" + \\\n \"\\n32 = Turns on tooltips for polar tracking, object snap tracking, and Ortho mode.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(63), \\\n QadVariableTypeEnum.INT, \\\n 0, 64, \\\n VariableDescr)\n \n # CIRCLEMINSEGMENTQTY (int): numero minimo di segmenti perché venga riconosciuto un cerchio\n VariableName = QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Minimum number of segments to approximate a circle.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(12), \\\n QadVariableTypeEnum.INT, \\\n 6, 999, \\\n VariableDescr)\n \n # CMDINPUTHISTORYMAX (int): Imposta il numero massimo di comandi nella lista di storicizzazione\n VariableName = QadMsg.translate(\"Environment variables\", \"CMDINPUTHISTORYMAX\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets the maximum number of previous input values that are stored for a prompt in a command.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(20), \\\n QadVariableTypeEnum.INT, \\\n 1, 999, \\\n VariableDescr)\n \n # COPYMODE (int):\n # 0 = Imposta il comando COPIA in modo che venga ripetuto automaticamente\n # 1 = Imposta il comando COPIA in modo da creare una singola copia\n VariableName = QadMsg.translate(\"Environment variables\", \"COPYMODE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls whether the COPY command repeats automatically:\" + \\\n \"\\n0 = Sets the COPY command to repeat automatically.\" + \\\n \"\\n1 = Sets the COPY command to create a single copy.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, 1, \\\n VariableDescr)\n \n # CROSSINGAREACOLOR (str): Imposta il colore (RGB) dell'area di selezione degli oggetti nel modo intersezione\n VariableName = QadMsg.translate(\"Environment variables\", \"CROSSINGAREACOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the color of the transparent selection area during crossing selection (RGB, #33A02C = green).\" + \\\n \"\\nThe SELECTIONAREA system variable must be on.\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#33A02C\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # green \n \n # CURSORCOLOR (str): Imposta il colore (RGB) del cursore (la croce)\n VariableName = QadMsg.translate(\"Environment variables\", \"CURSORCOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Cross pointer color (RGB, #FF0000 = red).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#FF0000\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # red \n \n # CURSORSIZE (int): Imposta la dimensione in pixel del cursore (la croce)\n VariableName = QadMsg.translate(\"Environment variables\", \"CURSORSIZE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Determines the size of the crosshairs as a percentage of the screen size.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(5), \\\n QadVariableTypeEnum.INT, \\\n 1, 100, \\\n VariableDescr)\n \n # DIMSTYLE (str): Imposta il nome dello stile di quotatura corrente\n VariableName = QadMsg.translate(\"Environment variables\", \"DIMSTYLE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Stores the name of the current dimension style.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"\"), \\\n QadVariableTypeEnum.STRING, \\\n None, None, \\\n VariableDescr)\n \n # EDGEMODE (int): Controlla i comandi ESTENDI e TAGLIA.\n # O = Vengono usate le dimensioni reali degli oggetti di riferimento\n # 1 = Vengono usate le estensioni degli oggetti di riferimento (es. un arco viene considerato cerchio)\n VariableName = QadMsg.translate(\"Environment variables\", \"EDGEMODE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls how the TRIM and EXTEND commands determine cutting and boundary edges:\" + \\\n \"\\n0 = Uses the selected edge without an extensions.\" + \\\n \"\\n1 = Extends or trims the selected object to an imaginary extension of the cutting or boundary edge.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, 1, \\\n VariableDescr)\n \n # FILLETRAD (float): raggio applicato per raccordare (gradi)\n VariableName = QadMsg.translate(\"Environment variables\", \"FILLETRAD\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Stores the current fillet radius.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Real type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, float(0.0), \\\n QadVariableTypeEnum.FLOAT, \\\n 0.000001, None, \\\n VariableDescr)\n\n # GRIPCOLOR (str): Imposta il colore (RGB) dei grip non selezionati\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPCOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the color of unselected grips (RGB, #100DD6 = blue).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#100DD6\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # blu \n\n # GRIPCONTOUR (str): Imposta il colore (RGB) del bordo dei grip\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPCONTOUR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the color of the grip contour (RGB, #939393 = gray).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#939393\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # gray \n\n # GRIPHOT(str): Imposta il colore (RGB) dei grip selezionati\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPHOT\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the color of selected grips (RGB, #FF0000 = red).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#FF0000\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # red \n\n # GRIPHOVER(str): Imposta il colore (RGB) dei grip non selezionati quando il cursore si ferma su di essi\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPHOVER\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the fill color of an unselected grip when the cursor pauses over it (RGB, #FF7F7F = orange).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#FF7F7F\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # orange \n\n # GRIPS (int): Controlla la visualizzazione dei grip sugli oggetti selezionati\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPS\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the use of selection set grips for the Stretch, Move, Rotate, Scale, and Mirror Grip modes.\" + \\\n \"\\n0 = Hides grips.\" + \\\n \"\\n1 = Displays grips.\" + \\\n \"\\n2 = Displays additional midpoint grips on polyline segments.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(2), \\\n QadVariableTypeEnum.INT, \\\n 0, 2, \\\n VariableDescr)\n\n # GRIPSIZE (int): Imposta la dimensione in pixel dei simboli di grip\n VariableName = QadMsg.translate(\"Environment variables\", \"GRIPSIZE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Grip symbol size in pixel.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(10), \\\n QadVariableTypeEnum.INT, \\\n 1, 999, \\\n VariableDescr)\n\n # INPUTSEARCHDELAY (int): Controlla il tempo trascorso prima che le funzionalità di tastiera vengano visualizzate sulla riga di comando\n VariableName = QadMsg.translate(\"Environment variables\", \"INPUTSEARCHDELAY\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the amount of time that elapses before automated keyboard features display at the Command prompt.\" + \\\n \"\\nValid values are real numbers from 100 to 10,000, which represent milliseconds.\" + \\\n \"\\nThe time delay setting in the INPUTSEARCHOPTIONS system variable must be turned on for INPUTSEARCHDELAY to have an effect.\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(300), \\\n QadVariableTypeEnum.INT, \\\n 100, 10000, \\\n VariableDescr)\n\n # INPUTSEARCHOPTIONS (int): Controlla i tipi di funzioni automatiche della tastiera disponibili dalla riga di comando\n VariableName = QadMsg.translate(\"Environment variables\", \"INPUTSEARCHOPTIONS\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls what types of automated keyboard features are available at the Command prompt.\" + \\\n \"\\nThe setting is stored as a bitcode using the sum of the following values:\" + \\\n \"\\n 0 = Turns off all automated keyboard features when typing at the Command prompt.\" + \\\n \"\\n 1 = Turns on any automated keyboard features when typing at the Command prompt.\" + \\\n \"\\n 2 = Automatically appends suggestions as each keystroke is entered after the second keystroke.\" + \\\n \"\\n 4 = Displays a list of suggestions as keystrokes are entered.\" + \\\n \"\\n 8 = Displays the icon of the command or system variable, if available.\" + \\\n \"\\n16 = Excludes the display of system variables.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(15), \\\n QadVariableTypeEnum.INT, \\\n 0, 31, \\\n VariableDescr)\n\n # OFFSETDIST(float): Setta la distanza di default per l'offset\n # < 0 offset di un oggetto attraverso un punto\n # >= 0 offset di un oggetto attraverso la distanza\n VariableName = QadMsg.translate(\"Environment variables\", \"OFFSETDIST\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets the default offset distance:\" + \\\n \"\\n<0 = Offsets an object through a specified point.\" + \\\n \"\\n>=0 = Sets the default offset distance.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Real type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, float(-1.0), \\\n QadVariableTypeEnum.FLOAT, \\\n None, None, \\\n VariableDescr)\n\n # OFFSETGAPTYPE (int):\n # 0 = Estende i segmenti di linea alle relative intersezioni proiettate\n # 1 = Raccorda i segmenti di linea in corrispondenza delle relative intersezioni proiettate.\n # Il raggio di ciascun segmento di arco é uguale alla distanza di offset\n # 2 = Cima i segmenti di linea in corrispondenza delle intersezioni proiettate.\n # La distanza perpendicolare da ciascuna cima al rispettivo vertice\n # sull'oggetto originale é uguale alla distanza di offset.\n VariableName = QadMsg.translate(\"Environment variables\", \"OFFSETGAPTYPE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls how potential gaps between segments are treated when polylines are offset:\" + \\\n \"\\n0 = Extends line segments to their projected intersections.\" + \\\n \"\\n1 = Fillets line segments at their projected intersections. The radius of each arc segment is equal to the offset distance.\" + \\\n \"\\n2 = Chamfers line segments at their projected intersections. The perpendicular distance from each chamfer to its corresponding vertex on the original object is equal to the offset distance.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, 2, \\\n VariableDescr) \n \n # ORTHOMODE (int):\n # 0 = modalità di movimento ortogonale cursore disabilitata\n # 1 = modalità di movimento ortogonale cursore abilitata\n VariableName = QadMsg.translate(\"Environment variables\", \"ORTHOMODE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Constrains cursor movement to the perpendicular.\" + \\\n \"\\nWhen ORTHOMODE is turned on, the cursor can move only horizontally or vertically:\" + \\\n \"\\n0 = Turns off Ortho mode.\" + \\\n \"\\n1 = Turns on Ortho mode.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, 1, \\\n VariableDescr) \n \n # OSCOLOR (str): Imposta il colore (RGB) dei simboli di osnap\n VariableName = QadMsg.translate(\"Environment variables\", \"OSCOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Osnap symbols color (RGB, #FF0000 = red).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#FF0000\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # red\n \n # OSMODE (int): Imposta lo snap ad oggetto (somma di bit):\n # 0 = (NON) nessuno\n # 1 = (FIN) punti finali di ogni segmento\n # 2 = (MED) punto medio \n # 4 = (CEN) centroide di un poligono \n # 8 = (NOD) ad oggetto punto\n # 16 = (QUA) punto quadrante di un poligono\n # 32 = (INT) intersezione di un oggetto (anche i vertici intermedi di una linestring o polygon)\n # 64 = (INS) punto di inserimento di oggetti (come 8)\n # 128 = (PER) punto perpendicolare a un oggetto\n # 256 = (TAN) tangente di un arco, di un cerchio, di un'ellisse, di un arco ellittico o di una spline\n # 512 = (NEA) punto più vicino di un oggetto\n # 1024 = (C) Cancella tutti gli snap ad oggetto\n # 2048 = (APP) intersezione apparente di due oggetti che non si intersecano nello spazio 3D \n # ma che possono apparire intersecanti nella vista corrente\n # 4096 = (EST) Estensione : Visualizza una linea o un arco di estensione temporaneo quando si sposta il cursore sul punto finale degli oggetti, \n # in modo che sia possibile specificare punti sull'estensione\n # 8192 = (PAR) Parallelo: Vincola un segmento di linea, un segmento di polilinea, un raggio o una xlinea ad essere parallela ad un altro oggetto lineare\n # 16384 = osnap off\n # 65536 = (PR) Distanza progressiva\n # 131072 = intersezione sull'estensione\n # 262144 = perpendicolare differita\n # 524288 = tangente differita\n # 1048576 = puntamento polare\n # 2097152 = punti finali dell'intera polilinea\n VariableName = QadMsg.translate(\"Environment variables\", \"OSMODE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets running object snaps.\" + \\\n \"\\nThe setting is stored as a bitcode using the sum of the following values:\" + \\\n \"\\n0 = NONe.\" + \\\n \"\\n1 = ENDpoint.\" + \\\n \"\\n2 = MIDpoint.\" + \\\n \"\\n4 = CENter.\" + \\\n \"\\n8 = NODe.\" + \\\n \"\\n16 = QUAdrant.\" + \\\n \"\\n32 = INTersection.\" + \\\n \"\\n64 = INSertion.\" + \\\n \"\\n128 = PERpendicular.\" + \\\n \"\\n256 = TANgent.\" + \\\n \"\\n512 = NEArest.\" + \\\n \"\\n1024 = QUIck.\" + \\\n \"\\n2048 = APParent Intersection.\" + \\\n \"\\n4096 = EXTension.\" + \\\n \"\\n8192 = PARallel.\" + \\\n \"\\n65536 = PRogressive distance (PR[dist]).\" + \\\n \"\\n131072 = Intersection on extension (EXT_INT).\" + \\\n \"\\n2097152 = Final points on polyline (FIN_PL).\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, None, \\\n VariableDescr)\n \n # OSPROGRDISTANCE (float): Distanza progressiva per snap PR\n VariableName = QadMsg.translate(\"Environment variables\", \"OSPROGRDISTANCE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Progressive distance for <Progressive distance> snap mode.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Real type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, float(0.0), \\\n QadVariableTypeEnum.FLOAT, \\\n None, None, \\\n VariableDescr)\n \n # OSSIZE (int): Imposta la dimensione in pixel dei simboli di osnap\n VariableName = QadMsg.translate(\"Environment variables\", \"OSSIZE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Osnap symbol size in pixel.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(13), \\\n QadVariableTypeEnum.INT, \\\n 1, 999, \\\n VariableDescr)\n \n # PICKADD (int): Controlla se le selezioni successive sostituiscono il gruppo di selezione corrente o vengono aggiunte ad esso.\n VariableName = QadMsg.translate(\"Environment variables\", \"PICKADD\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls whether subsequent selections replace the current selection set or add to it.\" + \\\n \"\\n0 = Turns off PICKADD. The objects most recently selected become the selection set. Previously selected objects are removed from the selection set. Add more objects to the selection set by pressing SHIFT while selecting.\" + \\\n \"\\n1 = Turns on PICKADD. Each object selected, either individually or by windowing, is added to the current selection set. To remove objects from the set, press SHIFT while selecting.\" + \\\n \"\\n2 = Turns on PICKADD. Each object selected, either individually or by windowing, is added to the current selection set. To remove objects from the set, press SHIFT while selecting. Keeps objects selected after the SELECT command ends. \") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(0), \\\n QadVariableTypeEnum.INT, \\\n 0, 2, \\\n VariableDescr)\n \n # PICKBOX (int): Imposta la dimensione in pixel della distanza di selezione degli oggetti\n # dalla posizione corrente del puntatore\n VariableName = QadMsg.translate(\"Environment variables\", \"PICKBOX\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets the object selection target height, in pixels.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(5), \\\n QadVariableTypeEnum.INT, \\\n 1, 999, \\\n VariableDescr)\n \n # PICKBOXCOLOR (str): Imposta il colore (RGB) del quadratino di selezione degli oggetti\n VariableName = QadMsg.translate(\"Environment variables\", \"PICKBOXCOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets the object selection target color (RGB, #FF0000 = red).\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#FF0000\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # red \n\n # PICKFIRST (int): Controlla se è possibile selezionare gli oggetti prima di eseguire un comando.\n VariableName = QadMsg.translate(\"Environment variables\", \"PICKFIRST\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls whether you can select objects before you start a command.\" + \\\n \"\\n0 = Off. You can select objects only after you start a command.\" + \\\n \"\\n1 = On. You can also select objects before you start a command\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(1), \\\n QadVariableTypeEnum.INT, \\\n 0, 1, \\\n VariableDescr)\n\n # POLARANG (float): incremento dell'angolo polare per il puntamento polare (gradi)\n VariableName = QadMsg.translate(\"Environment variables\", \"POLARANG\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Sets the polar angle increment (degree).\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Real type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, float(90.0), \\\n QadVariableTypeEnum.INT, \\\n 0.000001, 359.999999, \\\n VariableDescr)\n \n # SELECTIONAREA (int): Controlla gli effetti della visualizzazione della selezione di aree.\n # dalla posizione corrente del puntatore\n VariableName = QadMsg.translate(\"Environment variables\", \"SELECTIONAREA\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the display of effects for selection areas.\" + \\\n \"\\nSelection areas are created by the Window, Crossing, WPolygon, CPolygon, WCircle, CCircle, WObjects, CObjects, WBuffer and CBuffer options of SELECT.\" + \\\n \"\\n0 = Off\" + \\\n \"\\n1 = On\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(1), \\\n QadVariableTypeEnum.INT, \\\n 0, 1, \\\n VariableDescr)\n \n # SELECTIONAREAOPACITY (int): Controlla gli effetti della visualizzazione della selezione di aree.\n # dalla posizione corrente del puntatore\n VariableName = QadMsg.translate(\"Environment variables\", \"SELECTIONAREAOPACITY\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the transparency of the selection area during window and crossing selection.\" + \\\n \"\\nThe valid range is 0 to 100. The lower the setting, the more transparent the area. A value of 100 makes the area opaque. The SELECTIONAREA system variable must be on.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Integer type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, int(25), \\\n QadVariableTypeEnum.INT, \\\n 0, 100, \\\n VariableDescr)\n\n # SUPPORTPATH (str): Path di ricerca per i files di supporto\n default = os.path.abspath(os.path.dirname(__file__) + \"\\\\support\")\n VariableName = QadMsg.translate(\"Environment variables\", \"SUPPORTPATH\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Searching path for support files.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, default, \\\n QadVariableTypeEnum.STRING, \\\n None, None, \\\n VariableDescr)\n \n # SHOWTEXTWINDOW (bool): Visualizza la finestra di testo all'avvio\n VariableName = QadMsg.translate(\"Environment variables\", \"SHOWTEXTWINDOW\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Show the text window at startup.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Boolean type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, True, \\\n QadVariableTypeEnum.BOOL, \\\n None, None, \\\n VariableDescr)\n \n # TOLERANCE2APPROXCURVE (float):\n # massimo errore tollerato tra una vera curva e quella approssimata dai segmenti retti\n # (nel sistema map-coordinate)\n VariableName = QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Maximum error approximating a curve to segments.\") # x lupdate\n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Real type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, float(0.1), \\\n QadVariableTypeEnum.FLOAT, \\\n 0.000001, None, \\\n VariableDescr)\n \n # WINDOWAREACOLOR (str): Imposta il colore (RGB) dell'area di selezione degli oggetti nel modo finestra\n VariableName = QadMsg.translate(\"Environment variables\", \"WINDOWAREACOLOR\") # x lupdate\n VariableDescr = QadMsg.translate(\"Environment variables\", \"Controls the color of the transparent selection area during window selection (RGB, #1F78B4 = blu).\" + \\\n \"\\nThe SELECTIONAREA system variable must be on.\") # x lupdate \n VariableDescr = VariableDescr + \"\\n\" + QadMsg.translate(\"Environment variables\", \"Character type.\")\n self.__VariableValuesDict[VariableName] = QadVariable(VariableName, unicode(\"#1F78B4\"), \\\n QadVariableTypeEnum.COLOR, \\\n None, None, \\\n VariableDescr) # blue \n \n\n def getVarNames(self):\n \"\"\"\n Ritorna la lista dei nomi delle variabili \n \"\"\"\n return self.__VariableValuesDict.keys()\n \n def set(self, VarName, VarValue):\n \"\"\"\n Modifica il valore di una variabile \n \"\"\"\n UpperVarName = VarName.upper()\n variable = self.getVariable(UpperVarName)\n \n if variable is None: # se non c'è la variablie\n self.__VariableValuesDict[UpperVarName] = QadVariable(UpperVarName, VarValue, \\\n QadVariableTypeEnum.UNKNOWN, \\\n None, None, \\\n \"\")\n else:\n if type(variable.value) != type(VarValue):\n if not((type(variable.value) == unicode or type(variable.value) == str) and\n (type(VarValue) == unicode or type(VarValue) == str)):\n return False\n if variable.typeValue == QadVariableTypeEnum.COLOR:\n if len(VarValue) == 7: # es. \"#FF0000\"\n if VarValue[0] != \"#\":\n return False\n else:\n return False\n elif variable.typeValue == QadVariableTypeEnum.FLOAT or \\\n variable.typeValue == QadVariableTypeEnum.INT:\n if variable.minNum is not None:\n if VarValue < variable.minNum:\n return False \n if variable.maxNum is not None:\n if VarValue > variable.maxNum:\n return False \n \n self.__VariableValuesDict[UpperVarName].value = VarValue\n\n return True\n \n def get(self, VarName, defaultValue = None):\n \"\"\"\n Restituisce il valore di una variabile \n \"\"\"\n variable = self.getVariable(VarName)\n if variable is None:\n result = defaultValue\n else:\n result = variable.value\n \n return result\n\n def getVariable(self, VarName):\n UpperVarName = VarName\n return self.__VariableValuesDict.get(UpperVarName.upper())\n\n\n def getDefaultQadIniFilePath(self):\n # ottiene il percorso automatico incluso il nome del file dove salvare il file qad.ini\n # se esiste un progetto caricato il percorso è quello del progetto\n prjFileInfo = QFileInfo(QgsProject.instance().fileName())\n path = prjFileInfo.absolutePath()\n if len(path) == 0:\n # se non esiste un progetto caricato uso il percorso di installazione di qad\n path = QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + \"python/plugins/qad\")\n return path + \"/\" + \"qad.ini\"\n \n \n def save(self, Path=\"\"):\n \"\"\"\n Salva il dizionario delle variabili su file \n \"\"\"\n if Path == \"\":\n # Se la path non é indicata uso il file \"qad.ini\" del progetto o dell'installazione di qad \n Path = self.getDefaultQadIniFilePath()\n \n dir = QFileInfo(Path).absoluteDir()\n if not dir.exists():\n os.makedirs(dir.absolutePath())\n \n file = open(Path, \"w\") # apre il file in scrittura\n for VarName in self.__VariableValuesDict.keys():\n VarValue = self.get(VarName)\n # scrivo il valore + il tipo (es var = 5 <type 'int'>)\n VarValue = str(VarValue) + \" \" + str(type(VarValue))\n Item = \"%s = %s\\n\" % (VarName, VarValue)\n file.write(Item)\n \n file.close()\n \n def load(self, Path=\"\"):\n \"\"\"\n Carica il dizionario delle variabili da file\n Ritorna True in caso di successo, false in caso di errore\n \"\"\"\n # svuoto il dizionario e lo reimposto con i valori di default\n self.__VariableValuesDict.clear()\n self.__init__()\n if Path == \"\":\n # Se la path non é indicata uso il file \"qad.ini\" del progetto o dell'installazione di qad \n Path = self.getDefaultQadIniFilePath()\n\n if not os.path.exists(Path):\n return False\n \n file = open(Path, \"r\") # apre il file in lettura\n for line in file:\n # leggo il valore + il tipo (es var = 5 <type 'int'>)\n sep = line.rfind(\" = \")\n VarName = line[0:sep]\n VarName = VarName.strip(\" \") # rimuovo gli spazi prima e dopo\n VarValue = line[sep+3:]\n sep = VarValue.rfind(\" <type '\")\n sep2 = VarValue.rfind(\"'>\")\n VarType = VarValue[sep+8:sep2]\n VarValue = VarValue[:sep]\n if VarType == \"int\":\n VarValue = qad_utils.str2int(VarValue)\n if VarValue is None:\n self.set(VarName, int(0))\n else:\n self.set(VarName, VarValue)\n elif VarType == \"long\":\n VarValue = qad_utils.str2long(VarValue)\n if VarValue is None:\n self.set(VarName, long(0))\n else:\n self.set(VarName, VarValue)\n elif VarType == \"float\":\n VarValue = qad_utils.str2float(VarValue)\n if VarValue is None:\n self.set(VarName, float(0))\n else:\n self.set(VarName, VarValue)\n elif VarType == \"bool\":\n VarValue = qad_utils.str2bool(VarValue)\n if VarValue is None:\n self.set(VarName, False)\n else:\n self.set(VarName, VarValue)\n else:\n self.set(VarName, str(VarValue))\n \n file.close()\n \n return True\n\n\n#===============================================================================\n# = variabile globale\n#===============================================================================\n\nQadVariables = QadVariablesClass()\n"
},
{
"alpha_fraction": 0.5088176131248474,
"alphanum_fraction": 0.5148695111274719,
"avg_line_length": 39.924102783203125,
"blob_id": "9f0f44d6ebe101284273e72dd86d49768993f238",
"content_id": "6e5edb1937faa87c70e6b0270d216a67a3889651",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 30751,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 751,
"path": "/qad_arc.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per la gestione degli archi\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_circle import *\nfrom qad_variables import *\n\n\n#===============================================================================\n# QadArc arc class\n#===============================================================================\nclass QadArc():\n \n def __init__(self, arc = None):\n if arc is not None:\n self.set(arc.center, arc.radius, arc.startAngle, arc.endAngle)\n else: \n self.center = None\n self.radius = None\n self.startAngle = None\n self.endAngle = None \n\n def whatIs(self):\n return \"ARC\"\n \n def set(self, center, radius, startAngle, endAngle):\n self.center = QgsPoint(center)\n self.radius = radius\n self.startAngle = startAngle\n self.endAngle = endAngle \n\n def transform(self, coordTransform):\n \"\"\"Transform this geometry as described by CoordinateTranasform ct.\"\"\"\n self.center = coordTransform.transform(self.center) \n\n def transformFromCRSToCRS(self, sourceCRS, destCRS):\n \"\"\"Transform this geometry as described by CRS.\"\"\"\n if (sourceCRS is not None) and (destCRS is not None) and sourceCRS != destCRS: \n coordTransform = QgsCoordinateTransform(sourceCRS, destCRS) # trasformo le coord\n self.center = coordTransform.transform(self.center)\n \n def __eq__(self, arc):\n \"\"\"self == other\"\"\"\n if self.center != arc.center or self.radius != arc.radius or \\\n self.startAngle != arc.startAngle or self.endAngle != arc.endAngle:\n return False\n else:\n return True \n \n def __ne__(self, arc):\n \"\"\"self != other\"\"\"\n if self.center != arc.center or self.radius != arc.radius or \\\n self.startAngle != arc.startAngle or self.endAngle != arc.endAngle:\n return True \n else:\n return False \n\n def totalAngle(self):\n if self.startAngle < self.endAngle:\n return self.endAngle - self.startAngle\n else:\n return (2 * math.pi - self.startAngle) + self.endAngle\n\n def length(self):\n return self.radius * self.totalAngle() \n\n def getStartPt(self):\n return qad_utils.getPolarPointByPtAngle(self.center,\n self.startAngle,\n self.radius)\n def setStartAngleByPt(self, pt):\n # da usare per modificare un arco già efinito\n angle = qad_utils.getAngleBy2Pts(self.center, pt)\n if angle == self.endAngle:\n return False\n else:\n self.startAngle = angle\n return True\n\n def getEndPt(self):\n return qad_utils.getPolarPointByPtAngle(self.center,\n self.endAngle,\n self.radius)\n def setEndAngleByPt(self, pt):\n # da usare per modificare un arco già definito\n angle = qad_utils.getAngleBy2Pts(self.center, pt)\n if angle == self.startAngle:\n return False\n else:\n self.endAngle = angle\n return True\n\n def isPtOnArc(self, point):\n dist = qad_utils.getDistance(self.center, point)\n if qad_utils.doubleNear(self.radius, dist):\n angle = qad_utils.getAngleBy2Pts(self.center, point)\n return qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle)\n else:\n return False\n\n def inverse(self):\n dummy = self.endAngle\n self.endAngle = self.startAngle \n self.startAngle = dummy\n\n def getMiddlePt(self):\n halfAngle = self.totalAngle() / 2\n return qad_utils.getPolarPointByPtAngle(self.center,\n self.startAngle + halfAngle,\n self.radius)\n\n def getQuadrantPoints(self):\n result = [] \n\n angle = 0\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append(QgsPoint(self.center.x() + self.radius, self.center.y()))\n \n angle = math.pi / 2\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append(QgsPoint(self.center.x(), self.center.y() + self.radius))\n \n angle = math.pi\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append(QgsPoint(self.center.x() - self.radius, self.center.y()))\n\n angle = math.pi * 3 / 2\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append(QgsPoint(self.center.x(), self.center.y() - self.radius))\n\n return result\n\n\n #============================================================================\n # getTanPoints\n #============================================================================\n def getTanPoints(self, point):\n result = []\n \n circle = QadCircle()\n circle.set(self.center, self.radius)\n points = circle.getTanPoints(point)\n tot = len(points)\n for p in points:\n angle = qad_utils.getAngleBy2Pts(self.center, p)\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append(p)\n \n return result\n\n\n #============================================================================\n # getTanDirectionOnPt\n #============================================================================\n def getTanDirectionOnPt(self, pt):\n angle = qad_utils.getAngleBy2Pts(self.center, pt)\n return qad_utils.normalizeAngle(angle + math.pi / 2) \n\n \n #============================================================================\n # getTanDirectionOnStartPt\n #============================================================================\n def getTanDirectionOnStartPt(self):\n return self.getTanDirectionOnPt(self.getStartPt()) \n\n\n #============================================================================\n # getTanDirectionOnEndPt\n #============================================================================\n def getTanDirectionOnEndPt(self):\n return self.getTanDirectionOnPt(self.getEndPt()) \n\n\n #============================================================================\n # getPerpendicularPoints\n #============================================================================\n def getPerpendicularPoints(self, point):\n result = []\n angle = qad_utils.getAngleBy2Pts(self.center, point)\n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append( qad_utils.getPolarPointByPtAngle(self.center,\n angle,\n self.radius))\n\n angle = angle + math.pi \n if qad_utils.isAngleBetweenAngles(self.startAngle, self.endAngle, angle) == True:\n result.append( qad_utils.getPolarPointByPtAngle(self.center,\n angle,\n self.radius))\n \n return result\n\n #============================================================================\n # getIntersectionPointsWithInfinityLine\n #============================================================================\n def getIntersectionPointsWithInfinityLine(self, p1, p2):\n result = []\n circle = QadCircle()\n circle.set(self.center, self.radius)\n intPtList = circle.getIntersectionPointsWithInfinityLine(p1, p2)\n for intPt in intPtList:\n if self.isPtOnArc(intPt):\n result.append(intPt) \n return result\n\n\n #============================================================================\n # getIntersectionPointsWithSegment\n #============================================================================\n def getIntersectionPointsWithSegment(self, p1, p2):\n result = []\n intPtList = self.getIntersectionPointsWithInfinityLine(p1, p2)\n for intPt in intPtList:\n if qad_utils.isPtOnSegment(p1, p2, intPt):\n result.append(intPt) \n return result\n\n\n #============================================================================\n # getIntersectionPointsWithCircle\n #============================================================================\n def getIntersectionPointsWithCircle(self, circle):\n result = []\n circle1 = QadCircle()\n circle1.set(self.center, self.radius)\n intPtList = circle1.getIntersectionPointsWithCircle(circle)\n for intPt in intPtList:\n if self.isPtOnArc(intPt):\n result.append(intPt) \n return result\n\n\n #============================================================================\n # getIntersectionPointsWithArc\n #============================================================================\n def getIntersectionPointsWithArc(self, arc):\n result = []\n circle = QadCircle()\n circle.set(arc.center, arc.radius)\n intPtList = self.getIntersectionPointsWithCircle(circle)\n for intPt in intPtList:\n if arc.isPtOnArc(intPt):\n result.append(intPt) \n return result\n\n \n #============================================================================\n # asPolyline\n #============================================================================\n def asPolyline(self, tolerance2ApproxCurve = None, atLeastNSegment = None):\n \"\"\"\n ritorna una lista di punti che definisce l'arco\n \"\"\"\n if tolerance2ApproxCurve is None:\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n else:\n tolerance = tolerance2ApproxCurve\n \n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n # Calcolo la lunghezza del segmento con pitagora\n dummy = self.radius - tolerance\n if dummy <= 0: # se la tolleranza é troppo bassa rispetto al raggio\n SegmentLen = self.radius\n else:\n dummy = (self.radius * self.radius) - (dummy * dummy)\n SegmentLen = math.sqrt(dummy) # radice quadrata\n SegmentLen = SegmentLen * 2\n \n if SegmentLen == 0: # se la tolleranza é troppo bassa la lunghezza del segmento diventa zero \n return None\n \n # calcolo quanti segmenti ci vogliono (non meno di _atLeastNSegment)\n SegmentTot = math.ceil(self.length() / SegmentLen)\n if SegmentTot < _atLeastNSegment:\n SegmentTot = _atLeastNSegment\n \n points = []\n # primo punto\n pt = qad_utils.getPolarPointByPtAngle(self.center, self.startAngle, self.radius)\n points.append(pt)\n\n i = 1\n angle = self.startAngle\n offSetAngle = self.totalAngle() / SegmentTot\n while i < SegmentTot:\n angle = angle + offSetAngle\n pt = qad_utils.getPolarPointByPtAngle(self.center, angle, self.radius)\n points.append(pt) \n i = i + 1\n\n # ultimo punto\n pt = qad_utils.getPolarPointByPtAngle(self.center, self.endAngle, self.radius)\n points.append(pt)\n return points\n \n \n #============================================================================\n # fromStartSecondEndPts\n #============================================================================\n def fromStartSecondEndPts(self, startPt, secondPt, endPt):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n secondo punto (intermedio)\n punto finale\n \"\"\"\n points = [startPt, secondPt, endPt]\n # lista di punti, parte dal punto 0, almeno 2 segmenti\n if self.fromPolyline(points, 0, 2) is None:\n return False\n else:\n return True\n\n\n #============================================================================\n # fromStartCenterEndPts\n #============================================================================\n def fromStartCenterEndPts(self, startPt, centerPt, endPt):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n centro\n punto finale\n \"\"\"\n if startPt == centerPt or startPt == endPt or endPt == centerPt:\n return False\n \n self.center = centerPt\n self.radius = qad_utils.getDistance(centerPt, startPt)\n self.startAngle = qad_utils.getAngleBy2Pts(centerPt, startPt)\n self.endAngle = qad_utils.getAngleBy2Pts(centerPt, endPt)\n return True\n \n\n #============================================================================\n # fromStartCenterPtsAngle\n #============================================================================\n def fromStartCenterPtsAngle(self, startPt, centerPt, angle):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n centro\n angolo inscritto\n \"\"\"\n if startPt == centerPt or angle == 0:\n return False\n \n self.center = centerPt\n self.radius = qad_utils.getDistance(centerPt, startPt)\n self.startAngle = qad_utils.getAngleBy2Pts(centerPt, startPt) \n self.endAngle = self.startAngle + angle\n if self.endAngle > math.pi * 2:\n self.endAngle = self.endAngle % (math.pi * 2) # modulo\n return True\n \n\n #============================================================================\n # fromStartCenterPtsChord\n #============================================================================\n def fromStartCenterPtsChord(self, startPt, centerPt, chord):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n centro\n lunghezza dela corda tra punto iniziale e finale\n \"\"\"\n if startPt == centerPt or chord == 0:\n return False\n\n self.center = centerPt\n self.radius = qad_utils.getDistance(centerPt, startPt)\n if chord > 2 * self.radius:\n return False\n self.startAngle = qad_utils.getAngleBy2Pts(centerPt, startPt)\n # Teorema della corda\n angle = 2 * math.asin(chord / (2 * self.radius))\n self.endAngle = self.startAngle + angle\n return True\n\n\n #============================================================================\n # fromStartEndPtsAngle\n #============================================================================\n def fromStartEndPtsAngle(self, startPt, endPt, angle):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n punto finale\n angolo inscritto\n \"\"\"\n if startPt == endPt or angle == 0:\n return False\n\n chord = qad_utils.getDistance(startPt, endPt)\n half_chord = chord / 2 \n # Teorema della corda\n self.radius = half_chord / math.sin(angle / 2)\n \n angleSegment = qad_utils.getAngleBy2Pts(startPt, endPt)\n ptMiddle = qad_utils.getMiddlePoint(startPt, endPt)\n \n # Pitagora\n distFromCenter = math.sqrt((self.radius * self.radius) - (half_chord * half_chord))\n if angle < math.pi: # se angolo < 180 gradi\n # aggiungo 90 gradi per cercare il centro a sinistra del segmento\n self.center = qad_utils.getPolarPointByPtAngle(ptMiddle, \n angleSegment + (math.pi / 2),\n distFromCenter)\n else:\n # sottraggo 90 gradi per cercare il centro a destra del segmento\n self.center = qad_utils.getPolarPointByPtAngle(ptMiddle, \n angleSegment - (math.pi / 2),\n distFromCenter)\n self.startAngle = qad_utils.getAngleBy2Pts(self.center, startPt)\n self.endAngle = qad_utils.getAngleBy2Pts(self.center, endPt) \n return True\n\n\n #============================================================================\n # fromStartEndPtsTan\n #============================================================================\n def fromStartEndPtsTan(self, startPt, endPt, tan):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n punto finale\n direzione della tangente sul punto iniziale\n \"\"\"\n if startPt == endPt:\n return False\n \n angleSegment = qad_utils.getAngleBy2Pts(startPt, endPt)\n if tan == angleSegment or tan == angleSegment - math.pi:\n return False\n \n chord = qad_utils.getDistance(startPt, endPt)\n half_chord = chord / 2\n ptMiddle = qad_utils.getMiddlePoint(startPt, endPt)\n\n angle = tan + (math.pi / 2)\n angle = angleSegment - angle\n distFromCenter = math.tan(angle) * half_chord\n self.center = qad_utils.getPolarPointByPtAngle(ptMiddle, \n angleSegment - (math.pi / 2),\n distFromCenter)\n pt = qad_utils.getPolarPointByPtAngle(startPt, tan, chord)\n \n if qad_utils.leftOfLine(endPt, startPt, pt) < 0:\n # arco si sviluppa a sinistra della tangente\n self.startAngle = qad_utils.getAngleBy2Pts(self.center, startPt)\n self.endAngle = qad_utils.getAngleBy2Pts(self.center, endPt)\n else:\n # arco si sviluppa a destra della tangente\n self.startAngle = qad_utils.getAngleBy2Pts(self.center, endPt)\n self.endAngle = qad_utils.getAngleBy2Pts(self.center, startPt)\n \n self.radius = qad_utils.getDistance(startPt, self.center)\n return True\n\n\n #============================================================================\n # fromStartEndPtsRadius\n #============================================================================\n def fromStartEndPtsRadius(self, startPt, endPt, radius):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n punto finale\n raggio\n \"\"\"\n if startPt == endPt or radius <= 0:\n return False\n\n chord = qad_utils.getDistance(startPt, endPt)\n half_chord = chord / 2\n if radius < half_chord:\n return False\n\n self.radius = radius\n angleSegment = qad_utils.getAngleBy2Pts(startPt, endPt)\n ptMiddle = qad_utils.getMiddlePoint(startPt, endPt)\n \n # Pitagora\n distFromCenter = math.sqrt((self.radius * self.radius) - (half_chord * half_chord))\n # aggiungo 90 gradi\n self.center = qad_utils.getPolarPointByPtAngle(ptMiddle, \n angleSegment + (math.pi / 2),\n distFromCenter)\n self.startAngle = qad_utils.getAngleBy2Pts(self.center, startPt)\n self.endAngle = qad_utils.getAngleBy2Pts(self.center, endPt)\n return True\n\n\n #============================================================================\n # fromStartPtAngleRadiusChordDirection\n #============================================================================\n def fromStartPtAngleRadiusChordDirection(self, startPt, angle, radius, chordDirection):\n \"\"\"\n setta le caratteristiche dell'arco attraverso:\n punto iniziale\n angolo inscritto\n raggio\n direzione della corda\n \"\"\"\n if angle == 0 or angle == 2 * math.pi or radius <= 0:\n return False\n\n a = chordDirection + (math.pi / 2) - (angle / 2) \n self.radius = radius\n self.center = qad_utils.getPolarPointByPtAngle(startPt, a, radius)\n endPt = qad_utils.getPolarPointByPtAngle(self.center, a + math.pi + angle, radius)\n \n self.startAngle = qad_utils.getAngleBy2Pts(self.center, startPt)\n self.endAngle = qad_utils.getAngleBy2Pts(self.center, endPt)\n return True\n \n\n #============================================================================\n # fromPolyline\n #============================================================================\n def fromPolyline(self, points, startVertex, atLeastNSegment = None):\n \"\"\"\n setta le caratteristiche del primo arco incontrato nella lista di punti\n partendo dalla posizione startVertex (0-indexed)\n ritorna la posizione nella lista del punto iniziale e finale se é stato trovato un arco\n altrimenti None\n N.B. in punti NON devono essere in coordinate geografiche\n \"\"\"\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n totPoints = len(points)\n # perché sia un arco ci vogliono almeno _atLeastNSegment segmenti\n if (totPoints - 1) - startVertex < _atLeastNSegment or _atLeastNSegment < 2:\n return None\n \n # per problemi di approssimazione dei calcoli\n epsilon = 1.e-4 # percentuale del raggio per ottenere max diff. di una distanza con il raggio\n\n InfinityLinePerpOnMiddle1 = None\n InfinityLinePerpOnMiddle2 = None\n \n nSegment = 0\n i = startVertex\n while i < totPoints - 1:\n if InfinityLinePerpOnMiddle1 is None:\n InfinityLinePerpOnMiddle1 = qad_utils.getInfinityLinePerpOnMiddle(points[i], points[i + 1])\n nStartVertex = i\n nSegment = 1\n i = i + 1\n continue\n elif InfinityLinePerpOnMiddle2 is None: \n InfinityLinePerpOnMiddle2 = qad_utils.getInfinityLinePerpOnMiddle(points[i], points[i + 1])\n if InfinityLinePerpOnMiddle2 is None: \n InfinityLinePerpOnMiddle1 = None\n nSegment = 0\n else:\n # calcolo il presunto centro con 2 segmenti\n center = qad_utils.getIntersectionPointOn2InfinityLines(InfinityLinePerpOnMiddle1[0], \\\n InfinityLinePerpOnMiddle1[1], \\\n InfinityLinePerpOnMiddle2[0], \\\n InfinityLinePerpOnMiddle2[1])\n if center is None: # linee parallele\n InfinityLinePerpOnMiddle1 = InfinityLinePerpOnMiddle2\n InfinityLinePerpOnMiddle2 = None\n nStartVertex = i\n nSegment = 1\n else:\n nSegment = nSegment + 1\n radius = qad_utils.getDistance(center, points[i + 1]) # calcolo il presunto raggio\n maxDifference = radius * epsilon\n \n # calcolo il verso dell'arco e l'angolo dell'arco \n # se un punto intermedio dell'arco è a sinistra del\n # segmento che unisce i due punti allora il verso è antiorario\n startClockWise = True if qad_utils.leftOfLine(points[i], points[i - 1], points[i + 1]) < 0 else False\n angle = qad_utils.getAngleBy3Pts(points[i - 1], center, points[i + 1], startClockWise) \n else: # e sono già stati valutati almeno 2 segmenti\n # calcolo la distanza del punto dal presunto centro\n dist = qad_utils.getDistance(center, points[i + 1])\n # calcolo il verso dell'arco e l'angolo \n clockWise = True if qad_utils.leftOfLine(points[i], points[i - 1], points[i + 1]) < 0 else False \n angle = angle + qad_utils.getAngleBy3Pts(points[i], center, points[i + 1], startClockWise) \n \n # se la distanza è così vicina a quella del raggio\n # il verso dell'arco deve essere quello iniziale\n # l'angolo dell'arco non può essere >= 360 gradi\n if qad_utils.doubleNear(radius, dist, maxDifference) and \\\n startClockWise == clockWise and \\\n angle < 2 * math.pi: \n nSegment = nSegment + 1 # anche questo segmento fa parte dell'arco\n else: # questo segmento non fa parte del cerchio\n # se sono stati trovati un numero sufficiente di segmenti successivi\n if nSegment >= _atLeastNSegment:\n # se é un angolo giro e il primo punto = ultimo punto allora points é un cerchio\n if qad_utils.doubleNear(angle, 2 * math.pi) and points[0] == points[-1]: \n return None\n break\n else:\n i = i - 2\n InfinityLinePerpOnMiddle1 = None\n InfinityLinePerpOnMiddle2 = None\n \n i = i + 1\n \n # se sono stati trovati un numero sufficiente di segmenti successivi\n if nSegment >= _atLeastNSegment:\n nEndVertex = nStartVertex + nSegment\n # se il punto iniziale e quello finale non coincidono é un arco \n if points[nStartVertex] != points[nEndVertex]:\n self.center = center\n self.radius = radius\n \n # se il verso é orario\n if startClockWise:\n # inverto l'angolo iniziale con quello finale\n self.endAngle = qad_utils.getAngleBy2Pts(center, points[nStartVertex])\n self.startAngle = qad_utils.getAngleBy2Pts(center, points[nEndVertex])\n else:\n self.startAngle = qad_utils.getAngleBy2Pts(center, points[nStartVertex])\n self.endAngle = qad_utils.getAngleBy2Pts(center, points[nEndVertex]) \n\n return nStartVertex, nEndVertex\n \n return None\n \n\n#===============================================================================\n# QadArcList lista di archi class\n#===============================================================================\nclass QadArcList():\n def __init__(self):\n self.arcList = [] # lista di archi\n self.startEndVerticesList = [] # lista degli estremi (posizioni dei vertici iniziali e finali)\n\n def clear(self):\n del self.arcList[:] # svuoto la lista\n del self.startEndVerticesList[:] # svuoto la lista\n\n\n #============================================================================\n # fromPoints\n #============================================================================\n def fromPoints(self, points, atLeastNSegment = None):\n \"\"\"\n setta la lista degli archi e degli estremi leggendo una sequenza di punti\n ritorna il numero di archi trovati\n \"\"\" \n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n self.clear()\n startVertex = 0\n arc = QadArc()\n startEndVertices = arc.fromPolyline(points, startVertex, _atLeastNSegment)\n while startEndVertices is not None:\n _arc = QadArc(arc) # ne faccio una copia\n self.arcList.append(_arc)\n self.startEndVerticesList.append(startEndVertices)\n startVertex = startEndVertices[1] # l'ultimo punto dell'arco\n startEndVertices = arc.fromPolyline(points, startVertex, _atLeastNSegment) \n\n return len(self.arcList)\n\n\n #============================================================================\n # fromGeom\n #============================================================================\n def fromGeom(self, geom, atLeastNSegment = None):\n \"\"\"\n setta la lista degli archi e degli estremi leggendo una geometria\n ritorna il numero di archi trovati\n \"\"\"\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n self.clear()\n arc = QadArc()\n incremental = 0 \n # riduco in polilinee\n geoms = qad_utils.asPointOrPolyline(geom)\n for g in geoms:\n points = g.asPolyline() # vettore di punti\n startVertex = 0\n startEndVertices = arc.fromPolyline(points, startVertex, _atLeastNSegment)\n while startEndVertices is not None:\n _arc = QadArc(arc) # ne faccio una copia\n self.arcList.append(_arc)\n self.startEndVerticesList.append([startEndVertices[0] + incremental, startEndVertices[1] + incremental])\n startVertex = startEndVertices[1] # l'ultimo punto dell'arco\n startEndVertices = arc.fromPolyline(points, startVertex, _atLeastNSegment)\n \n incremental = len(points) - 1\n\n return len(self.arcList)\n\n #============================================================================\n # fromGeom\n #============================================================================\n def arcAt(self, afterVertex):\n \"\"\"\n cerca se esiste un arco al segmento il cui secondo vertice é <afterVertex>\n restituisce una lista con <arco>, <lista con indice del punto iniziale e finale>\n oppure None se arco non trovato\n \"\"\"\n i = 0\n for startEndVertices in self.startEndVerticesList:\n if afterVertex > startEndVertices[0] and afterVertex <= startEndVertices[1]:\n return self.arcList[i], startEndVertices\n i = i + 1\n \n return None\n"
},
{
"alpha_fraction": 0.6772279739379883,
"alphanum_fraction": 0.7075636982917786,
"avg_line_length": 61.84745788574219,
"blob_id": "ff272819a2b804b7b7d1a7811652dcd95731bac1",
"content_id": "08afc06e5e2fe2ed35e07a665d4a2a7917cf6cb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7417,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 118,
"path": "/qad_dimstyle_ui.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qad_dimstyle.ui'\n#\n# Created: Tue Sep 08 15:55:19 2015\n# by: PyQt4 UI code generator 4.10.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_DimStyle_Dialog(object):\n def setupUi(self, DimStyle_Dialog):\n DimStyle_Dialog.setObjectName(_fromUtf8(\"DimStyle_Dialog\"))\n DimStyle_Dialog.setWindowModality(QtCore.Qt.WindowModal)\n DimStyle_Dialog.resize(523, 341)\n self.label = QtGui.QLabel(DimStyle_Dialog)\n self.label.setGeometry(QtCore.QRect(20, 10, 121, 16))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.currentDimStyle = QtGui.QLabel(DimStyle_Dialog)\n self.currentDimStyle.setGeometry(QtCore.QRect(140, 10, 331, 16))\n self.currentDimStyle.setObjectName(_fromUtf8(\"currentDimStyle\"))\n self.label_2 = QtGui.QLabel(DimStyle_Dialog)\n self.label_2.setGeometry(QtCore.QRect(20, 40, 47, 16))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.dimStyleList = QtGui.QListView(DimStyle_Dialog)\n self.dimStyleList.setGeometry(QtCore.QRect(10, 60, 171, 171))\n self.dimStyleList.setObjectName(_fromUtf8(\"dimStyleList\"))\n self.SetCurrent = QtGui.QPushButton(DimStyle_Dialog)\n self.SetCurrent.setGeometry(QtCore.QRect(410, 60, 101, 23))\n self.SetCurrent.setObjectName(_fromUtf8(\"SetCurrent\"))\n self.new_2 = QtGui.QPushButton(DimStyle_Dialog)\n self.new_2.setGeometry(QtCore.QRect(410, 90, 101, 23))\n self.new_2.setObjectName(_fromUtf8(\"new_2\"))\n self.Mod = QtGui.QPushButton(DimStyle_Dialog)\n self.Mod.setGeometry(QtCore.QRect(410, 120, 101, 23))\n self.Mod.setObjectName(_fromUtf8(\"Mod\"))\n self.TempMod = QtGui.QPushButton(DimStyle_Dialog)\n self.TempMod.setGeometry(QtCore.QRect(410, 150, 101, 23))\n self.TempMod.setObjectName(_fromUtf8(\"TempMod\"))\n self.Diff = QtGui.QPushButton(DimStyle_Dialog)\n self.Diff.setGeometry(QtCore.QRect(410, 180, 101, 23))\n self.Diff.setObjectName(_fromUtf8(\"Diff\"))\n self.groupBox = QtGui.QGroupBox(DimStyle_Dialog)\n self.groupBox.setGeometry(QtCore.QRect(10, 240, 501, 61))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.descriptionSelectedStyle = QtGui.QLabel(self.groupBox)\n self.descriptionSelectedStyle.setGeometry(QtCore.QRect(10, 10, 481, 41))\n self.descriptionSelectedStyle.setObjectName(_fromUtf8(\"descriptionSelectedStyle\"))\n self.label_3 = QtGui.QLabel(DimStyle_Dialog)\n self.label_3.setGeometry(QtCore.QRect(190, 40, 71, 16))\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.selectedStyle = QtGui.QLabel(DimStyle_Dialog)\n self.selectedStyle.setGeometry(QtCore.QRect(270, 40, 241, 16))\n self.selectedStyle.setObjectName(_fromUtf8(\"selectedStyle\"))\n self.layoutWidget = QtGui.QWidget(DimStyle_Dialog)\n self.layoutWidget.setGeometry(QtCore.QRect(350, 310, 158, 25))\n self.layoutWidget.setObjectName(_fromUtf8(\"layoutWidget\"))\n self.horizontalLayout = QtGui.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout.setMargin(0)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.closeButton = QtGui.QPushButton(self.layoutWidget)\n self.closeButton.setObjectName(_fromUtf8(\"closeButton\"))\n self.horizontalLayout.addWidget(self.closeButton)\n self.helpButton = QtGui.QPushButton(self.layoutWidget)\n self.helpButton.setObjectName(_fromUtf8(\"helpButton\"))\n self.horizontalLayout.addWidget(self.helpButton)\n self.previewDummy = QtGui.QPushButton(DimStyle_Dialog)\n self.previewDummy.setGeometry(QtCore.QRect(190, 60, 211, 171))\n self.previewDummy.setText(_fromUtf8(\"\"))\n self.previewDummy.setObjectName(_fromUtf8(\"previewDummy\"))\n\n self.retranslateUi(DimStyle_Dialog)\n QtCore.QObject.connect(self.SetCurrent, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.setCurrentStyle)\n QtCore.QObject.connect(self.new_2, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.createNewStyle)\n QtCore.QObject.connect(self.Mod, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.modStyle)\n QtCore.QObject.connect(self.dimStyleList, QtCore.SIGNAL(_fromUtf8(\"customContextMenuRequested(QPoint)\")), DimStyle_Dialog.displayPopupMenu)\n QtCore.QObject.connect(self.TempMod, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.temporaryModStyle)\n QtCore.QObject.connect(self.helpButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.ButtonHELP_Pressed)\n QtCore.QObject.connect(self.Diff, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.showDiffBetweenStyles)\n QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Dialog.accept)\n QtCore.QMetaObject.connectSlotsByName(DimStyle_Dialog)\n\n def retranslateUi(self, DimStyle_Dialog):\n DimStyle_Dialog.setWindowTitle(_translate(\"DimStyle_Dialog\", \"QAD - Dimension style manager\", None))\n self.label.setText(_translate(\"DimStyle_Dialog\", \"Current dimension style:\", None))\n self.currentDimStyle.setText(_translate(\"DimStyle_Dialog\", \"none\", None))\n self.label_2.setText(_translate(\"DimStyle_Dialog\", \"Styles\", None))\n self.SetCurrent.setToolTip(_translate(\"DimStyle_Dialog\", \"Sets the style selected under Styles to current. The current style is applied to dimensions you create.\", None))\n self.SetCurrent.setText(_translate(\"DimStyle_Dialog\", \"Set current\", None))\n self.new_2.setToolTip(_translate(\"DimStyle_Dialog\", \"Define a new dimension style.\", None))\n self.new_2.setText(_translate(\"DimStyle_Dialog\", \"New...\", None))\n self.Mod.setToolTip(_translate(\"DimStyle_Dialog\", \"Modify the selected dimension style.\", None))\n self.Mod.setText(_translate(\"DimStyle_Dialog\", \"Modify...\", None))\n self.TempMod.setToolTip(_translate(\"DimStyle_Dialog\", \"Set temporary modifications for the selected style. The temporary modifications will not saved.\", None))\n self.TempMod.setText(_translate(\"DimStyle_Dialog\", \"Override...\", None))\n self.Diff.setToolTip(_translate(\"DimStyle_Dialog\", \"Compare two dimension styles or list all the properties of one dimension style.\", None))\n self.Diff.setText(_translate(\"DimStyle_Dialog\", \"Compare...\", None))\n self.groupBox.setTitle(_translate(\"DimStyle_Dialog\", \"Description\", None))\n self.descriptionSelectedStyle.setText(_translate(\"DimStyle_Dialog\", \"none\", None))\n self.label_3.setText(_translate(\"DimStyle_Dialog\", \"Preview of:\", None))\n self.selectedStyle.setText(_translate(\"DimStyle_Dialog\", \"none\", None))\n self.closeButton.setText(_translate(\"DimStyle_Dialog\", \"Close\", None))\n self.helpButton.setText(_translate(\"DimStyle_Dialog\", \"?\", None))\n\n"
},
{
"alpha_fraction": 0.5848752856254578,
"alphanum_fraction": 0.5869500637054443,
"avg_line_length": 40.50790786743164,
"blob_id": "52417353d295c35d8c174efa6fe36101a76bc986",
"content_id": "f783dbb4f01217c3ae03a0a793a4241b63583a2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 23660,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 569,
"path": "/qad_commands.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire i comandi\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_maptool import QadMapTool, QadVirtualSelCommandClass, QadVirtualGripCommandsClass\nfrom qad_msg import QadMsg\nfrom qad_cmd_aliases import *\nfrom qad_variables import QadVariables\n\nfrom qad_getpoint import *\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_id_cmd import QadIDCommandClass\nfrom qad_setcurrlayerbygraph_cmd import QadSETCURRLAYERBYGRAPHCommandClass, QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass\nfrom qad_setvar_cmd import QadSETVARCommandClass\nfrom qad_pline_cmd import QadPLINECommandClass\nfrom qad_arc_cmd import QadARCCommandClass\nfrom qad_circle_cmd import QadCIRCLECommandClass\nfrom qad_dsettings_cmd import QadDSETTINGSCommandClass\nfrom qad_line_cmd import QadLINECommandClass\nfrom qad_erase_cmd import QadERASECommandClass\nfrom qad_mpolygon_cmd import QadMPOLYGONCommandClass\nfrom qad_mbuffer_cmd import QadMBUFFERCommandClass\nfrom qad_rotate_cmd import QadROTATECommandClass\nfrom qad_move_cmd import QadMOVECommandClass\nfrom qad_scale_cmd import QadSCALECommandClass\nfrom qad_copy_cmd import QadCOPYCommandClass\nfrom qad_offset_cmd import QadOFFSETCommandClass\nfrom qad_extend_cmd import QadEXTENDCommandClass\nfrom qad_trim_cmd import QadTRIMCommandClass\nfrom qad_rectangle_cmd import QadRECTANGLECommandClass\nfrom qad_mirror_cmd import QadMIRRORCommandClass\nfrom qad_undoredo_cmd import QadUNDOCommandClass, QadREDOCommandClass\nfrom qad_insert_cmd import QadINSERTCommandClass\nfrom qad_text_cmd import QadTEXTCommandClass\nfrom qad_stretch_cmd import QadSTRETCHCommandClass\nfrom qad_break_cmd import QadBREAKCommandClass\nfrom qad_pedit_cmd import QadPEDITCommandClass\nfrom qad_fillet_cmd import QadFILLETCommandClass\nfrom qad_polygon_cmd import QadPOLYGONCommandClass\nfrom qad_dim_cmd import QadDIMLINEARCommandClass, QadDIMALIGNEDCommandClass\nfrom qad_dimstyle_cmd import QadDIMSTYLECommandClass\nfrom qad_lengthen_cmd import QadLENGTHENCommandClass\nfrom qad_help_cmd import QadHELPCommandClass\n\n\n# Classe che gestisce i comandi di Qad\nclass QadCommandsClass():\n # quando si aggiunge un nuovo comando bisogna\n # 1) aggiungerlo nella lista __cmdObjs nella funzione __init__ \n # 2) se il comando può essere richiamato da menu o da toolbar vedere la funzione Qad::initGui (qad.py)\n # e ricordarsi di inserire l'icona in resources.qrc e di ricompilare le risorse\n # 3) aggiungere funzione per l'avvio del comando \"run<nome_comando>Command\"\n \n def __init__(self, plugIn): \n self.plugIn = plugIn\n \n self.__cmdObjs = [] # lista interna degli oggetti comandi\n self.__cmdObjs.append(QadIDCommandClass(self.plugIn)) # ID\n self.__cmdObjs.append(QadSETVARCommandClass(self.plugIn)) # SETVAR\n self.__cmdObjs.append(QadPLINECommandClass(self.plugIn)) # PLINE\n self.__cmdObjs.append(QadSETCURRLAYERBYGRAPHCommandClass(self.plugIn))# SETCURRLAYERBYGRAPH\n self.__cmdObjs.append(QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(self.plugIn)) # SETCURRUPDATEABLELAYERBYGRAPH\n self.__cmdObjs.append(QadARCCommandClass(self.plugIn)) # ARC\n self.__cmdObjs.append(QadCIRCLECommandClass(self.plugIn)) # CIRCLE\n self.__cmdObjs.append(QadDSETTINGSCommandClass(self.plugIn)) # DSETTINGS\n self.__cmdObjs.append(QadLINECommandClass(self.plugIn)) # LINE\n self.__cmdObjs.append(QadERASECommandClass(self.plugIn)) # ERASE\n self.__cmdObjs.append(QadMPOLYGONCommandClass(self.plugIn)) # MPOLYGON\n self.__cmdObjs.append(QadMBUFFERCommandClass(self.plugIn)) # MBUFFER\n self.__cmdObjs.append(QadROTATECommandClass(self.plugIn)) # ROTATE\n self.__cmdObjs.append(QadMOVECommandClass(self.plugIn)) # MOVE\n self.__cmdObjs.append(QadSCALECommandClass(self.plugIn)) # SCALE\n self.__cmdObjs.append(QadCOPYCommandClass(self.plugIn)) # COPY\n self.__cmdObjs.append(QadOFFSETCommandClass(self.plugIn)) # OFFSET\n self.__cmdObjs.append(QadEXTENDCommandClass(self.plugIn)) # EXTEND\n self.__cmdObjs.append(QadTRIMCommandClass(self.plugIn)) # TRIM\n self.__cmdObjs.append(QadRECTANGLECommandClass(self.plugIn)) # RECTANGLE\n self.__cmdObjs.append(QadMIRRORCommandClass(self.plugIn)) # MIRROR\n self.__cmdObjs.append(QadUNDOCommandClass(self.plugIn)) # UNDO\n self.__cmdObjs.append(QadREDOCommandClass(self.plugIn)) # REDO\n self.__cmdObjs.append(QadINSERTCommandClass(self.plugIn)) # INSERT\n self.__cmdObjs.append(QadTEXTCommandClass(self.plugIn)) # TEXT\n self.__cmdObjs.append(QadSTRETCHCommandClass(self.plugIn)) # STRETCH\n self.__cmdObjs.append(QadBREAKCommandClass(self.plugIn)) # BREAK\n self.__cmdObjs.append(QadPEDITCommandClass(self.plugIn)) # PEDIT\n self.__cmdObjs.append(QadFILLETCommandClass(self.plugIn)) # FILLET\n self.__cmdObjs.append(QadPOLYGONCommandClass(self.plugIn)) # POLYGON\n self.__cmdObjs.append(QadDIMLINEARCommandClass(self.plugIn)) # DIMLINEAR\n self.__cmdObjs.append(QadDIMALIGNEDCommandClass(self.plugIn)) # DIMALIGNED\n self.__cmdObjs.append(QadDIMSTYLECommandClass(self.plugIn)) # DIMSTYLE\n self.__cmdObjs.append(QadHELPCommandClass(self.plugIn)) # HELP\n self.__cmdObjs.append(QadLENGTHENCommandClass(self.plugIn)) # LENGTHEN\n \n self.actualCommand = None # Comando in corso di esecuzione\n \n # scarto gli alias che hanno lo stesso nome dei comandi\n exceptionList = []\n for cmdObj in self.__cmdObjs:\n exceptionList.append(cmdObj.getName())\n exceptionList.append(\"_\" + cmdObj.getEnglishName())\n \n # carico alias dei comandi\n self.commandAliases = QadCommandAliasesClass()\n self.commandAliases.load(\"\", exceptionList)\n \n self.usedCmdNames = QadUsedCmdNamesClass()\n \n \n def isValidCommand(self, command):\n cmd = self.getCommandObj(command)\n if cmd:\n del cmd\n return True\n else:\n return False\n\n\n def isValidEnvVariable(self, variable):\n # verifico se è una variabile di sistema\n if QadVariables.get(variable) is not None:\n return True\n else:\n return False\n \n \n def showCommandPrompt(self):\n if self.plugIn is not None:\n self.plugIn.showInputMsg() # visualizza prompt standard per richiesta comando \n \n def showMsg(self, msg, displayPromptAfterMsg = False):\n if self.plugIn is not None:\n self.plugIn.showMsg(msg, displayPromptAfterMsg)\n\n def showErr(self, err):\n if self.plugIn is not None:\n self.plugIn.showErr(err)\n\n\n #============================================================================\n # getCommandObj\n #============================================================================\n def getCommandObj(self, cmdName, useAlias = True):\n if cmdName is None:\n return None\n if cmdName == \"\":\n return None\n upperCommand = cmdName.upper()\n if upperCommand[0] == \"_\":\n englishName = True\n upperCommand = upperCommand[1:] # salto il primo carattere di \"_\"\n else:\n englishName = False \n \n for cmd in self.__cmdObjs:\n if englishName:\n if upperCommand == cmd.getEnglishName(): # in inglese\n return cmd.instantiateNewCmd()\n else:\n if upperCommand == cmd.getName(): # in lingua locale\n return cmd.instantiateNewCmd()\n \n if cmdName == \"MACRO_RUNNER\":\n return QadMacroRunnerCommandClass(self.plugIn)\n else:\n if useAlias:\n command = self.commandAliases.getCommandName(cmdName)\n return self.getCommandObj(command, False)\n else:\n return None\n \n \n #============================================================================\n # getCommandNames\n #============================================================================\n def getCommandNames(self):\n \"\"\" Return a list of pairs : [(<local cmd name>, <english cmd name>)...]\"\"\" \n cmdNames = []\n # ricavo la lista dei nomi dei comandi\n for cmd in self.__cmdObjs:\n cmdNames.append([cmd.getName(), cmd.getEnglishName]) # in lingua locale, in inglese\n # aggiungo gli alias\n for alias in self.commandAliases.getCommandAliasDict().keys():\n cmdNames.append([alias, alias])\n \n return cmdNames\n \n \n #============================================================================\n # run\n #============================================================================\n def run(self, command, param = None):\n # se c'é un comando attivo\n if self.actualCommand is not None:\n return\n\n # eccezione per comando virtuale \"QadVirtualSelCommandClass\" che in realtà non è un comando\n # ma è usato per selezionare oggetti quando nessun comando è attivo\n if command == \"QadVirtualSelCommandClass\":\n self.actualCommand = QadVirtualSelCommandClass(self.plugIn)\n # param è la posizione corrente del mouse\n if self.actualCommand.run(False, param) == True: # comando terminato\n self.clearCommand()\n return\n\n # eccezione per comando virtuale \"QadVirtualGripCommandsClass\" che in realtà non è un comando\n # ma è usato per modificare gli oggetti selezionati da grip points\n if command == \"QadVirtualGripCommandsClass\":\n self.actualCommand = QadVirtualGripCommandsClass(self.plugIn)\n # param è una lista in cui:\n # il primo elemento è il codice del comando da eseguire\n # il secondo elemento è entitySetGripPoints\n # il terzo elemento è il punto del grip corrente\n self.actualCommand.entitySetGripPoints = param[1]\n self.actualCommand.basePt = param[2]\n self.actualCommand.initStartCommand(param[0])\n if self.actualCommand.run(False) == True: # comando terminato\n self.clearCommand()\n return\n \n self.actualCommand = self.getCommandObj(command)\n if self.actualCommand is None:\n # verifico se è una variabile di sistema\n if QadVariables.get(command) is not None:\n self.showMsg(\"\\n\")\n # lancio comando SETVAR per settare la variabile\n args = [QadMsg.translate(\"Command_list\", \"SETVAR\"), command]\n return self.runMacro(args)\n \n msg = QadMsg.translate(\"QAD\", \"\\nInvalid command \\\"{0}\\\".\")\n self.showErr(msg.format(command))\n return\n\n self.usedCmdNames.setUsed(command)\n self.plugIn.clearEntityGripPoints() # pulisco i grip points correnti\n if self.actualCommand.run() == True: # comando terminato\n self.clearCommand()\n \n \n #============================================================================\n # runMacro\n #============================================================================\n def runMacro(self, args):\n # se non c'é alcun comando attivo\n if self.actualCommand is not None:\n return\n \n self.actualCommand = self.getCommandObj(\"MACRO_RUNNER\")\n if self.actualCommand is None:\n msg = QadMsg.translate(\"QAD\", \"\\nInvalid command \\\"{0}\\\".\")\n self.showErr(msg.format(command))\n return\n\n self.plugIn.clearEntityGripPoints() # pulisco i grip points correnti\n self.actualCommand.setCmdAndOptionsToRun(args)\n \n self.showMsg(args[0]) # visualizzo il nome del comando in macro\n if self.actualCommand.run() == True: # comando terminato\n self.clearCommand()\n\n\n #============================================================================\n # continueCommandFromMapTool\n #============================================================================\n def continueCommandFromMapTool(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n msg = None\n # se é stato premuto il tasto destro del mouse valuto cosa é stato inserito nella finestra di testo\n if self.actualCommand.getPointMapTool().rightButton == True:\n msg = self.actualCommand.getCurrMsgFromTxtWindow()\n if (msg is not None) and len(msg) > 0:\n self.actualCommand.showEvaluateMsg()\n else:\n if self.actualCommand.run(True) == True: # comando terminato\n self.clearCommand()\n else:\n if self.actualCommand.run(True) == True: # comando terminato\n self.clearCommand()\n\n\n #============================================================================\n # continueCommandFromTextWindow\n #============================================================================\n def continueCommandFromTextWindow(self, msg):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n if self.actualCommand.run(False, msg) == True: # comando terminato\n self.clearCommand()\n\n \n #============================================================================\n # abortCommand\n #============================================================================\n def abortCommand(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n self.showCommandPrompt() # visualizza prompt standard per richiesta comando \n self.plugIn.setStandardMapTool() \n else:\n self.showMsg(QadMsg.translate(\"QAD\", \"*Canceled*\"))\n self.clearCommand()\n # pulisco le entità selezionate e i grip points correnti\n self.plugIn.clearCurrentObjsSelection()\n\n\n #============================================================================\n # clearCommand\n #============================================================================\n def clearCommand(self):\n if self.actualCommand is None:\n return\n \n # eccezione per comando virtuale \"QadVirtualGripCommandsClass\" che in realtà non è un comando\n # ma è usato per modificare gli oggetti selezionati da grip points\n if self.actualCommand.getName() == \"QadVirtualGripCommandsClass\":\n # ridisegno i grip point nelle nuove posizioni resettando quelli selezionati\n self.plugIn.tool.clearEntityGripPoints()\n self.plugIn.tool.refreshEntityGripPoints()\n else:\n # eccezione per comando virtuale \"QadVirtualSelCommandClass\" che in realtà non è un comando\n # ma è usato per selezionare oggetti quando nessun comando è attivo\n if self.actualCommand.getName() != \"QadVirtualSelCommandClass\":\n qad_utils.deselectAll(self.plugIn.canvas.layers())\n \n del self.actualCommand\n self.actualCommand = None \n self.plugIn.setStandardMapTool()\n self.showCommandPrompt() # visualizza prompt standard per richiesta comando \n\n\n #============================================================================\n # forceCommandMapToolSnapTypeOnce\n #============================================================================\n def forceCommandMapToolSnapTypeOnce(self, snapType, snapParams = None):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n # se non c'é un maptool del comando attuale\n if self.actualCommand.getPointMapTool() is None:\n return\n # se il maptool del comando attuale se non é attivo\n if self.plugIn.canvas.mapTool() != self.actualCommand.getPointMapTool():\n self.actualCommand.setMapTool(self.actualCommand.getPointMapTool())\n self.actualCommand.getPointMapTool().forceSnapTypeOnce(snapType, snapParams)\n\n\n #============================================================================\n # getCurrenPointFromCommandMapTool\n #============================================================================\n def getCurrenPointFromCommandMapTool(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return None\n # se non c'é un maptool del comando attuale\n if self.actualCommand.getPointMapTool() is None:\n return None\n # se il maptool del comando attuale se non é attivo\n if self.plugIn.canvas.mapTool() != self.actualCommand.getPointMapTool():\n self.actualCommand.setMapTool(self.actualCommand.getPointMapTool())\n return self.actualCommand.getPointMapTool().tmpPoint\n \n\n #============================================================================\n # refreshCommandMapToolSnapType\n #============================================================================\n def refreshCommandMapToolSnapType(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n # se non c'é un maptool attivo del comando attuale\n if self.actualCommand.getPointMapTool() is None:\n return\n self.actualCommand.getPointMapTool().refreshSnapType()\n \n \n #============================================================================\n # refreshCommandMapToolOrthoMode\n #============================================================================\n def refreshCommandMapToolOrthoMode(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n # se non c'é un maptool attivo del comando attuale\n if self.actualCommand.getPointMapTool() is None:\n return\n self.actualCommand.getPointMapTool().refreshOrthoMode()\n \n \n #============================================================================\n # refreshCommandMapToolAutoSnap\n #============================================================================\n def refreshCommandMapToolAutoSnap(self):\n # se non c'é alcun comando attivo\n if self.actualCommand is None:\n return\n # se non c'é un maptool attivo del comando attuale\n if self.actualCommand.getPointMapTool() is None:\n return\n self.actualCommand.getPointMapTool().refreshAutoSnap()\n\n\n\n #============================================================================\n # getMoreUsedCmd\n #============================================================================\n def getMoreUsedCmd(self, filter):\n upperFilter = filter.upper()\n cmdName, qty = self.usedCmdNames.getMoreUsed(upperFilter)\n if cmdName == \"\": # nessun comando\n if upperFilter[0] == \"_\":\n englishName = True\n upperFilter = upperFilter[1:] # salto il primo carattere di \"_\"\n else:\n englishName = False \n \n for cmd in self.__cmdObjs:\n if englishName:\n if cmd.getEnglishName().startswith(upperFilter): # in inglese\n return cmd.getEnglishName(), 0\n else:\n if cmd.getName().startswith(upperFilter): # in lingua locale\n return cmd.getName(), 0\n return cmdName, 0\n\n\n#===============================================================================\n# QadMacroRunnerCommandClass\n#===============================================================================\nclass QadMacroRunnerCommandClass(QadCommandClass):\n # Classe che gestisce l'esecuzione di altri comandi\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadMacroRunnerCommandClass(self.plugIn)\n\n def getName(self):\n if self.command is None:\n return \"MACRO_RUNNER\"\n else:\n return self.command.getName()\n\n def getEnglishName(self):\n return \"MACRO_RUNNER\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runREDOCommand)\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.command = None\n self.args = [] # lista degli argomenti\n self.argsIndex = -1\n\n def __del__(self):\n QadCommandClass.__del__(self)\n if self.command is not None:\n del self.command\n\n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.command is not None:\n return self.command.getPointMapTool(drawMode)\n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n\n def setCmdAndOptionsToRun(self, CmdAndArglist):\n # primo eleemto della lista = nome comando\n # gli altri elementi sono gli argomenti del comando None = input dell'utente\n cmdName = CmdAndArglist[0]\n self.args = CmdAndArglist[1:] # copio la lista saltando il primo elemento\n \n self.command = self.plugIn.getCommandObj(cmdName)\n\n if self.command is None:\n msg = QadMsg.translate(\"QAD\", \"\\nInvalid command \\\"{0}\\\".\")\n self.showErr(msg.format(command))\n return False\n self.plugIn.updateHistoryfromTxtWindow(cmdName)\n return True\n \n def run(self, msgMapTool = False, msg = None):\n \n if self.command.run(msgMapTool, msg) == True:\n return True\n \n # se l'input precedente era valido\n if self.command.isValidPreviousInput == True:\n # al comando passo la prossima opzione\n self.argsIndex = self.argsIndex + 1\n if self.argsIndex < len(self.args):\n arg = self.args[self.argsIndex]\n if arg is not None:\n self.showEvaluateMsg(arg)\n\n return False\n\n\n#===============================================================================\n# QadUsedCmdNamesClass usata per contare quante volte sono stati usati i comandi\n#===============================================================================\n\n\nclass QadUsedCmdNamesClass():\n def __init__(self):\n self.__nUsedCmdNames = [] # lista interna di item composti da (nome comando o alias, n. di volte che è stato usato)\n\n def __del__(self):\n del self.__nUsedCmdNames[:]\n\n\n def setUsed(self, cmdName):\n uName = cmdName.upper()\n for _cmdName in self.__nUsedCmdNames:\n if _cmdName[0] == uName:\n _cmdName[1] = _cmdName[1] + 1\n return _cmdName[1]\n\n self.__nUsedCmdNames.append([uName, 1])\n return 1\n\n\n def getUsed(self, cmdName):\n uName = cmdName.upper()\n for _cmdName in self.__nUsedCmdNames:\n if _cmdName[0] == uName:\n return _cmdName[1]\n\n return 0\n \n def getMoreUsed(self, filter):\n moreUsedCmd = \"\"\n nUsedCmd = 0\n for _cmdName in self.__nUsedCmdNames:\n if _cmdName[0].startswith(filter):\n if _cmdName[1] > nUsedCmd:\n moreUsedCmd = _cmdName[0]\n nUsedCmd = _cmdName[1]\n\n return moreUsedCmd, nUsedCmd"
},
{
"alpha_fraction": 0.5613096952438354,
"alphanum_fraction": 0.5639826059341431,
"avg_line_length": 43.40652847290039,
"blob_id": "3ad9a197b86869649bc9dc158cd248d3cb6d9e9f",
"content_id": "69d4a9d6d8d70fcb5161e2c171f2b77ac4794a28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14987,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 337,
"path": "/qad_stretch_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando stretch\n \n -------------------\n begin : 2014-01-08\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_dim import *\nimport qad_stretch_fun\nfrom qad_highlight import QadHighlight\n\n\n#===============================================================================\n# Qad_stretch_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_stretch_maptool_ModeEnum():\n # si richiede la selezione del primo punto del rettangolo per selezionare gli oggetti\n ASK_FOR_FIRST_PT_RECTANGLE = 1\n # noto niente il primo punto del rettangolo si richiede il secondo punto\n FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_RECTANGLE = 2 \n # noto niente si richiede il punto base\n NONE_KNOWN_ASK_FOR_BASE_PT = 3\n # noto il punto base si richiede il secondo punto per lo spostamento\n BASE_PT_KNOWN_ASK_FOR_MOVE_PT = 4 \n\n\n#===============================================================================\n# Qad_stretch_maptool class\n#===============================================================================\nclass Qad_stretch_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.basePt = None\n self.SSGeomList = [] # lista di entità da stirare con geom di selezione\n self.__highlight = QadHighlight(self.canvas)\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None \n \n \n #============================================================================\n # stretch\n #============================================================================\n def stretch(self, entity, containerGeom, offSetX, offSetY, tolerance2ApproxCurve):\n # entity = entità da stirare\n # ptList = lista dei punti da stirare\n # offSetX, offSetY = spostamento da fare\n # tolerance2ApproxCurve = tolleranza per ricreare le curve\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.whatIs() == \"ENTITY\":\n stretchedGeom = entity.getGeometry()\n # controllo inserito perchè con le quote, questa viene cancellata e ricreata quindi alcuni oggetti potrebbero non esistere più\n if stretchedGeom is None: # se non c'è lo salto senza errore\n return True\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(entity.layer.crs(), self.canvas.mapRenderer().destinationCrs())\n stretchedGeom.transform(coordTransform) \n # stiro la feature\n stretchedGeom = qad_stretch_fun.stretchQgsGeometry(stretchedGeom, containerGeom, \\\n offSetX, offSetY, \\\n tolerance2ApproxCurve)\n \n if stretchedGeom is not None:\n # trasformo la geometria nel crs del layer\n coordTransform = QgsCoordinateTransform(self.canvas.mapRenderer().destinationCrs(), entity.layer.crs())\n stretchedGeom.transform(coordTransform)\n self.__highlight.addGeometry(stretchedGeom, entity.layer)\n\n elif entity.whatIs() == \"DIMENTITY\":\n # stiro la quota\n entity.stretch(self.plugIn, containerGeom, offSetX, offSetY)\n self.__highlight.addGeometry(entity.textualFeature.geometry(), entity.getTextualLayer())\n self.__highlight.addGeometries(entity.getLinearGeometryCollection(), entity.getLinearLayer())\n self.__highlight.addGeometries(entity.getSymbolGeometryCollection(), entity.getSymbolLayer())\n \n return True\n\n\n #============================================================================\n # addStretchedGeometries\n #============================================================================\n def addStretchedGeometries(self, newPt):\n self.__highlight.reset() \n\n dimElaboratedList = [] # lista delle quotature già elaborate\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n offSetX = newPt.x() - self.basePt.x()\n offSetY = newPt.y() - self.basePt.y()\n\n entity = QadEntity()\n for SSGeom in self.SSGeomList:\n # copio entitySet\n entitySet = QadEntitySet(SSGeom[0])\n geomSel = SSGeom[1]\n\n for layerEntitySet in entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n\n for featureId in layerEntitySet.featureIds:\n entity.set(layer, featureId)\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimEntity = QadDimStyles.getDimEntity(entity)\n if dimEntity is None: \n self.stretch(entity, geomSel, offSetX, offSetY, tolerance2ApproxCurve)\n else:\n found = False\n for dimElaborated in dimElaboratedList:\n if dimElaborated == dimEntity:\n found = True\n \n if found == False: # quota non ancora elaborata\n dimElaboratedList.append(dimEntity)\n self.stretch(dimEntity, geomSel, offSetX, offSetY, tolerance2ApproxCurve)\n\n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n # noto il punto base si richiede il secondo punto per l'angolo di rotazione\n if self.mode == Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT:\n self.addStretchedGeometries(self.tmpPoint) \n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__highlight.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n \n # si richiede la selezione del primo punto del rettangolo per selezionare gli oggetti\n if self.mode == Qad_stretch_maptool_ModeEnum.ASK_FOR_FIRST_PT_RECTANGLE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE) \n # noto niente il primo punto del rettangolo si richiede il secondo punto\n elif self.mode == Qad_stretch_maptool_ModeEnum.FIRST_PT_KNOWN_ASK_FOR_SECOND_PT_RECTANGLE:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_RECTANGLE) \n # noto niente si richiede il punto base\n elif self.mode == Qad_stretch_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il punto base si richiede il secondo punto\n elif self.mode == Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.basePt)\n\n\n#===============================================================================\n# Qad_gripStretch_maptool class\n#===============================================================================\nclass Qad_gripStretch_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.basePt = None\n self.selectedEntityGripPoints = [] # lista in cui ogni elemento è una entità + una lista di punti da stirare\n self.__highlight = QadHighlight(self.canvas)\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None\n\n\n #============================================================================\n # getSelectedEntityGripPointNdx\n #============================================================================\n def getSelectedEntityGripPointNdx(self, entity):\n # lista delle entityGripPoint con dei grip point selezionati\n # cerca la posizione di un'entità nella lista in cui ogni elemento è una entità + una lista di punti da stirare\n i = 0\n tot = len(self.selectedEntityGripPoints)\n while i < tot:\n selectedEntityGripPoint = self.selectedEntityGripPoints[i]\n if selectedEntityGripPoint[0] == entity:\n return i\n i = i + 1\n return -1\n \n \n #============================================================================\n # stretch\n #============================================================================\n def stretch(self, entity, ptList, offSetX, offSetY, tolerance2ApproxCurve):\n # entity = entità da stirare\n # ptList = lista dei punti da stirare\n # offSetX, offSetY = spostamento da fare\n # tolerance2ApproxCurve = tolleranza per ricreare le curve\n # entitySet = gruppo di selezione delle entità da stirare\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.whatIs() == \"ENTITY\":\n stretchedGeom = entity.gripGeomStretch(self.basePt, ptList, offSetX, offSetY, tolerance2ApproxCurve)\n\n if stretchedGeom is not None:\n self.__highlight.addGeometry(stretchedGeom, entity.layer)\n elif entity.whatIs() == \"DIMENTITY\":\n # stiro la quota\n entity.stretch(self.plugIn, ptList, offSetX, offSetY)\n self.__highlight.addGeometry(entity.textualFeature.geometry(), entity.getTextualLayer())\n self.__highlight.addGeometries(entity.getLinearGeometryCollection(), entity.getLinearLayer())\n self.__highlight.addGeometries(entity.getSymbolGeometryCollection(), entity.getSymbolLayer())\n\n \n #============================================================================\n # addStretchedGeometries\n #============================================================================\n def addStretchedGeometries(self, newPt):\n self.__highlight.reset()\n\n dimElaboratedList = [] # lista delle quotature già elaborate\n\n for selectedEntity in self.selectedEntityGripPoints:\n entity = selectedEntity[0]\n ptList = selectedEntity[1]\n layer = entity.layer\n\n tolerance2ApproxCurve = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n offSetX = newPt.x() - self.basePt.x()\n offSetY = newPt.y() - self.basePt.y()\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n if entity.isDimensionComponent() == False:\n self.stretch(entity, ptList, offSetX, offSetY, tolerance2ApproxCurve)\n else:\n dimEntity = QadDimEntity()\n if dimEntity.initByDimId(entity.dimStyle, entity.dimId):\n found = False\n for dimElaborated in dimElaboratedList:\n if dimElaborated == dimEntity:\n found = True\n if found == False: # quota non ancora elaborata\n dimEntitySet = dimEntity.getEntitySet()\n # creo un'unica lista contenente i grip points di tutti i componenti della quota\n dimPtlist = []\n for layerEntitySet in dimEntitySet.layerEntitySetList:\n for featureId in layerEntitySet.featureIds:\n componentDim = QadEntity()\n componentDim.set(layerEntitySet.layer, featureId)\n i = self.getSelectedEntityGripPointNdx(componentDim)\n if i >= 0:\n dimPtlist.extend(self.selectedEntityGripPoints[i][1])\n \n dimElaboratedList.append(dimEntity)\n self.stretch(dimEntity, dimPtlist, offSetX, offSetY, tolerance2ApproxCurve)\n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n # noto il punto base si richiede il secondo punto per l'angolo di rotazione\n if self.mode == Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT:\n self.addStretchedGeometries(self.tmpPoint) \n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__highlight.show()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n \n # noto niente si richiede il punto base\n if self.mode == Qad_stretch_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_BASE_PT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.__highlight.reset() \n # noto il punto base si richiede il secondo punto\n elif self.mode == Qad_stretch_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_MOVE_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.basePt)\n"
},
{
"alpha_fraction": 0.5507481098175049,
"alphanum_fraction": 0.5619187951087952,
"avg_line_length": 41.21323013305664,
"blob_id": "0dca39cfdf9129fef7a2def1eabbb46510e3e55d",
"content_id": "e4b40c81975d643f4a33acd0ef73ca1aa56d11f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 397373,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 9403,
"path": "/qad_utils.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n funzioni varie di utilità\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n#from qgis.utils import *\nimport qgis.utils\n\n\nimport math\nimport sys\nimport string\nfrom ctypes import *\nimport ConfigParser\nimport time\n\n\nfrom qad_variables import *\nfrom qad_snapper import *\nfrom qad_msg import QadMsg\nfrom qad_circle import *\nfrom qad_arc import *\nfrom qad_entity import *\n\n\n# Modulo che gestisce varie funzionalità di Qad\n\n\n#===============================================================================\n# TOLERANCE = variabile globale\n#===============================================================================\nTOLERANCE = 1.e-7\n\n\n#===============================================================================\n# isNumericField\n#===============================================================================\ndef isNumericField(field):\n \"\"\"\n La funzione verifica che il campo di tipo QgsField sia numerico\n \"\"\"\n fldType = field.type()\n if fldType == QVariant.Double or fldType == QVariant.LongLong or fldType == QVariant.Int or \\\n fldType == QVariant.ULongLong or fldType == QVariant.UInt:\n return True\n else:\n return False\n\n\n#===============================================================================\n# checkUniqueNewName\n#===============================================================================\ndef checkUniqueNewName(newName, nameList, prefix = None, suffix = None, caseSensitive = True):\n \"\"\"\n La funzione verifica che il nuovo nome non esistà già nella lista <nameList>.\n Se nella lista dovesse già esistere allora aggiunge un prefisso (se <> None) o un suffisso (se <> None)\n finchè il nome non è più presnete nella lista\n \"\"\"\n ok = False\n result = newName \n while ok == False:\n ok = True\n for name in nameList:\n if caseSensitive == True:\n if name == result:\n ok = False\n break\n else:\n if name.upper() == result.upper():\n ok = False\n break\n \n if ok == True:\n return result\n if prefix is not None:\n result = prefix + result\n else:\n if suffix is not None:\n result = result + suffix\n \n return None\n\n#===============================================================================\n# wildCard2regularExpr\n#===============================================================================\ndef wildCard2regularExpr(wildCard, ignoreCase = True):\n \"\"\"\n Ritorna la conversione di una stringa con wildcards (es. \"gas*\")\n in forma di regular expression (es. \"[g][a][s].*\")\n \"\"\"\n # ? -> .\n # * -> .*\n # altri caratteri -> [carattere]\n regularExpr = \"\" \n for ch in wildCard:\n if ch == \"?\":\n regularExpr = regularExpr + \".\"\n elif ch == \"*\":\n regularExpr = regularExpr + \".*\"\n else:\n if ignoreCase:\n regularExpr = regularExpr + \"[\" + ch.upper() + ch.lower() + \"]\"\n else:\n regularExpr = regularExpr + \"[\" + ch + \"]\" \n\n return regularExpr\n\n\n#===============================================================================\n# str2float\n#===============================================================================\ndef str2float(s):\n \"\"\"\n Ritorna la conversione di una stringa in numero reale\n \"\"\" \n try:\n n = float(s)\n return n\n except ValueError:\n return None\n\n\n#===============================================================================\n# str2long\n#===============================================================================\ndef str2long(s):\n \"\"\"\n Ritorna la conversione di una stringa in numero lungo\n \"\"\" \n try:\n n = long(s)\n return n\n except ValueError:\n return None\n\n\n#===============================================================================\n# str2int\n#===============================================================================\ndef str2int(s):\n \"\"\"\n Ritorna la conversione di una stringa in numero intero\n \"\"\" \n try:\n n = int(s)\n return n\n except ValueError:\n return None\n\n\n#===============================================================================\n# str2bool\n#===============================================================================\ndef str2bool(s):\n \"\"\"\n Ritorna la conversione di una stringa in bool\n \"\"\" \n try:\n upperS = s.upper()\n # 16 = \"N\", 17 = \"NO\"\n # \"F\" \"FALSO\" \n if upperS == \"0\" or \\\n upperS == QadMsg.translate(\"QAD\", \"N\") or \\\n upperS == QadMsg.translate(\"QAD\", \"NO\") or \\\n upperS == QadMsg.translate(\"QAD\", \"F\") or \\\n upperS == QadMsg.translate(\"QAD\", \"FALSE\"):\n return False\n else:\n return True\n except ValueError:\n return None\n\n\n#===============================================================================\n# str2QgsPoint\n#===============================================================================\ndef str2QgsPoint(s, lastPoint = None, currenPoint = None, oneNumberAllowed = True):\n \"\"\"\n Ritorna la conversione di una stringa in punto QgsPoint\n se <oneNumberAllowed> = False significa che s non può essere un solo numero\n che rappresenterebbe la distanza dall'ultimo punto con angolo in base al punto corrente\n (questo viene vietato quando si vuole accettare un numero o un punto)\n lastPoint viene usato solo per le espressioni tipo @10<45 (dall'ultimo punto, lunghezza 10, angolo 45 gradi)\n o @ (dall'ultimo punto)\n o @10,20 (dall'ultimo punto, + 10 per la X e + 20 per la Y)\n o 100 (dall'ultimo punto, distanza 100, angolo in base al punto corrente)\n \"\"\" \n expression = s.strip() # senza spazi iniziali e finali\n if len(expression) == 0:\n return None\n\n if expression[0] == \"@\": # coordinate relative a lastpoint\n if lastPoint is None:\n return None\n \n if len(expression) == 1:\n return lastPoint\n \n expression = expression[1:] # scarto il primo carattere \"@\"\n coords = expression.split(\",\")\n if len(coords) == 2:\n OffSetX = str2float(coords[0].strip())\n OffSetY = str2float(coords[1].strip())\n if (OffSetX is None) or (OffSetY is None):\n return None\n return QgsPoint(lastPoint.x() + OffSetX, lastPoint.y() + OffSetY)\n else:\n if len(coords) != 1:\n return None\n # verifico se si sta usando la coordinata polare\n expression = coords[0].strip()\n values = expression.split(\"<\")\n if len(values) != 2: \n return None\n dist = str2float(values[0].strip())\n angle = str2float(values[1].strip())\n if (dist is None) or (angle is None):\n return None \n coords = getPolarPointByPtAngle(lastPoint, math.radians(angle), dist) \n return QgsPoint(coords[0], coords[1])\n else:\n # verifico se è specificato un CRS\n CRS, newExpr = strFindCRS(expression)\n if CRS is not None:\n if CRS.geographicFlag():\n pt = strLatLon2QgsPoint(newExpr)\n else: \n coords = newExpr.split(\",\")\n if len(coords) != 2:\n return None\n x = str2float(coords[0].strip())\n y = str2float(coords[1].strip())\n if (x is None) or (y is None):\n return None\n pt = QgsPoint(x, y)\n \n if pt is not None:\n destCRS = qgis.utils.iface.mapCanvas().mapRenderer().destinationCrs() # CRS corrente\n return QgsCoordinateTransform(CRS, destCRS).transform(pt) # trasformo le coord\n\n\n coords = expression.split(\",\")\n if len(coords) == 2: # coordinate assolute\n x = str2float(coords[0].strip())\n y = str2float(coords[1].strip())\n if (x is None) or (y is None):\n return None\n return QgsPoint(x, y)\n else:\n if oneNumberAllowed == False: # vietato che la stringa sia un solo numero\n return None\n \n dist = str2float(expression)\n\n if (dist is None) or (lastPoint is None) or (currenPoint is None):\n return None\n \n angle = getAngleBy2Pts(lastPoint, currenPoint)\n coords = getPolarPointByPtAngle(lastPoint, angle, dist) \n return QgsPoint(coords[0], coords[1])\n\n#===============================================================================\n# strLatLon2QgsPoint\n#===============================================================================\ndef strFindCRS(s):\n \"\"\"\n Cerca il sistema di coordinate in una stringa indicante un punto (usa authid).\n Il sistema di coordinate va espresso in qualsiasi punto della stringa e deve essere\n racchiuso tra parentesi tonde (es \"111,222 (EPSG:3003)\")\n Ritorna il SR e la stringa depurata del SR (es \"111,222\")\n \"\"\"\n initial = string.find(s, \"(\")\n if initial == -1:\n return None, s\n final = string.find(s, \")\")\n if initial > final:\n return None, s\n authId = s[initial+1:final]\n authId = authId.strip() # senza spazi iniziali e finali\n return QgsCoordinateReferenceSystem(authId), s.replace(s[initial:final+1], \"\")\n\n\n#===============================================================================\n# strLatLon2QgsPoint\n#===============================================================================\ndef strLatLon2QgsPoint(s):\n \"\"\"\n Ritorna la conversione di una stringa contenente una coordinata in latitudine longitudine\n in punto QgsPoint.\n \n Sono supportati i seguenti formati:\n DDD gradi decimali (49.11675S o S49.11675 o 49.11675 S o S 49.11675 o -49.1167)\n DMS gradi minuti secondi (49 7 20.06)\n DMM gradi minuti con secondi decimali (49 7.0055)\n \n Sintassi latitudine longitudine:\n Il separatore può essere uno spazio, puoi anche usare ' per i minuti e \" per i secondi (47 7'20.06\")\n La notazione di direzione è N, S, E, W maiuscolo o minuscolo prima o dopo la coordinata\n (\"N 37 24 23.3\" o \"N37 24 23.3\" o \"37 24 23.3 N\" o \"37 24 23.3N\")\n Puoi usare anche le coordinate negative per l'ovest e il sud.\n \n La prima coordinata viene interpretata come latitudine a meno che specifichi una lettera di direzione (E o W)\n (\"122 05 08.40 W 37 25 19.07 N\")\n Puoi usare uno spazio, una virgola o una barra per delimitare le coppie di valori\n (\"37.7 N 122.2 W\" o \"37.7 N,122.2 W\" o \"37.7 N/122.2 W\") \n \"\"\"\n expression = s.strip() # senza spazi iniziali e finali\n if len(expression) == 0:\n return None\n \n numbers = []\n directions = []\n word = \"\"\n for ch in s:\n if ch.isnumeric() or ch == \".\" or ch == \"-\":\n word += ch\n else:\n if len(word) > 0:\n n = str2float(word)\n if n is None:\n return None\n numbers.append(n)\n word = \"\"\n if ch == \"N\" or ch == \"n\" or ch == \"S\" or ch == \"s\" or ch == \"E\" or ch == \"e\" or ch == \"W\" or ch == \"w\":\n directions.append(ch.upper())\n word = \"\"\n\n directions_len = len(directions)\n if directions_len != 0 and directions_len != 2:\n return None\n\n numbers_len = len(numbers)\n if numbers_len == 2: # DDD\n lat = numbers[0]\n lon = numbers[1]\n elif numbers_len == 4: # DMM \n degrees = numbers[0]\n minutes = numbers[1]\n lat = degrees + minutes / 60\n degrees = numbers[2]\n minutes = numbers[3]\n lon = degrees + minutes / 60\n elif numbers_len == 6: # DMS\n degrees = numbers[0]\n minutes = numbers[1]\n seconds = numbers[2]\n lat = degrees + minutes / 60 + seconds / 3600\n degrees = numbers[3]\n minutes = numbers[4]\n seconds = numbers[5]\n lon = degrees + minutes / 60 + seconds / 3600\n else:\n return None\n \n if directions_len == 2:\n if lat < 0 or lon < 0:\n return None\n if directions[0] == \"N\" or directions[0] == \"S\": # latitude first\n if directions[0] == \"S\":\n lat = -lat\n elif directions[0] == \"E\" or directions[0] == \"W\": # longitude first\n dummy = lat\n lat = lon if directions[0] == \"E\" else -lon\n lon = dummy if directions[1] == \"S\" else -value2\n else:\n return None\n \n return QgsPoint(lon, lat)\n else: # latitude first\n return QgsPoint(lon, lat)\n\n\n#===============================================================================\n# str2snapTypeEnum\n#===============================================================================\ndef str2snapTypeEnum(s):\n \"\"\"\n Ritorna la conversione di una stringa in una combinazione di tipi di snap\n oppure -1 se non ci sono snap indicati.\n \"\"\"\n snapType = QadSnapTypeEnum.NONE\n snapTypeStrList = s.strip().split(\",\")\n for snapTypeStr in snapTypeStrList:\n snapTypeStr = snapTypeStr.strip().upper()\n \n # \"NES\" nessuno snap\n if snapTypeStr == QadMsg.translate(\"Snap\", \"NONE\") or snapTypeStr == \"_NONE\":\n return QadSnapTypeEnum.NONE\n # \"FIN\" punti finali di ogni segmento\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"END\") or snapTypeStr == \"_END\":\n snapType = snapType | QadSnapTypeEnum.END\n # \"FIN_PL\" punti finali dell'intera polilinea\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"END_PL\") or snapTypeStr == \"_END_PL\":\n snapType = snapType | QadSnapTypeEnum.END_PLINE\n # \"MED\" punto medio\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"MID\") or snapTypeStr == \"_MID\":\n snapType = snapType | QadSnapTypeEnum.MID\n # \"CEN\" centro (centroide)\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"CEN\") or snapTypeStr == \"_CEN\":\n snapType = snapType | QadSnapTypeEnum.CEN\n # \"NOD\" oggetto punto\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"NOD\") or snapTypeStr == \"_NOD\":\n snapType = snapType | QadSnapTypeEnum.NOD\n # \"QUA\" punto quadrante\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"QUA\") or snapTypeStr == \"_QUA\":\n snapType = snapType | QadSnapTypeEnum.QUA\n # \"INT\" intersezione\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"INT\") or snapTypeStr == \"_INT\":\n snapType = snapType | QadSnapTypeEnum.INT\n # \"INS\" punto di inserimento\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"INS\") or snapTypeStr == \"_INS\":\n snapType = snapType | QadSnapTypeEnum.INS\n # \"PER\" punto perpendicolare\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"PER\") or snapTypeStr == \"_PER\":\n snapType = snapType | QadSnapTypeEnum.PER\n # \"TAN\" tangente\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"TAN\") or snapTypeStr == \"_TAN\":\n snapType = snapType | QadSnapTypeEnum.TAN\n # \"VIC\" punto più vicino\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"NEA\") or snapTypeStr == \"_NEA\":\n snapType = snapType | QadSnapTypeEnum.NEA\n # \"APP\" intersezione apparente\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"APP\") or snapTypeStr == \"_APP\":\n snapType = snapType | QadSnapTypeEnum.APP\n # \"EST\" Estensione\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"EXT\") or snapTypeStr == \"_EXT\":\n snapType = snapType | QadSnapTypeEnum.EXT\n # \"PAR\" Parallelo\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"PAR\") or snapTypeStr == \"_PAR\":\n snapType = snapType | QadSnapTypeEnum.PAR \n # se inizia per \"PR\" distanza progressiva\n elif string.find(snapTypeStr, QadMsg.translate(\"Snap\", \"PR\")) == 0 or \\\n string.find(snapTypeStr, \"_PR\") == 0:\n # la parte successiva PR può essere vuota o numerica\n if string.find(snapTypeStr, QadMsg.translate(\"Snap\", \"PR\")) == 0:\n param = snapTypeStr[len(QadMsg.translate(\"Snap\", \"PR\")):]\n else:\n param = snapTypeStr[len(\"_PR\"):]\n if len(param) == 0 or str2float(param) is not None:\n snapType = snapType | QadSnapTypeEnum.PR\n # \"EST_INT\" intersezione su estensione\n elif snapTypeStr == QadMsg.translate(\"Snap\", \"EXT_INT\") or snapTypeStr == \"_EXT_INT\":\n snapType = snapType | QadSnapTypeEnum.EXT_INT\n \n return snapType if snapType != QadSnapTypeEnum.NONE else -1\n\n\n#===============================================================================\n# str2snapParam\n#===============================================================================\ndef str2snapParams(s):\n \"\"\"\n Ritorna la conversione di una stringa in una lista di parametri per i tipi di snap\n \"\"\"\n params = []\n snapTypeStrList = s.strip().split(\",\")\n for snapTypeStr in snapTypeStrList:\n snapTypeStr = snapTypeStr.strip().upper()\n # se inizia per \"PR\" distanza progressiva\n if string.find(snapTypeStr, QadMsg.translate(\"Snap\", \"PR\")) == 0 or \\\n string.find(snapTypeStr, \"_PR\") == 0:\n # la parte successiva PR può essere vuota o numerica\n if string.find(snapTypeStr, QadMsg.translate(\"Snap\", \"PR\")) == 0:\n param = str2float(snapTypeStr[len(QadMsg.translate(\"Snap\", \"PR\")):]) # fino alla fine della stringa\n else:\n param = str2float(snapTypeStr[len(\"_PR\"):]) # fino alla fine della stringa\n if param is not None:\n params.append([QadSnapTypeEnum.PR, param]) \n\n return params\n\n\n#===============================================================================\n# strip\n#===============================================================================\ndef strip(s, stripList):\n \"\"\"\n Rimuove dalla stringa <s> tutte le stringhe nella lista <stripList> che sono \n all'inizio e anche alla fine della stringa <s>\n \"\"\"\n for item in stripList:\n s = s.strip(item) # rimuovo prima e dopo\n return s\n\n\n#===============================================================================\n# findFile\n#===============================================================================\ndef findFile(fileName):\n \"\"\"\n Cerca il file indicato usando i percorsi indicati dalla variabile \"SUPPORTPATH\" \n più il percorso locale di QAD. Ritorna il percorso del file in caso di successo\n oppure \"\" in caso di file non trovato\n \"\"\"\n path = QadVariables.get(QadMsg.translate(\"Environment variables\", \"SUPPORTPATH\"))\n if len(path) > 0:\n path += \";\" \n path += QgsApplication.qgisSettingsDirPath() + \"python/plugins/qad/\"\n # lista di directory separate da \";\"\n dirList = path.strip().split(\";\")\n for _dir in dirList:\n _dir = QDir.cleanPath(_dir)\n if _dir != \"\":\n if _dir.endswith(\"/\") == False:\n _dir = _dir + \"/\"\n _dir = _dir + fileName\n \n if os.path.exists(_dir):\n return _dir\n\n return \"\"\n\n\n#===============================================================================\n# toRadians\n#===============================================================================\ndef toRadians(angle):\n \"\"\"\n Converte da gradi a radianti\n \"\"\"\n return math.radians(angle)\n\n\n#===============================================================================\n# toDegrees\n#===============================================================================\ndef toDegrees(angle):\n \"\"\"\n Converte da radianti a gradi \n \"\"\"\n return math.degrees(angle)\n\n\n#===============================================================================\n# normalizeAngle\n#===============================================================================\ndef normalizeAngle(angle, norm = math.pi * 2):\n \"\"\"\n Normalizza un angolo a da [0 - 2pi] o da [0 - pi].\n Così, ad esempio, se un angolo é più grande di 2pi viene ridotto all'angolo giusto \n (il raffronto in gradi sarebbe da 380 a 20 gradi) o se é negativo diventa positivo\n (il raffronto in gradi sarebbe da -90 a 270 gradi) \n \"\"\"\n if angle == 0:\n return 0\n if angle > 0:\n return angle % norm\n else:\n return norm - ((-angle) % norm)\n\n\n#===============================================================================\n# getStrIntDecParts\n#===============================================================================\ndef getStrIntDecParts(n):\n \"\"\"\n Restituisce due stringhe rappresentanti la parte intera senza segno e la parte decimale di un numero\n \"\"\"\n if type(n) == int or type(n) == float:\n nStr = str(n)\n if \".\" in nStr:\n parts = nStr.split(\".\")\n return str(abs(int(parts[0]))), parts[1]\n else:\n return n, 0\n else:\n return None\n \n\n\n\n#===============================================================================\n# distMapToLayerCoordinates\n#===============================================================================\ndef distMapToLayerCoordinates(dist, canvas, layer):\n # trovo il punto centrale dello schermo \n boundBox = canvas.extent()\n x = (boundBox.xMinimum() + boundBox.xMaximum()) / 2\n y = (boundBox.yMinimum() + boundBox.yMaximum()) / 2\n pt1 = QgsPoint(x, y)\n pt2 = QgsPoint(x + dist, y)\n transformedPt1 = canvas.mapRenderer().mapToLayerCoordinates(layer, pt1)\n transformedPt2 = canvas.mapRenderer().mapToLayerCoordinates(layer, pt2)\n return getDistance(transformedPt1, transformedPt2)\n \n\n#===============================================================================\n# filterFeaturesByType\n#===============================================================================\ndef filterFeaturesByType(features, filterByGeomType):\n \"\"\"\n Riceve una lista di features e la tipologia di geometria che deve essere filtrata.\n La funzine modifica la lista <features> depurandola dalle geometrie di tipo diverso\n da <filterByGeomType>. \n Restituisce 3 liste rispettivamente di punti, linee e poligoni.\n La lista del tipo indicato dal parametro <filterByGeomType> sarà vuota, le altre\n due liste conterranno geometrie.\n \"\"\"\n resultPoint = []\n resultLine = []\n resultPolygon = []\n\n for i in xrange(len(features) - 1, -1, -1): \n f = features[i]\n g = f.geometry()\n geomType = g.type()\n if geomType != filterByGeomType: \n if geomType == QGis.Point: \n resultPoint.append(QgsGeometry(g))\n elif geomType == QGis.Line: \n resultLine.append(QgsGeometry(g))\n elif geomType == QGis.Polygon: \n resultPolygon.append(QgsGeometry(g))\n del features[i]\n\n return resultPoint, resultLine, resultPolygon\n \n\n#===============================================================================\n# filterGeomsByType\n#===============================================================================\ndef filterGeomsByType(geoms, filterByGeomType):\n \"\"\"\n Riceve una lista di geometrie e la tipologia di geometria che deve essere filtrata.\n La funzine modifica la lista <geoms> depurandola dalle geometrie di tipo diverso\n da <filterByGeomType>. \n Restituisce 3 liste rispettivamente di punti, linee e poligoni.\n La lista del tipo indicato dal parametro <filterByGeomType> sarà vuota, le altre\n due liste conterranno geometrie.\n \"\"\"\n resultPoint = []\n resultLine = []\n resultPolygon = []\n\n for i in xrange(len(geoms) - 1, -1, -1): \n g = geoms[i]\n geomType = g.type()\n if geomType != filterByGeomType: \n if geomType == QGis.Point: \n resultPoint.append(QgsGeometry(g))\n elif geomType == QGis.Line: \n resultLine.append(QgsGeometry(g))\n elif geomType == QGis.Polygon: \n resultPolygon.append(QgsGeometry(g))\n del geoms[i]\n\n return resultPoint, resultLine, resultPolygon\n\n\n#===============================================================================\n# getEntSelCursor\n#===============================================================================\ndef getEntSelCursor():\n \"\"\"\n Ritorna l'immagine del cursore per la selezione di un'entità\n \"\"\"\n \n size = 1 + QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) * 2\n # <width/cols> <height/rows> <colors> <char on pixel>\n row = str(size) + \" \" + str(size) + \" 2 1\"\n xpm = [row]\n # <Colors> \n xpm.append(\" c None\")\n xpm.append(\"+ c \" + QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOXCOLOR\")))\n # <Pixels>\n # es . \"+++++\",\n # es . \"+ +\",\n # es . \"+ +\",\n # es . \"+ +\",\n # es . \"+++++\",\n xpm.append(\"+\" * size)\n if size > 1:\n row = \"+\" + \" \" * (size - 2) + \"+\"\n for i in range(size - 2): # da 0\n xpm.append(row)\n xpm.append(\"+\" * size)\n \n return QCursor(QPixmap(xpm))\n\n\ndef getGetPointCursor():\n \"\"\"\n Ritorna l'immagine del cursore per la selezione di un punto \n \"\"\"\n pickBox = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CURSORSIZE\"))\n size = 1 + pickBox * 2\n # <width/cols> <height/rows> <colors> <char on pixel>\n row = str(size) + \" \" + str(size) + \" 2 1\"\n xpm = [row]\n # <Colors> \n xpm.append(\" c None\")\n xpm.append(\"+ c \" + QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOXCOLOR\")))\n # <Pixels>\n # es . \" + \",\n # es . \" + \",\n # es . \"+++++\",\n # es . \" + \",\n # es . \" + \",\n row = (\" \" * pickBox) + \"+\" + (\" \" * pickBox) \n xpm.append(row)\n if size > 1:\n for i in range(pickBox - 1): # da 0\n xpm.append(row)\n xpm.append(\"+\" * (size))\n for i in range(pickBox - 1): # da 0\n xpm.append(row)\n \n return QCursor(QPixmap(xpm))\n\n \n#===============================================================================\n# getFeatureRequest\n#===============================================================================\ndef getFeatureRequest(fetchAttributes = [], fetchGeometry = True, \\\n rect = None, useIntersect = False):\n # PER ORA <fetchGeometry> NON VIENE USATO PERCHE' NON SO FARE IL CAST in QgsFeatureRequest.Flags\n # restituisce un oggetto QgsFeatureRequest per interrogare un layer\n # It can get 4 arguments, all of them are optional:\n # fetchAttributes: List of attributes which should be fetched.\n # None = disable fetching attributes, Empty list means that all attributes are used.\n # default: empty list\n # fetchGeometry: Whether geometry of the feature should be fetched. Default: True\n # rect: Spatial filter by rectangle.\n # None = nessuna ricerca spaziale, empty rect means (QgsRectangle()), all features are fetched.\n # Default: none\n # useIntersect: When using spatial filter, this argument says whether accurate test for intersection \n # should be done or whether test on bounding box suffices.\n # This is needed e.g. for feature identification or selection. Default: False\n \n request = QgsFeatureRequest()\n \n #flag = QgsFeatureRequest.NoFlags\n \n# if fetchGeometry == False:\n# flag = flag | QgsFeatureRequest.NoGeometry\n \n if rect is not None:\n r = QgsRectangle(rect)\n \n # Se il rettangolo é schiacciato in verticale o in orizzontale\n # risulta una linea e la funzione fa casino, allora in questo caso lo allargo un pochino\n if doubleNear(r.xMinimum(), r.xMaximum(), 1.e-6):\n r.setXMaximum(r.xMaximum() + 1.e-6)\n r.setXMinimum(r.xMinimum() - 1.e-6)\n if doubleNear(r.yMinimum(), r.yMaximum(), 1.e-6):\n r.setYMaximum(r.yMaximum() + 1.e-6)\n r.setYMinimum(r.yMinimum() - 1.e-6)\n \n request.setFilterRect(r)\n\n if useIntersect == True:\n request.setFlags(QgsFeatureRequest.ExactIntersect) \n\n if fetchAttributes is None:\n request.setSubsetOfAttributes([])\n else:\n if len(fetchAttributes) > 0:\n request.setSubsetOfAttributes(fetchAttributes)\n\n return request\n\n \n#===============================================================================\n# getEntSel\n#===============================================================================\ndef getEntSel(point, mQgsMapTool, \\\n layersToCheck = None, checkPointLayer = True, checkLineLayer = True, checkPolygonLayer = True,\n onlyBoundary = True, onlyEditableLayers = False):\n \"\"\"\n dato un punto (in screen coordinates) e un QgsMapTool, \n la funzione cerca la prima entità dentro il quadrato\n di dimensioni PICKBOX centrato sul punto <point>\n layersToCheck = opzionale, lista dei layer in cui cercare\n checkPointLayer = opzionale, considera i layer di tipo punto\n checkLineLayer = opzionale, considera i layer di tipo linea\n checkPolygonLayer = opzionale, considera i layer di tipo poligono\n onlyBoundary = serve per considerare solo il bordo dei poligoni o anche il loro interno\n Restituisce una lista composta da una QgsFeature e il suo layer e il punto di selezione \n in caso di successo altrimenti None \n \"\"\" \n \n if checkPointLayer == False and checkLineLayer == False and checkPolygonLayer == False:\n return None\n \n feature = QgsFeature()\n Tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) # leggo la tolleranza\n \n #QApplication.setOverrideCursor(Qt.WaitCursor)\n \n if layersToCheck is None:\n # Tutti i layer visibili visibili\n _layers = mQgsMapTool.canvas.layers()\n else:\n # solo la lista passata come parametro\n _layers = layersToCheck\n \n for layer in _layers: # ciclo sui layer\n # considero solo i layer vettoriali che sono filtrati per tipo\n if (layer.type() == QgsMapLayer.VectorLayer) and \\\n ((layer.geometryType() == QGis.Point and checkPointLayer == True) or \\\n (layer.geometryType() == QGis.Line and checkLineLayer == True) or \\\n (layer.geometryType() == QGis.Polygon and checkPolygonLayer == True)) and \\\n (onlyEditableLayers == False or layer.isEditable()): \n layerCoords = mQgsMapTool.toLayerCoordinates(layer, point)\n ToleranceInMapUnits = QgsTolerance.toleranceInMapUnits(Tolerance, layer, \\\n mQgsMapTool.canvas.mapRenderer(), \\\n QgsTolerance.Pixels)\n\n selectRect = QgsRectangle(layerCoords.x() - ToleranceInMapUnits, layerCoords.y() - ToleranceInMapUnits, \\\n layerCoords.x() + ToleranceInMapUnits, layerCoords.y() + ToleranceInMapUnits)\n \n featureIterator = layer.getFeatures(getFeatureRequest([], True, selectRect, True))\n\n # se é un layer contenente poligoni allora verifico se considerare solo i bordi\n if onlyBoundary == False or layer.geometryType() != QGis.Polygon:\n for feature in featureIterator:\n return feature, layer, point\n else:\n # considero solo i bordi delle geometrie e non lo spazio interno dei poligoni\n for feature in featureIterator:\n # Riduco le geometrie in point o polyline\n geoms = asPointOrPolyline(feature.geometry())\n for g in geoms:\n if g.intersects(selectRect):\n return feature, layer, point\n\n# # test per usare la cache (ancora più lento...)\n# dummy, snappingResults = layer.snapWithContext(layerCoords, ToleranceInMapUnits,\n# QgsSnapper.SnapToVertex if layer.geometryType() == QGis.Point else QgsSnapper.SnapToSegment)\n# if len(snappingResults) > 0:\n# featureId = snappingResults[0][1].snappedAtGeometry()\n# feature = getFeatureById(layer, featureId)\n# \n# # se é un layer contenente poligoni allora verifico se considerare solo i bordi\n# if onlyBoundary == False or layer.geometryType() != QGis.Polygon:\n# return feature, layer, point\n# else:\n# geoms = asPointOrPolyline(feature.geometry())\n# for g in geoms:\n# if g.intersects(selectRect):\n# return feature, layer, point\n \n #QApplication.restoreOverrideCursor()\n return None\n\n\n#===============================================================================\n# getFeatureById\n#===============================================================================\ndef getFeatureById(layer, id):\n \"\"\"\n Ricava una feature dal suo id.\n \"\"\"\n feature = QgsFeature()\n if layer.getFeatures(QgsFeatureRequest().setFilterFid(id)).nextFeature(feature):\n return feature\n else:\n return None\n\n \n#===============================================================================\n# isGeomInPickBox\n#===============================================================================\ndef isGeomInPickBox(point, mQgsMapTool, geom, crs = None, \\\n checkPointLayer = True, checkLineLayer = True, checkPolygonLayer = True,\n onlyBoundary = True):\n \"\"\"\n dato un punto (in screen coordinates) e un QgsMapTool, \n la funzione verifica se la geometria é dentro il quadrato\n di dimensioni PICKBOX centrato sul punto\n geom = geometria da verificare\n crs = sistema di coordinate della geometria (se = NON significa in map coordinates)\n checkPointLayer = opzionale, considera la geometria di tipo punto\n checkLineLayer = opzionale, considera la geometria di tipo linea\n checkPolygonLayer = opzionale, considera la geometria di tipo poligono\n onlyBoundary = serve per considerare solo il bordo dei poligoni o anche il loro interno\n Restituisce True se la geometria é nel quadrato di PickBox altrimenti False \n \"\"\" \n if geom is None:\n return False\n if checkPointLayer == False and checkLineLayer == False and checkPolygonLayer == False:\n return False\n \n Tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) # leggo la tolleranza\n \n # considero solo la geometria filtrata per tipo\n if ((geom.type() == QGis.Point and checkPointLayer == True) or \\\n (geom.type() == QGis.Line and checkLineLayer == True) or \\\n (geom.type() == QGis.Polygon and checkPolygonLayer == True)): \n mapPoint = mQgsMapTool.toMapCoordinates(point)\n mapGeom = QgsGeometry(geom)\n if crs is not None and mQgsMapTool.canvas.mapRenderer().destinationCrs() != crs:\n # trasformo le coord della geometria in map coordinates\n coordTransform = QgsCoordinateTransform(crs, mQgsMapTool.canvas.mapRenderer().destinationCrs()) \n mapGeom.transform(coordTransform) \n \n ToleranceInMapUnits = Tolerance * mQgsMapTool.canvas.mapRenderer().mapUnitsPerPixel() \n selectRect = QgsRectangle(mapPoint.x() - ToleranceInMapUnits, mapPoint.y() - ToleranceInMapUnits, \\\n mapPoint.x() + ToleranceInMapUnits, mapPoint.y() + ToleranceInMapUnits)\n \n # se é una geometria poligono allora verifico se considerare solo i bordi\n if onlyBoundary == False or geom.type() != QGis.Polygon:\n if mapGeom.intersects(selectRect):\n return True\n else:\n # considero solo i bordi della geometria e non lo spazio interno del poligono\n # Riduco la geometria in point o polyline\n geoms = asPointOrPolyline(mapGeom)\n for g in geoms:\n if g.intersects(selectRect):\n return True\n \n return False\n\n \n#===============================================================================\n# getGeomInPickBox\n#===============================================================================\ndef getGeomInPickBox(point, mQgsMapTool, geoms, crs = None, \\\n checkPointLayer = True, checkLineLayer = True, checkPolygonLayer = True,\n onlyBoundary = True):\n \"\"\"\n dato un punto (in screen coordinates) e un QgsMapTool, \n la funzione cerca la prima geometria dentro il quadrato\n di dimensioni PICKBOX centrato sul punto\n geoms = lista di geometrie da verificare\n crs = sistema di coordinate della geometria (se = NON significa in map coordinates)\n checkPointLayer = opzionale, considera la geometria di tipo punto\n checkLineLayer = opzionale, considera la geometria di tipo linea\n checkPolygonLayer = opzionale, considera la geometria di tipo poligono\n onlyBoundary = serve per considerare solo il bordo dei poligoni o anche il loro interno\n Restituisce la geometria che é nel quadrato di PickBox altrimenti None \n \"\"\" \n if geoms is None:\n return False\n for geom in geoms:\n if isGeomInPickBox(point, mQgsMapTool, geom, crs, checkPointLayer, checkLineLayer, checkPolygonLayer, onlyBoundary):\n return geom\n return None\n\n\n#===============================================================================\n# getActualSingleSelection\n#===============================================================================\ndef getActualSingleSelection(layers):\n \"\"\"\n la funzione cerca se esiste una sola entità selezionata tra i layer\n Restituisce un QgsFeature e il suo layer in caso di successo altrimenti None \n \"\"\"\n selFeature = []\n\n for layer in layers: # ciclo sui layer\n if (layer.type() == QgsMapLayer.VectorLayer):\n selectedFeatureCount = layer.selectedFeaturCount()\n if selectedFeatureCount == 1:\n selFeature = layer.selectedFeatures()\n selLayer = Layer\n elif selectedFeatureCount > 1:\n del selFeature[:] # svuoto la lista\n break\n \n if len(selFeature) == 1: # se c'era solo una entità selezionata\n return selFeature[0], selLayer\n \n return None\n\n\ndef deselectAll(layers):\n \"\"\"\n la funzione deseleziona tutte le entità selezionate nei layer\n \"\"\"\n selFeatureIds = []\n for layer in layers: # ciclo sui layer\n if (layer.type() == QgsMapLayer.VectorLayer):\n if layer.selectedFeaturesIds() > 0:\n layer.setSelectedFeatures(selFeatureIds)\n\n\n#===============================================================================\n# getSelSet\n#===============================================================================\ndef getSelSet(mode, mQgsMapTool, points = None, \\\n layersToCheck = None, checkPointLayer = True, checkLineLayer = True, checkPolygonLayer = True,\n onlyEditableLayers = False):\n \"\"\"\n dato un QgsMapTool, una modalità di selezione e una lista opzionale di punti (in map coordinates),\n la funzione cerca le entità.\n mode = \"C\" -> Crossing selection (inside and crossing)\n \"CP\" -> Crossing polygon (inside and crossing)\n \"F\" -> Fence selection (crossing)\n \"W\" -> Window selection (inside)\n \"WP\" -> Windows polygon (inside)\n \"X\" -> all \n layer = opzionale, lista dei layer in cui cercare\n checkPointLayer = opzionale, considera i layer di tipo punto\n checkLineLayer = opzionale, considera i layer di tipo linea\n checkPolygonLayer = opzionale, considera i layer di tipo poligono\n onlyEditableLayers = opzionale, considera i layer editabili\n Restituisce un QadEntitySet in caso di successo altrimenti None \n \"\"\"\n \n if checkPointLayer == False and checkLineLayer == False and checkPolygonLayer == False:\n return None\n \n entity = QadEntity()\n result = QadEntitySet()\n feature = QgsFeature()\n \n #QApplication.setOverrideCursor(Qt.WaitCursor)\n \n if layersToCheck is None:\n # Tutti i layer visibili visibili\n _layers = mQgsMapTool.canvas.layers()\n else:\n # solo la lista passata come parametro\n _layers = layersToCheck\n \n for layer in _layers: # ciclo sui layer\n # considero solo i layer vettoriali che sono filtrati per tipo\n if (layer.type() == QgsMapLayer.VectorLayer) and \\\n ((layer.geometryType() == QGis.Point and checkPointLayer == True) or \\\n (layer.geometryType() == QGis.Line and checkLineLayer == True) or \\\n (layer.geometryType() == QGis.Polygon and checkPolygonLayer == True)) and \\\n (onlyEditableLayers == False or layer.isEditable()):\n provider = layer.dataProvider() \n\n if mode.upper() == \"X\": # take all features\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, None, False)):\n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"C\": # crossing selection\n p1 = mQgsMapTool.toLayerCoordinates(layer, points[0])\n p2 = mQgsMapTool.toLayerCoordinates(layer, points[1])\n selectRect = QgsRectangle(p1, p2)\n # Select features in rectangle\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, selectRect, True)):\n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"W\": # window selection\n p1 = mQgsMapTool.toLayerCoordinates(layer, points[0])\n p2 = mQgsMapTool.toLayerCoordinates(layer, points[1])\n selectRect = QgsRectangle(p1, p2)\n g = QgsGeometry.fromRect(selectRect)\n # Select features in rectangle\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, selectRect, True)): \n # solo le feature completamente interne al rettangolo\n if g.contains(feature.geometry()):\n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"CP\": # crossing polygon\n polyline = [] \n for point in points:\n polyline.append(mQgsMapTool.toLayerCoordinates(layer, point))\n \n g = QgsGeometry.fromPolygon([polyline])\n # Select features in the polygon bounding box\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, g.boundingBox(), True)): \n # solo le feature intersecanti il poligono\n if g.intersects(feature.geometry()): \n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"WP\": # windows polygon\n polyline = [] \n for point in points:\n polyline.append(mQgsMapTool.toLayerCoordinates(layer, point))\n \n g = QgsGeometry.fromPolygon([polyline])\n # Select features in the polygon bounding box\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, g.boundingBox(), True)): \n # solo le feature completamente interne al poligono\n if g.contains(feature.geometry()): \n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"CO\": # crossing object\n # points é in questo caso un QgsGeometry \n g = QgsGeometry(points)\n if mQgsMapTool.canvas.mapRenderer().destinationCrs() != layer.crs(): \n coordTransform = QgsCoordinateTransform(mQgsMapTool.canvas.mapRenderer().destinationCrs(), \\\n layer.crs()) # trasformo la geometria\n g.transform(coordTransform)\n \n # Select features in the object bounding box\n wkbType = g.wkbType() \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D: \n Tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) # leggo la tolleranza\n ToleranceInMapUnits = QgsTolerance.toleranceInMapUnits(Tolerance, layer, \\\n mQgsMapTool.canvas.mapRenderer(), \\\n QgsTolerance.Pixels)\n \n pt = g.asPoint()\n # QgsRectangle (double xmin=0, double ymin=0, double xmax=0, double ymax=0)\n selectRect = QgsRectangle(pt.x() - ToleranceInMapUnits, pt.y() - ToleranceInMapUnits, \\\n pt.x() + ToleranceInMapUnits, pt.y() + ToleranceInMapUnits)\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n request = getFeatureRequest([], True, selectRect, True)\n else:\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n request = getFeatureRequest([], True, g.boundingBox(), True)\n \n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(request): \n # solo le feature intersecanti l'oggetto\n if g.intersects(feature.geometry()):\n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"WO\": # windows object\n # points é in questo caso un QgsGeometry \n g = QgsGeometry(points)\n if mQgsMapTool.canvas.mapRenderer().destinationCrs() != layer.crs(): \n coordTransform = QgsCoordinateTransform(mQgsMapTool.canvas.mapRenderer().destinationCrs(), \\\n layer.crs()) # trasformo la geometria\n g.transform(coordTransform)\n\n # Select features in the object bounding box\n wkbType = g.wkbType() \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D: \n Tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"PICKBOX\")) # leggo la tolleranza\n ToleranceInMapUnits = QgsTolerance.toleranceInMapUnits(Tolerance, layer, \\\n mQgsMapTool.canvas.mapRenderer(), \\\n QgsTolerance.Pixels)\n \n pt = g.asPoint()\n selectRect = QgsRectangle(pt.x() - ToleranceInMapUnits, pt.y() - ToleranceInMapUnits, \\\n pt.x() + ToleranceInMapUnits, pt.y() + ToleranceInMapUnits)\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n request = getFeatureRequest([], True, selectRect, True)\n else:\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n request = getFeatureRequest([], True, g.boundingBox(), True)\n \n # solo le feature completamente interne all'oggetto\n for feature in layer.getFeatures(request): \n if g.contains(feature.geometry()): \n entity.set(layer, feature.id())\n result.addEntity(entity)\n elif mode.upper() == \"F\": # fence\n polyline = [] \n for point in points:\n polyline.append(mQgsMapTool.toLayerCoordinates(layer, point))\n \n g = QgsGeometry()\n g = QgsGeometry.fromPolyline(polyline)\n # Select features in the polyline bounding box\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in layer.getFeatures(getFeatureRequest([], True, g.boundingBox(), True)): \n # solo le feature che intersecano la polyline\n if g.intersects(feature.geometry()): \n entity.set(layer, feature.id())\n result.addEntity(entity)\n \n #QApplication.restoreOverrideCursor()\n return result\n \n \n#===============================================================================\n# appendUniquePointToList\n#===============================================================================\ndef appendUniquePointToList(pointList, point):\n \"\"\"\n Aggiunge un punto alla lista verificando che non sia già presente.\n Resituisce True se l'inserimento é avvenuto False se il punto c'era già.\n \"\"\"\n for iPoint in pointList:\n if ptNear(iPoint, point):\n return False\n\n pointList.append(point)\n return True\n\n\n#===============================================================================\n# getIntersectionPoints\n#===============================================================================\ndef getIntersectionPoints(geom1, geom2, checkForCurves = False):\n \"\"\"\n la funzione ritorna una lista dei punti di intersezione tra le 2 geometrie.\n Purtroppo non posso usare QgsGeometry.intersection perché non usa una tolleranza\n (le geometrie spesso vengono convertite in un'altro crs \n e poi riconvertite in quello originale perdendo precisione)\n \"\"\"\n result = []\n # Riduco le geometrie in point o polyline\n geoms1 = asPointOrPolyline(geom1)\n geoms2 = asPointOrPolyline(geom2)\n \n for g1 in geoms1:\n wkbType1 = g1.wkbType()\n if wkbType1 == QGis.WKBPoint:\n pt1 = g1.asPoint()\n for g2 in geoms2:\n wkbType2 = g2.wkbType()\n if wkbType2 == QGis.WKBPoint:\n if ptNear(pt1, g2.asPoint()):\n appendUniquePointToList(result, pt1)\n elif wkbType2 == QGis.WKBLineString:\n points2 = g2.asPolyline()\n p2Start = points2[0]\n for i in xrange(1, len(points2), 1):\n p2End = points2[i] \n if isPtOnSegment(p2Start, p2End, pt1):\n appendUniquePointToList(result, pt1)\n break\n p2Start = p2End\n elif wkbType1 == QGis.WKBLineString:\n points1 = g1.asPolyline()\n p1Start = points1[0]\n for i in xrange(1, len(points1), 1):\n p1End = points1[i] \n for g2 in geoms2:\n wkbType2 = g2.wkbType()\n if wkbType2 == QGis.WKBPoint:\n pt2 = g2.asPoint()\n if isPtOnSegment(p1Start, p1End, pt2):\n appendUniquePointToList(result, pt2)\n elif wkbType2 == QGis.WKBLineString:\n points2 = g2.asPolyline()\n p2Start = points2[0]\n for i in xrange(1, len(points2), 1):\n p2End = points2[i] \n intPt = getIntersectionPointOn2Segments(p1Start, p1End,p2Start, p2End) \n if intPt is not None:\n appendUniquePointToList(result, intPt)\n p2Start = p2End\n \n p1Start = p1End \n \n return result\n\n\ndef getNextPolygonVertex(vertex, totalSegment):\n return 0 if vertex == totalSegment - 1 else vertex + 1\ndef getPrevPolygonVertex(vertex, totalSegment):\n return totalSegment - 1 if vertex == 0 else vertex - 1\n \ndef getLinePart(geom, ptStart, ptEnd):\n \"\"\"\n la funzione ritorna una lista dei punti che rappresenta una linea che va dal\n punto ptStart al punto ptEnd passando per il contorno di geom.\n \"\"\"\n if ptStart == ptEnd:\n return None\n \n geomPtStart = QgsGeometry.fromPoint(ptStart) \n geomPtEnd = QgsGeometry.fromPoint(ptEnd)\n \n isPolygon = True if geom.wkbType() == QGis.WKBPolygon else False\n \n # Riduco le geometrie in point o polyline\n geoms = asPointOrPolyline(geom)\n \n for g in geoms:\n if g.wkbType() == QGis.WKBPoint:\n continue\n points = g.asPolyline()\n totalSegment = len(points) - 1\n\n # cerco il segmento che contiene il punto iniziale\n found = False\n for segmentStart in xrange(0, totalSegment, 1):\n geomSegment = QgsGeometry.fromPolyline([points[segmentStart], points[segmentStart + 1]])\n # se ci sono punti di intersezione\n if len(getIntersectionPoints(geomSegment, geomPtStart)) > 0:\n found = True\n break \n if found == False:\n continue \n\n # cerco il segmento che contiene il punto finale\n found = False\n for segmentEnd in xrange(0, totalSegment, 1):\n geomSegment = QgsGeometry.fromPolyline([points[segmentEnd], points[segmentEnd + 1]])\n # se ci sono punti di intersezione\n if len(getIntersectionPoints(geomSegment, geomPtEnd)) > 0:\n found = True\n break \n if found == False:\n continue \n \n if isPolygon == False:\n # trovata la polilinea che contiene il punto iniziale e finale\n result = [ptStart]\n if segmentStart < segmentEnd:\n # se il punto ptStart é uguale al punto iniziale del segmento successivo \n if ptStart == points[segmentStart + 1]:\n segmentStart = segmentStart + 1\n \n for i in xrange(segmentStart + 1, segmentEnd + 1, 1):\n result.append(points[i])\n \n elif segmentStart > segmentEnd:\n # se il punto ptEnd é uguale al punto finale del segmento \n if ptEnd == points[segmentEnd + 1]:\n segmentEnd = segmentEnd + 1\n \n for i in xrange(segmentStart, segmentEnd, -1):\n result.append(points[i])\n \n result.append(ptEnd) \n else:\n # do il senso di circolarità\n if ptStart == points[0]:\n segmentStart = totalSegment - 1\n \n if segmentStart == segmentEnd:\n return [ptStart, ptEnd]\n # Se é un poligono devo verificare il percorso più corto da ptStart e ptEnd\n \n # seguo il senso dei vertici\n result1 = [ptStart] \n # se il punto ptStart é uguale al punto iniziale del segmento successivo\n i = segmentStart\n nextSegment = getNextPolygonVertex(segmentStart, totalSegment) \n if ptStart == points[nextSegment]:\n i = nextSegment\n \n i = getNextPolygonVertex(i, totalSegment)\n nextSegment = getNextPolygonVertex(segmentEnd, totalSegment)\n while i != nextSegment:\n result1.append(points[i])\n i = getNextPolygonVertex(i, totalSegment) \n \n result1.append(ptEnd) \n \n # seguo il senso inverso dei vertici\n result2 = [ptStart]\n # se il punto ptEnd é uguale al punto finale del segmento \n nextSegment = getNextPolygonVertex(segmentEnd, totalSegment)\n if ptEnd == points[nextSegment]:\n segmentEnd = nextSegment\n \n i = segmentStart\n segmentPrevEnd = getNextPolygonVertex(segmentEnd, totalSegment)\n while i != segmentEnd:\n result2.append(points[i])\n i = getPrevPolygonVertex(i, totalSegment) \n \n result2.append(ptEnd)\n \n g1 = QgsGeometry.fromPolyline(result1)\n g2 = QgsGeometry.fromPolyline(result2)\n \n result = result1 if g1.length() < g2.length() else result2\n \n return result\n\n return None\n\n\n#===============================================================================\n# getPerpendicularPointOnInfinityLine\n#===============================================================================\ndef getPerpendicularPointOnInfinityLine(p1, p2, pt):\n \"\"\"\n la funzione ritorna il punto di proiezione perpendicolare di pt \n alla linea passante per p1-p2.\n \"\"\"\n \n diffX = p2.x() - p1.x()\n diffY = p2.y() - p1.y()\n \n if doubleNear(diffX, 0): # se la retta passante per p1 e p2 é verticale\n return QgsPoint(p1.x(), pt.y())\n elif doubleNear(diffY, 0): # se la retta passante per p1 e p2 é orizzontale\n return QgsPoint(pt.x(), p1.y())\n else:\n coeff = diffY / diffX\n x = (coeff * p1.x() - p1.y() + pt.x() / coeff + pt.y()) / (coeff + 1 / coeff)\n y = coeff * (x - p1.x()) + p1.y()\n \n return QgsPoint(x, y)\n\n\n#===============================================================================\n# getInfinityLinePerpOnMiddle\n#===============================================================================\ndef getInfinityLinePerpOnMiddle(pt1, pt2):\n \"\"\"\n dato un segmento pt1-pt2, la funzione trova una linea perpendicolare al segmento\n che passa per il suo punto medio. La funzione restituisce 2 punti della linea.\n \"\"\"\n ptMiddle = getMiddlePoint(pt1, pt2)\n dist = getDistance(pt1, ptMiddle)\n if dist == 0:\n return None\n angle = getAngleBy2Pts(pt1, pt2) + math.pi / 2\n pt2Middle = getPolarPointByPtAngle(ptMiddle, angle, dist)\n return ptMiddle, pt2Middle\n\n\n#===============================================================================\n# getBisectorInfinityLine\n#===============================================================================\ndef getBisectorInfinityLine(pt1, pt2, pt3, acuteMode = True):\n \"\"\"\n dato un angolo definito da 3 punti il cui secondo punto é vertice dell'angolo,\n la funzione restituisce la linea bisettrice dell'angolo attraverso 2 punti \n della linea (il vertice dell'angolo e un altro punto calcolato distante quanto\n la distanza di pt1 da pt2).\n acuteMode = True considera l'angolo acuto, acuteMode = False l'angolo ottuso \n \"\"\" \n angle1 = getAngleBy2Pts(pt2, pt1)\n angle2 = getAngleBy2Pts(pt2, pt3)\n angle = (angle1 + angle2) / 2 # angolo medio\n# return pt2, getPolarPointByPtAngle(pt2, angle, 10)\n \n dist = getDistance(pt1, pt2)\n ptProj = getPolarPointByPtAngle(pt2, angle, dist)\n ptInverseProj = getPolarPointByPtAngle(pt2, angle - math.pi, dist)\n if getDistance(pt1, ptProj) < getDistance(pt1, ptInverseProj):\n if acuteMode == True:\n return pt2, ptProj\n else:\n return pt2, ptInverseProj\n else:\n if acuteMode == True:\n return pt2, ptInverseProj\n else:\n return pt2, ptProj\n\n\n#===============================================================================\n# getXOnInfinityLine\n#===============================================================================\ndef getXOnInfinityLine(p1, p2, y):\n \"\"\"\n data la coordinata Y di un punto la funzione ritorna la coordinata X dello stesso\n sulla linea passante per p1-p2 \n \"\"\"\n \n diffX = p2.x() - p1.x()\n diffY = p2.y() - p1.y()\n \n if doubleNear(diffX, 0): # se la retta passante per p1 e p2 é verticale\n return p1.x()\n elif doubleNear(diffY, 0): # se la retta passante per p1 e p2 é orizzontale\n return None # infiniti punti\n else:\n coeff = diffY / diffX\n return p1.x() + (y - p1.y()) / coeff\n\n\n#===============================================================================\n# getYOnInfinityLine\n#===============================================================================\ndef getYOnInfinityLine(p1, p2, x):\n \"\"\"\n data la coordinata Y di un punto la funzione ritorna la coordinata X dello stesso\n sulla linea passante per p1-p2 \n \"\"\"\n \n diffX = p2.x() - p1.x()\n diffY = p2.y() - p1.y()\n \n if doubleNear(diffX, 0): # se la retta passante per p1 e p2 é verticale\n return None # infiniti punti\n elif doubleNear(diffY, 0): # se la retta passante per p1 e p2 é orizzontale\n return p1.y()\n else:\n coeff = diffY / diffX\n return p1.y() + (x - p1.x()) * coeff\n\n\n#===============================================================================\n# getSqrDistance\n#===============================================================================\ndef getSqrDistance(p1, p2):\n \"\"\"\n la funzione ritorna la distanza al quadrato tra 2 punti (QgsPoint)\n \"\"\"\n dx = p2.x() - p1.x()\n dy = p2.y() - p1.y()\n \n return dx * dx + dy * dy\n\n\n#===============================================================================\n# getDistance\n#===============================================================================\ndef getDistance(p1, p2):\n \"\"\"\n la funzione ritorna la distanza tra 2 punti (QgsPoint)\n \"\"\"\n return math.sqrt(getSqrDistance(p1, p2))\n\n\n#===============================================================================\n# getMinDistancePtBetweenSegmentAndPt\n#===============================================================================\ndef getMinDistancePtBetweenSegmentAndPt(p1, p2, pt):\n \"\"\"\n la funzione ritorna il punto di distanza minima e la distanza minima tra un segmento ed un punto\n (<punto di distanza minima><distanza minima>)\n \"\"\"\n if isPtOnSegment(p1, p2, pt) == True:\n return [pt, 0]\n perpPt = getPerpendicularPointOnInfinityLine(p1, p2, pt)\n if perpPt is not None:\n if isPtOnSegment(p1, p2, perpPt) == True:\n return [perpPt, getDistance(perpPt, pt)]\n\n distFromP1 = getDistance(p1, pt)\n distFromP2 = getDistance(p2, pt)\n if distFromP1 < distFromP2:\n return [p1, distFromP1]\n else:\n return [p2, distFromP2]\n\n\n#===============================================================================\n# getMinDistancePtBetweenArcAndPt\n#===============================================================================\ndef getMinDistancePtBetweenArcAndPt(arc, pt):\n \"\"\"\n la funzione ritorna il punto di distanza minima e la distanza minima tra un arco ed un punto\n (<punto di distanza minima><distanza minima>)\n \"\"\"\n angle = getAngleBy2Pts(arc.center, pt)\n if isAngleBetweenAngles(arc.startAngle, arc.endAngle, angle) == True:\n return [getPolarPointByPtAngle(arc.center, angle, arc.radius), \\\n math.fabs(getDistance(arc.center, pt) - arc.radius)]\n\n ptStart = arc.getStartPt()\n ptEnd = arc.getEndPt()\n distFromStartPt = getDistance(ptStart, pt)\n distFromEndPt = getDistance(ptEnd, pt)\n if distFromStartPt < distFromEndPt:\n return [ptStart, distFromStartPt]\n else:\n return [ptEnd, distFromEndPt]\n\n\n#===============================================================================\n# getMinDistancePtsBetween2Segments\n#===============================================================================\ndef getMinDistancePtsBetween2Segments(line1P1, line1P2, line2P1, line2P2):\n \"\"\"\n la funzione ritorna i punti di distanza minima e la distanza minima tra due segmenti\n (<punto di distanza minima sul segmento1><punto di distanza minima sul segmento2><distanza minima>)\n \"\"\"\n intPt = getIntersectionPointOn2Segments(line1P1, line1P2, line2P1, line2P2)\n if intPt is not None:\n return [intPt, intPt, 0]\n\n # ritorna una lista: (<punto di distanza minima><distanza minima>)\n bestResult = getMinDistancePtBetweenSegmentAndPt(line2P1, line2P2, line1P1)\n bestResult.insert(0, line1P1)\n resultLine1P2 = getMinDistancePtBetweenSegmentAndPt(line2P1, line2P2, line1P2)\n resultLine1P2.insert(0, line1P2)\n if bestResult[2] > resultLine1P2[2]:\n bestResult = resultLine1P2 \n resultLine2P1 = getMinDistancePtBetweenSegmentAndPt(line1P1, line1P2, line2P1)\n resultLine2P1.insert(1, line2P1)\n if bestResult[2] > resultLine2P1[2]:\n bestResult = resultLine2P1 \n resultLine2P2 = getMinDistancePtBetweenSegmentAndPt(line1P1, line1P2, line2P2)\n resultLine2P2.insert(1, line2P2)\n if bestResult[2] > resultLine2P2[2]:\n bestResult = resultLine2P2\n return bestResult\n \n\n#===============================================================================\n# getMinDistancePtsBetweenSegmentAndArc\n#===============================================================================\ndef getMinDistancePtsBetweenSegmentAndArc(p1, p2, arc):\n \"\"\"\n la funzione ritorna i punti di distanza minima e la distanza minima tra un segmento ed un arco\n (<punto di distanza minima sul segmento><punto di distanza minima sull'arco><distanza minima>)\n \"\"\" \n intPtList = arc.getIntersectionPointsWithSegment(p1, p2)\n if len(intPtList) > 0:\n return [intPtList[0], intPtList[0], 0]\n\n # ritorna una lista: (<punto di distanza minima><distanza minima>)\n resultP1 = getMinDistancePtBetweenArcAndPt(arc, p1) \n resultP2 = getMinDistancePtBetweenArcAndPt(arc, p2)\n # se il segmento é interno al cerchio orginato dall'estensione dell'arco\n if getDistance(p1, arc.center) < arc.radius and \\\n getDistance(p2, arc.center) < arc.radius:\n if resultP1[1] < resultP2[1]:\n return [p1, resultP1[0], resultP1[1]]\n else:\n return [p2, resultP2[0], resultP2[1]]\n # se il segmento é esterno al cerchio orginato dall'estensione dell'arco\n else:\n perpPt = getPerpendicularPointOnInfinityLine(p1, p2, arc.center)\n angle = getAngleBy2Pts(arc.center, perpPt)\n # il punto di perpendicolare alla linea infinita p1,p2 é sul segmento e sull'arco\n if isPtOnSegment(p1, p2, perpPt) == True and \\\n isAngleBetweenAngles(arc.startAngle, arc.endAngle, angle) == True:\n ptOnArc = getPolarPointByPtAngle(arc.center, angle, arc.radius)\n return [perpPt, ptOnArc, getDistance(perpPt, ptOnArc)]\n \n bestResult = resultP1\n bestResult.insert(0, p1)\n resultP2.insert(0, p2)\n if bestResult[2] > resultP2[2]:\n bestResult = resultP2 \n\n ptStart = arc.getStartPt()\n ptEnd = arc.getEndPt() \n \n # ritorna una lista: (<punto di distanza minima><distanza minima>) \n resultStartPt = getMinDistancePtBetweenSegmentAndPt(p1, p2, ptStart)\n resultStartPt.insert(1, ptStart) \n if bestResult[2] > resultStartPt[2]:\n bestResult = resultStartPt \n resultEndPt = getMinDistancePtBetweenSegmentAndPt(p1, p2, ptEnd)\n resultEndPt.insert(1, ptEnd)\n if bestResult[2] > resultEndPt[2]:\n bestResult = resultEndPt \n return bestResult\n \n\n#===============================================================================\n# getMinDistancePtsBetween2Arcs\n#===============================================================================\ndef getMinDistancePtsBetween2Arcs(arc1, arc2):\n \"\"\"\n la funzione ritorna i punti di distanza minima e la distanza minima tra due archi\n (<punto di distanza minima sull'arco1><punto di distanza minima sull'arco2><distanza minima>)\n \"\"\" \n intPtList = arc1.getIntersectionPointsWithArc(arc2)\n if len(intPtList) > 0:\n return [intPtList[0], intPtList[0], 0]\n \n StartPtArc1 = arc1.getStartPt()\n EndPtArc1 = arc1.getEndPt() \n StartPtArc2 = arc2.getStartPt()\n EndPtArc2 = arc2.getEndPt() \n \n # calcolo la minima distanza tra gli estremi di un arco e l'altro arco e \n # scelgo la migliore tra le quattro distanze\n # ritorna una lista: (<punto di distanza minima><distanza minima>)\n bestResult = getMinDistancePtBetweenArcAndPt(arc2, StartPtArc1) \n bestResult.insert(0, StartPtArc1)\n \n resultArc2_EndPtArc1 = getMinDistancePtBetweenArcAndPt(arc2, EndPtArc1)\n resultArc2_EndPtArc1.insert(0, EndPtArc1)\n if bestResult[2] > resultArc2_EndPtArc1[2]:\n bestResult = resultArc2_EndPtArc1\n \n resultArc1_StartPtArc2 = getMinDistancePtBetweenArcAndPt(arc1, StartPtArc2)\n resultArc1_StartPtArc2.insert(0, EndPtArc2)\n if bestResult[2] > resultArc1_StartPtArc2[2]:\n bestResult = resultArc1_StartPtArc2\n \n resultArc1_EndPtArc2 = getMinDistancePtBetweenArcAndPt(arc1, EndPtArc2)\n resultArc1_EndPtArc2.insert(0, EndPtArc2)\n if bestResult[2] > resultArc1_EndPtArc2[2]:\n bestResult = resultArc1_EndPtArc2 \n\n # il cerchio1 e il cerchio 2 sono derivati rispettivamente dall'estensione dell'arco1 e arco2.\n circle1 = QadCircle()\n circle1.set(arc1.center, arc1.radius)\n circle2 = QadCircle()\n circle2.set(arc2.center, arc2.radius)\n distanceBetweenCenters = getDistance(circle1.center, circle2.center)\n \n # considero i seguenti 2 casi:\n # i cerchi sono esterni\n if distanceBetweenCenters - circle1.radius - circle2.radius > 0:\n # creo un segmento che unisce i due centri e lo interseco con l'arco 1\n intPtListArc1 = arc1.getIntersectionPointsWithSegment(arc1.center, arc2.center)\n if len(intPtListArc1) > 0:\n intPtArc1 = intPtListArc1[0]\n \n # creo un segmento che unisce i due centri e lo interseco con l'arco 2\n intPtListArc2 = arc2.getIntersectionPointsWithSegment(arc1.center, arc2.center)\n if len(intPtListArc2) > 0:\n intPtArc2 = intPtListArc2[0]\n \n distanceIntPts = getDistance(intPtArc1, intPtArc2)\n if bestResult[2] > distanceIntPts:\n bestResult = [intPtArc1, intPtArc2, distanceIntPts] \n # il cerchio1 é interno al cerchio2 oppure\n # il cerchio2 é interno al cerchio1\n elif distanceBetweenCenters + circle1.radius < circle2.radius or \\\n distanceBetweenCenters + circle2.radius < circle1.radius:\n # creo un segmento che unisce i due centri e lo interseco con l'arco 2\n intPtListArc2 = arc2.getIntersectionPointsWithInfinityLine(arc1.center, arc2.center)\n if len(intPtListArc2) > 0:\n # creo un segmento che unisce i due centri e lo interseco con l'arco 1\n intPtListArc1 = arc1.getIntersectionPointsWithInfinityLine(arc1.center, arc2.center)\n\n for intPtArc2 in intPtListArc2:\n for intPtArc1 in intPtListArc1:\n distanceIntPts = getDistance(intPtArc2, intPtArc1)\n if bestResult[2] > distanceIntPts:\n bestResult = [intPtArc1, intPtArc2, distanceIntPts] \n\n return bestResult\n\n\n#===============================================================================\n# getMiddlePoint\n#===============================================================================\ndef getMiddlePoint(p1, p2):\n \"\"\"\n la funzione ritorna il punto medio tra 2 punti (QgsPoint)\n \"\"\"\n x = (p1.x() + p2.x()) / 2\n y = (p1.y() + p2.y()) / 2\n \n return QgsPoint(x, y)\n\n\n#===============================================================================\n# getAngleBy2Pts\n#===============================================================================\ndef getAngleBy2Pts(p1, p2):\n \"\"\"\n la funzione ritorna l'angolo in radianti della retta passante per p1 e p2\n \"\"\"\n diffX = p2.x() - p1.x()\n diffY = p2.y() - p1.y()\n if doubleNear(diffX, 0): # se la retta passante per p1 e p2 é verticale\n if p1.y() < p2.y():\n angle = math.pi / 2\n else :\n angle = math.pi * 3 / 2\n elif doubleNear(diffY, 0): # se la retta passante per p1 e p2 é orizzontale\n if p1.x() <= p2.x():\n angle = 0.0\n else:\n angle = math.pi\n else:\n angle = math.atan(diffY / diffX)\n if diffX < 0:\n angle = math.pi + angle\n else:\n if diffY < 0:\n angle = 2 * math.pi + angle\n\n return angle\n\n\n#===============================================================================\n# getAngleBy3Pts\n#===============================================================================\ndef getAngleBy3Pts(p1, vertex, p2, clockWise):\n \"\"\"\n la funzione ritorna l'angolo in radianti dell'angolo che parte da <p1> \n per arrivare a <p2> con vertice <vertex> nella direzione <clockWise> (oraria o antioraria)\n \"\"\"\n angle1 = getAngleBy2Pts(p1, vertex) \n angle2 = getAngleBy2Pts(p2, vertex)\n if clockWise: # senso orario\n if angle2 > angle1:\n return (2 * math.pi) - (angle2 - angle1) \n else:\n return angle1 - angle2 \n else: # senso anti-orario\n if angle2 < angle1:\n return (2 * math.pi) - (angle1 - angle2) \n else:\n return angle2 - angle1\n\n\n#===============================================================================\n# isAngleBetweenAngles\n#===============================================================================\ndef isAngleBetweenAngles(startAngle, endAngle, angle):\n \"\"\"\n la funzione ritorna True se l'angolo si trova entro l'angolo di partenza e quello finale\n estremi compresi\n \"\"\"\n _angle = angle % (math.pi * 2) # modulo\n if _angle < 0:\n _angle = (math.pi * 2) - _angle\n \n if startAngle < endAngle:\n if (_angle > startAngle or doubleNear(_angle, startAngle)) and \\\n (_angle < endAngle or doubleNear(_angle, endAngle)):\n return True \n else:\n if (_angle > 0 or doubleNear(_angle, 0)) and \\\n (_angle < endAngle or doubleNear(_angle, endAngle)):\n return True \n\n if (_angle < (math.pi * 2) or doubleNear(_angle, (math.pi * 2))) and \\\n (_angle > startAngle or doubleNear(_angle, startAngle)):\n return True \n \n return False\n\n\ndef getPolarPointBy2Pts(p1, p2, dist):\n \"\"\"\n la funzione ritorna il punto sulla retta passante per p1 e p2 che\n dista da p1 verso p2 <dist>.\n \"\"\"\n angle = getAngleBy2Pts(p1, p2)\n \n return getPolarPointByPtAngle(p1, angle, dist)\n\n\n#===============================================================================\n# isPtOnSegment\n#===============================================================================\ndef isPtOnSegment(p1, p2, point):\n \"\"\"\n la funzione ritorna true se il punto é sul segmento (estremi compresi).\n p1, p2 e point sono QgsPoint.\n \"\"\"\n if p1.x() < p2.x():\n xMin = p1.x()\n xMax = p2.x()\n else:\n xMax = p1.x()\n xMin = p2.x()\n \n if p1.y() < p2.y():\n yMin = p1.y()\n yMax = p2.y()\n else:\n yMax = p1.y()\n yMin = p2.y()\n\n y = getYOnInfinityLine(p1, p2, point.x())\n if y is None: # il segmento p1-p2 é verticale\n if (doubleNear(point.x(), xMin)) and \\\n (point.y() < yMax or doubleNear(point.y(), yMax)) and \\\n (point.y() > yMin or doubleNear(point.y(), yMin)):\n return True\n else:\n # se il punto é sulla linea infinita che passa da p1-p2\n if doubleNear(point.y(), y):\n # se la coordinata x é compresa nel segmento\n if (point.x() > xMin or doubleNear(point.x(), xMin)) and \\\n (point.x() < xMax or doubleNear(point.x(), xMax)):\n return True\n \n return False \n\n\n#===============================================================================\n# isPtOnInfinityLine\n#===============================================================================\ndef isPtOnInfinityLine(lineP1, lineP2, point):\n \"\"\"\n la funzione ritorna true se il punto é sul segmento (estremi compresi).\n p1, p2 e point sono QgsPoint.\n \"\"\"\n y = getYOnInfinityLine(lineP1, lineP2, point.x())\n if y is None: # la linea infinita lineP1-lineP2 é verticale\n if doubleNear(point.x(), lineP1.x()):\n return True\n else:\n # se il punto é sulla linea infinita che passa da p1-p2\n if doubleNear(point.y(), y):\n return True\n \n return False \n\n\n#===============================================================================\n# getIntersectionPointOn2InfinityLines\n#===============================================================================\ndef getIntersectionPointOn2InfinityLines(line1P1, line1P2, line2P1, line2P2):\n \"\"\"\n la funzione ritorna il punto di intersezione tra la linea passante per line1P1-line1P2 e\n la linea passante per line2P1-line2P2.\n \"\"\"\n line1DiffX = line1P2.x() - line1P1.x()\n line1DiffY = line1P2.y() - line1P1.y()\n\n line2DiffX = line2P2.x() - line2P1.x()\n line2DiffY = line2P2.y() - line2P1.y() \n \n if doubleNear(line1DiffX, 0) and doubleNear(line2DiffX, 0): # se la retta1 e la retta2 sono verticale\n return None # sono parallele\n elif doubleNear(line1DiffY, 0) and doubleNear(line2DiffY, 0): # se la retta1 e la retta2 sono orizzonatali\n return None # sono parallele\n\n if doubleNear(line1DiffX, 0): # se la retta1 é verticale\n return QgsPoint(line1P2.x(), getYOnInfinityLine(line2P1, line2P2, line1P2.x()))\n if doubleNear(line1DiffY, 0): # se la retta1 é orizzontale\n return QgsPoint(getXOnInfinityLine(line2P1, line2P2, line1P2.y()), line1P2.y())\n if doubleNear(line2DiffX, 0): # se la retta2 é verticale\n return QgsPoint(line2P2.x(), getYOnInfinityLine(line1P1, line1P2, line2P2.x()))\n if doubleNear(line2DiffY, 0): # se la retta2 é orizzontale\n return QgsPoint(getXOnInfinityLine(line1P1, line1P2, line2P2.y()), line2P2.y())\n\n line1Coeff = line1DiffY / line1DiffX\n line2Coeff = line2DiffY / line2DiffX\n\n if line1Coeff == line2Coeff: # sono parallele\n return None\n \n D = line1Coeff - line2Coeff\n # se D é così vicino a zero \n if doubleNear(D, 0.0):\n return None \n x = line1P1.x() * line1Coeff - line1P1.y() - line2P1.x() * line2Coeff + line2P1.y()\n x = x / D\n y = (x - line1P1.x()) * line1Coeff + line1P1.y()\n \n return QgsPoint(x, y)\n\n\n#===============================================================================\n# getIntersectionPointOn2Segments\n#===============================================================================\ndef getIntersectionPointOn2Segments(line1P1, line1P2, line2P1, line2P2):\n \"\"\"\n la funzione ritorna il punto di intersezione tra il segmento1 avente come estremi line1P1-line1P2 e\n il segmento2 avente come estremi line2P1-line2P2.\n \"\"\"\n ptInt = getIntersectionPointOn2InfinityLines(line1P1, line1P2, line2P1, line2P2)\n if ptInt is not None: # se non sono parallele\n # se il punto di intersezione é sui segmenti\n if isPtOnSegment(line1P1, line1P2, ptInt) and isPtOnSegment(line2P1, line2P2, ptInt):\n return QgsPoint(ptInt)\n else:\n # il segmento line2 si sovrappone a line1\n if isPtOnSegment(line1P1, line1P2, line2P1) == True and \\\n isPtOnSegment(line1P1, line1P2, line2P2) == True:\n return None\n # il segmento line1 si sovrappone a line2\n if isPtOnSegment(line2P1, line2P2, line1P1) == True and \\\n isPtOnSegment(line2P1, line2P2, line1P2) == True:\n return None\n # se il punto iniziale di line1 coincide con il punto iniziale o finale di line2\n if line1P1 == line2P1 or line1P1 == line2P2:\n return QgsPoint(line1P1) \n # se il punto finale di line1 coincide con il punto iniziale o finale di line2\n if line1P2 == line2P1 or line1P2 == line2P2:\n return QgsPoint(line1P2)\n\n return None\n\n\n#===============================================================================\n# getNearestPoints\n#===============================================================================\ndef getNearestPoints(point, points, tolerance = 0):\n \"\"\"\n Ritorna una lista di punti più vicino a point.\n \"\"\" \n result = [] \n minDist = sys.float_info.max\n \n if tolerance == 0: # solo il punto più vicino\n for pt in points:\n dist = getDistance(point, pt)\n if dist < minDist:\n minDist = dist\n nearestPoint = pt\n\n if minDist != sys.float_info.max: # trovato\n result.append(nearestPoint)\n else:\n nearest = getNearestPoints(point, points) # punto più vicino\n nearestPoint = nearest[0]\n \n for pt in points:\n dist = getDistance(nearestPoint, pt)\n if dist <= tolerance:\n result.append(pt)\n\n return result\n\n\n#===============================================================================\n# getPolarPointByPtAngle\n#===============================================================================\ndef getPolarPointByPtAngle(p1, angle, dist):\n \"\"\"\n la funzione ritorna il punto sulla retta passante per p1 con angolo <angle> che\n dista da p1 <dist>.\n \"\"\"\n y = dist * math.sin(angle)\n x = dist * math.cos(angle)\n return QgsPoint(p1.x() + x, p1.y() + y)\n\n\n#===============================================================================\n# asPointOrPolyline\n#===============================================================================\ndef asPointOrPolyline(geom):\n \"\"\"\n la funzione ritorna una lista di geometrie di punti e/o polilinee in cui viene ridotta la geometria. \n \"\"\"\n # Riduco le geometrie in point o polyline\n result = []\n for g in geom.asGeometryCollection():\n wkbType = g.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBLineString:\n result.append(g)\n elif wkbType == QGis.WKBMultiPoint:\n pointList = g.asMultiPoint() # vettore di punti\n for point in pointList:\n _g = QgsGeometry.fromPoint(point)\n result.append(_g) \n elif wkbType == QGis.WKBMultiLineString:\n lineList = g.asMultiPolyline() # vettore di linee\n for line in lineList:\n _g = QgsGeometry.fromPolyline(line)\n result.append(_g)\n elif wkbType == QGis.WKBPolygon:\n lineList = g.asPolygon() # vettore di linee \n for line in lineList:\n _g = QgsGeometry.fromPolyline(line)\n result.append(_g)\n elif wkbType == QGis.WKBMultiPolygon:\n polygonList = g.asMultiPolygon() # vettore di poligoni\n for polygon in polygonList:\n for line in polygon:\n _g = QgsGeometry.fromPolyline(line)\n result.append(_g)\n \n return result\n\n\n#===============================================================================\n# leftOfLineCoords\n#===============================================================================\ndef leftOfLineCoords(x, y, x1, y1, x2, y2):\n \"\"\"\n la funzione ritorna una numero < 0 se il punto x,y é alla sinistra della linea x1,y1 -> x2,y2\n \"\"\"\n f1 = x - x1\n f2 = y2 - y1\n f3 = y - y1\n f4 = x2 - x1\n return f1*f2 - f3*f4\n\ndef leftOfLine(pt, pt1, pt2):\n return leftOfLineCoords(pt.x(), pt.y(), pt1.x(), pt1.y(), pt2.x(), pt2.y())\n\n\n#===============================================================================\n# ptNear\n#===============================================================================\ndef ptNear(pt1, pt2, tolerance = TOLERANCE):\n \"\"\"\n la funzione compara 2 punti (ma permette una tolleranza)\n \"\"\"\n return getDistance(pt1, pt2) <= tolerance\n\n\n#===============================================================================\n# doubleNear\n#===============================================================================\ndef doubleNear(a, b, tolerance = TOLERANCE):\n \"\"\"\n la funzione compara 2 float (ma permette una tolleranza)\n \"\"\"\n diff = a - b\n return diff > -tolerance and diff <= tolerance\n\n\n#===============================================================================\n# doubleGreater\n#===============================================================================\ndef doubleGreater(a, b, tolerance = TOLERANCE):\n \"\"\"\n la funzione compara 2 float (ma permette una tolleranza)\n \"\"\"\n return a > b and not doubleNear(a, b, tolerance)\n\n\n#===============================================================================\n# doubleSmaller\n#===============================================================================\ndef doubleSmaller(a, b, tolerance = TOLERANCE):\n \"\"\"\n la funzione compara 2 float (ma permette una tolleranza)\n \"\"\"\n return a < b and not doubleNear(a, b, tolerance)\n\n\n#===============================================================================\n# TanDirectionNear\n#===============================================================================\ndef TanDirectionNear(a, b, tolerance = TOLERANCE):\n \"\"\"\n la funzione compara 2 direzioni di tangenti (ma permette una tolleranza)\n \"\"\"\n if doubleNear(a, b):\n return True\n arc = QadArc()\n arc.set(QgsPoint(0,0), 1, a, b)\n if arc.totalAngle() <= tolerance:\n return True\n else:\n arc.set(QgsPoint(0,0), 1, b, a)\n return arc.totalAngle() <= tolerance\n\n\n#===============================================================================\n# numericListAvg\n#===============================================================================\ndef numericListAvg(dblList):\n \"\"\"\n la funzione calcola la media di una lista di numeri\n \"\"\"\n if (dblList is None) or len(dblList) == 0:\n return None\n sum = 0\n for num in dblList:\n sum = sum + num\n \n return sum / len(dblList)\n\n\n#===============================================================================\n# sqrDistToSegment\n#===============================================================================\ndef sqrDistToSegment(point, x1, y1, x2, y2, epsilon):\n \"\"\"\n la funzione ritorna una lista con \n (<minima distanza al quadrato>\n <punto più vicino>)\n \"\"\"\n minDistPoint = QgsPoint()\n \n if x1 == x2 and y1 == y2:\n minDistPoint.setX(x1)\n minDistPoint.setY(y1)\n else:\n nx = y2 - y1\n ny = -( x2 - x1 )\n \n t = (point.x() * ny - point.y() * nx - x1 * ny + y1 * nx ) / (( x2 - x1 ) * ny - ( y2 - y1 ) * nx )\n \n if t < 0.0:\n minDistPoint.setX(x1)\n minDistPoint.setY(y1)\n elif t > 1.0:\n minDistPoint.setX(x2)\n minDistPoint.setY(y2)\n else:\n minDistPoint.setX( x1 + t *( x2 - x1 ) )\n minDistPoint.setY( y1 + t *( y2 - y1 ) )\n\n dist = point.sqrDist(minDistPoint)\n # prevent rounding errors if the point is directly on the segment \n if doubleNear( dist, 0.0, epsilon ):\n minDistPoint.setX( point.x() )\n minDistPoint.setY( point.y() )\n return (0.0, minDistPoint)\n \n return (dist, minDistPoint)\n\n\n#===============================================================================\n# sqrDistToArc\n#===============================================================================\ndef sqrDistToArc(point, arc):\n \"\"\"\n la funzione ritorna una lista con \n (<minima distanza al quadrato>\n <punto più vicino>)\n \"\"\" \n minDistPoint = QgsPoint()\n angle = getAngleBy2Pts(arc.center, point)\n if isAngleBetweenAngles(arc.startAngle, arc.endAngle, angle):\n distFromArc = getDistance(arc.center, point) - arc.radius\n return (distFromArc * distFromArc, getPolarPointByPtAngle(arc.center, angle, arc.radius))\n else: \n startPt = arc.getStartPt()\n endPt = arc.getEndPt()\n distFromStartPt = getSqrDistance(startPt, point)\n distFromEndPt = getSqrDistance(endPt, point)\n if distFromStartPt < distFromEndPt:\n return (distFromStartPt, startPt)\n else:\n return (distFromEndPt, endPt)\n\n\n#===============================================================================\n# closestSegmentWithContext\n#===============================================================================\ndef closestSegmentWithContext(point, geom, epsilon = 1.e-15):\n \"\"\"\n la funzione ritorna una lista con \n (<minima distanza al quadrato>\n <punto più vicino>\n <indice vertice successivo del segmento più vicino (nel caso la geom fosse linea o poligono)>\n <\"a sinistra di\" se il punto é alla sinista del segmento (< 0 -> sinistra, > 0 -> destra)\n \"\"\"\n minDistPoint = QgsPoint()\n closestSegmentIndex = 0\n wkbType = geom.wkbType()\n sqrDist = sys.float_info.max\n\n if wkbType == QGis.WKBPoint:\n minDistPoint = geom.asPoint()\n point.sqrDist(minDistPoint)\n return (point.sqrDist(minDistPoint), minDistPoint, None, None)\n \n if wkbType == QGis.WKBMultiPoint:\n minDistPoint = getNearestPoints(point, geom.asMultiPoint())[0] # vettore di punti\n return (point.sqrDist(minDistPoint), minDistPoint, None, None)\n\n if wkbType == QGis.WKBLineString:\n points = geom.asPolyline() # vettore di punti\n index = 0\n for pt in points:\n if index > 0:\n prevX = thisX\n prevY = thisY\n \n thisX = pt.x()\n thisY = pt.y()\n\n if index > 0:\n result = sqrDistToSegment(point, prevX, prevY, thisX, thisY, epsilon)\n testdist = result[0]\n distPoint = result[1] \n \n if testdist < sqrDist:\n closestSegmentIndex = index\n sqrDist = testdist\n minDistPoint = distPoint\n \n index = index + 1\n\n leftOf = leftOfLine(point, geom.vertexAt(closestSegmentIndex - 1), geom.vertexAt(closestSegmentIndex))\n return (sqrDist, minDistPoint, closestSegmentIndex, leftOf)\n\n if wkbType == QGis.WKBMultiLineString:\n lines = geom.asMultiPolyline() # lista di linee\n pointindex = 0\n for line in lines:\n prevX = 0\n prevY = 0\n \n for pt in line: # lista di punti\n thisX = pt.x()\n thisY = pt.y()\n \n if prevX and prevY:\n result = sqrDistToSegment(point, prevX, prevY, thisX, thisY, epsilon)\n testdist = result[0]\n distPoint = result[1] \n\n if testdist < sqrDist:\n closestSegmentIndex = index\n sqrDist = testdist\n minDistPoint = distPoint\n\n prevX = thisX\n prevY = thisY\n pointindex = pointindex + 1\n \n leftOf = leftOfLine(point, geom.vertexAt(closestSegmentIndex - 1), geom.vertexAt(closestSegmentIndex)) \n return (sqrDist, minDistPoint, closestSegmentIndex, leftOf)\n\n if wkbType == QGis.WKBPolygon:\n lines = geom.asPolygon() # lista di linee \n index = 0\n for line in lines:\n prevX = 0\n prevY = 0\n\n for pt in line: # lista di punti\n thisX = pt.x()\n thisY = pt.y()\n\n if prevX and prevY:\n result = sqrDistToSegment(point, prevX, prevY, thisX, thisY, epsilon)\n testdist = result[0]\n distPoint = result[1] \n\n if testdist < sqrDist:\n closestSegmentIndex = index\n sqrDist = testdist\n minDistPoint = distPoint\n\n prevX = thisX\n prevY = thisY\n index = index + 1\n \n leftOf = leftOfLine(point, geom.vertexAt(closestSegmentIndex - 1), geom.vertexAt(closestSegmentIndex))\n return (sqrDist, minDistPoint, closestSegmentIndex, leftOf)\n\n if wkbType == QGis.WKBMultiPolygon:\n polygons = geom.asMultiPolygon() # vettore di poligoni\n pointindex = 0\n for polygon in polygons:\n for line in polygon: # lista di linee\n prevX = 0\n prevY = 0\n \n for pt in line: # lista di punti\n thisX = pt.x()\n thisY = pt.y()\n \n if prevX and prevY:\n result = sqrDistToSegment(point, prevX, prevY, thisX, thisY, epsilon)\n testdist = result[0]\n distPoint = result[1] \n \n if testdist < sqrDist:\n closestSegmentIndex = pointindex\n sqrDist = testdist\n minDistPoint = distPoint\n \n prevX = thisX\n prevY = thisY\n pointindex = pointindex + 1\n \n leftOf = leftOfLine(point, geom.vertexAt(closestSegmentIndex - 1), geom.vertexAt(closestSegmentIndex))\n return (sqrDist, minDistPoint, closestSegmentIndex, leftOf)\n\n return (-1, None, None, None)\n\n\n\n#===============================================================================\n# closestVertexPtWithContext\n#===============================================================================\ndef closestVertexPtWithContext(point, geom, epsilon = 1.e-15):\n \"\"\"\n la funzione ritorna il punto del vertice più vicino a point\n \"\"\"\n wkbType = geom.wkbType()\n if wkbType == QGis.WKBPoint:\n return geom.asPoint()\n if wkbType == QGis.WKBMultiPoint:\n return getNearestPoints(point, geom.asMultiPoint())[0] # vettore di punti\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = closestSegmentWithContext(point, geom, epsilon) \n if dummy[2] is not None:\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom1 = qad_utils.getSubGeomAtVertex(geom, dummy[2])\n l = QadLinearObjectList()\n l.fromPolyline(subGeom.asPolyline())\n vertexAt = l.closestVertexWithContext(point)\n return l.getPointAtVertex(vertexAt)\n\n\n#===============================================================================\n# getBoundingPtsOnOnInfinityLine\n#===============================================================================\ndef getBoundingPtsOnOnInfinityLine(linePt1, linePt2, pts):\n \"\"\"\n Data una linea infinita passante per <linePt1> e <linePt2> e una lista di punti <pts> non ordinati sulla linea,\n la funzione ritorna i due punti estremi al fascio di punti (i due punti più lontani tra di loro).\n \"\"\"\n tot = len(pts)\n if tot < 3:\n return pts[:] # copio la lista\n \n result = [] \n # elaboro i tratti intermedi\n # calcolo la direzione dal primo punto al secondo punto \n angle = getAngleBy2Pts(pts[0], pts[1]) \n # ciclo su tutti i punti considerando solo quelli che hanno la stessa direzione con il punto precedente (boundingPt1)\n i = 2\n boundingPt1 = pts[1]\n while i < tot:\n pt2 = pts[i]\n if TanDirectionNear(angle, getAngleBy2Pts(boundingPt1, pt2)):\n boundingPt1 = pt2\n i = i + 1\n\n # calcolo la direzione dal secondo punto al primo punto \n angle = getAngleBy2Pts(pts[1], pts[0]) \n # ciclo su tutti i punti considerando solo quelli che hanno la stessa direzione con il punto precedente (boundingPt2)\n i = 2\n boundingPt2 = pts[0]\n while i < tot:\n pt2 = pts[i]\n if TanDirectionNear(angle, getAngleBy2Pts(boundingPt2, pt2)):\n boundingPt2 = pt2\n i = i + 1\n\n return [QgsPoint(boundingPt1), QgsPoint(boundingPt2)]\n\n\n#===============================================================================\n# rotatePoint\n#===============================================================================\ndef rotatePoint(point, basePt, angle):\n \"\"\"\n la funzione ruota un punto QgsPoint secondo un punto base <basePt> e un angolo <angle> in radianti \n \"\"\"\n return getPolarPointByPtAngle(basePt, getAngleBy2Pts(basePt, point) + angle, getDistance(basePt, point))\n\n\n#===============================================================================\n# rotateQgsGeometry\n#===============================================================================\ndef rotateQgsGeometry(geom, basePt, angle):\n \"\"\"\n la funzione ruota la geometria secondo un punto base <basePt> e un angolo <angle> in radianti\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = geom.asPoint() # un punto\n newPt = rotatePoint(pt, basePt, angle)\n return QgsGeometry.fromPoint(newPt)\n\n if wkbType == QGis.WKBMultiPoint:\n points = geom.asMultiPoint() # vettore di punti\n for pt in points:\n newPt = rotatePoint(pt, basePt, angle)\n pt.set(newPt.x(), newPt.y())\n return QgsGeometry.fromMultiPoint(points)\n \n if wkbType == QGis.WKBLineString:\n points = geom.asPolyline() # vettore di punti\n for pt in points:\n newPt = rotatePoint(pt, basePt, angle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolyline(points)\n \n if wkbType == QGis.WKBMultiLineString:\n lines = geom.asMultiPolyline() # lista di linee\n for line in lines: \n for pt in line: # lista di punti\n newPt = rotatePoint(pt, basePt, angle)\n pt.set(newPt.x(), newPt.y())\n\n return QgsGeometry.fromMultiPolyline(lines)\n \n if wkbType == QGis.WKBPolygon:\n lines = geom.asPolygon() # lista di linee \n for line in lines:\n for pt in line: # lista di punti\n newPt = rotatePoint(pt, basePt, angle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolygon(lines)\n\n if wkbType == QGis.WKBMultiPolygon:\n polygons = geom.asMultiPolygon() # vettore di poligoni\n for polygon in polygons:\n for line in polygon: # lista di linee\n for pt in line: # lista di punti\n newPt = rotatePoint(pt, basePt, angle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromMultiPolygon(polygons)\n\n return None\n\n\n#===============================================================================\n# scalePoint\n#===============================================================================\ndef scalePoint(point, basePt, scale):\n \"\"\"\n la funzione scala un punto QgsPoint secondo un punto base <basePt> e un fattore di scala\n \"\"\"\n return getPolarPointByPtAngle(basePt, getAngleBy2Pts(basePt, point), getDistance(basePt, point) * scale)\n\n\n#===============================================================================\n# scaleQgsGeometry\n#===============================================================================\ndef scaleQgsGeometry(geom, basePt, scale):\n \"\"\"\n la funzione scala la geometria secondo un punto base <basePt> e un fattore di scala\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = geom.asPoint() # un punto\n newPt = scalePoint(pt, basePt, scale)\n return QgsGeometry.fromPoint(newPt)\n\n if wkbType == QGis.WKBMultiPoint:\n points = geom.asMultiPoint() # vettore di punti\n for pt in points:\n newPt = scalePoint(pt, basePt, scale)\n pt.set(newPt.x(), newPt.y())\n return QgsGeometry.fromMultiPoint(points)\n \n if wkbType == QGis.WKBLineString:\n points = geom.asPolyline() # vettore di punti\n for pt in points:\n newPt = scalePoint(pt, basePt, scale)\n pt.set(newPt.x(), newPt.y())\n \n return ApproxCurvesOnGeom(QgsGeometry.fromPolyline(points)) \n \n if wkbType == QGis.WKBMultiLineString:\n lines = geom.asMultiPolyline() # lista di linee\n for line in lines: \n for pt in line: # lista di punti\n newPt = scalePoint(pt, basePt, scale)\n pt.set(newPt.x(), newPt.y())\n\n return ApproxCurvesOnGeom(QgsGeometry.fromMultiPolyline(lines)) \n\n if wkbType == QGis.WKBPolygon:\n lines = geom.asPolygon() # lista di linee \n for line in lines:\n for pt in line: # lista di punti\n newPt = scalePoint(pt, basePt, scale)\n pt.set(newPt.x(), newPt.y())\n \n return ApproxCurvesOnGeom(QgsGeometry.fromPolygon(lines)) \n\n if wkbType == QGis.WKBMultiPolygon:\n polygons = geom.asMultiPolygon() # vettore di poligoni\n for polygon in polygons:\n for line in polygon: # lista di linee\n for pt in line: # lista di punti\n newPt = scalePoint(pt, basePt, scale)\n pt.set(newPt.x(), newPt.y())\n \n return ApproxCurvesOnGeom(QgsGeometry.fromMultiPolygon(polygons))\n\n return None\n\n\n#===============================================================================\n# movePoint\n#===============================================================================\ndef movePoint(point, offSetX, offSetY):\n \"\"\"\n la funzione sposta un punto QgsPoint secondo un offset X e uno Y\n \"\"\"\n return QgsPoint(point.x() + offSetX, point.y() + offSetY)\n\n\n#===============================================================================\n# moveQgsGeometry\n#===============================================================================\ndef moveQgsGeometry(geom, offSetX, offSetY):\n \"\"\"\n la funzione sposta la geometria secondo un offset X uno Y\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = geom.asPoint() # un punto\n newPt = movePoint(pt, offSetX, offSetY)\n return QgsGeometry.fromPoint(newPt)\n\n if wkbType == QGis.WKBMultiPoint:\n points = geom.asMultiPoint() # vettore di punti\n for pt in points:\n newPt = movePoint(pt, offSetX, offSetY)\n pt.set(newPt.x(), newPt.y())\n return QgsGeometry.fromMultiPoint(points)\n \n if wkbType == QGis.WKBLineString:\n points = geom.asPolyline() # vettore di punti\n for pt in points:\n newPt = movePoint(pt, offSetX, offSetY)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolyline(points)\n \n if wkbType == QGis.WKBMultiLineString:\n lines = geom.asMultiPolyline() # lista di linee\n for line in lines: \n for pt in line: # lista di punti\n newPt = movePoint(pt, offSetX, offSetY)\n pt.set(newPt.x(), newPt.y())\n\n return QgsGeometry.fromMultiPolyline(lines)\n \n if wkbType == QGis.WKBPolygon:\n lines = geom.asPolygon() # lista di linee \n for line in lines:\n for pt in line: # lista di punti\n newPt = movePoint(pt, offSetX, offSetY)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolygon(lines)\n\n if wkbType == QGis.WKBMultiPolygon:\n polygons = geom.asMultiPolygon() # vettore di poligoni\n for polygon in polygons:\n for line in polygon: # lista di linee\n for pt in line: # lista di punti\n newPt = movePoint(pt, offSetX, offSetY)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromMultiPolygon(polygons)\n\n return None\n\n\n#===============================================================================\n# extendQgsGeometry\n#===============================================================================\ndef extendQgsGeometry(geom_crs, geom, pt, limitEntitySet, edgeMode, tolerance2ApproxCurve):\n \"\"\"\n la funzione estende la geometria (lineare) nella parte iniziale o finale fino ad\n incontrare l'oggetto più vicino nel gruppo <limitEntitySet> secondo la modalità <edgeMode>.\n <geom_crs> = sistema di coordinate della geometria da estendere\n <geom> = geometria da estendere\n <pt> = punto che indica il sotto-oggetto grafico (se si tratta di WKBMultiLineString)\n e la parte di quell'oggetto che deve essere estesa\n <QadEntitySet> = gruppo di entità che serve da limite di estensione\n <edgeMode> se = 0 si deve estendere la geometria fino ad incontrare l'oggetto più vicino\n se = 1 si deve estendere la geometria fino ad incontrare l'oggetto più vicino o \n anche il suo prolungamento\n <tolerance2ApproxCurve> = tolleranza di approssimazione per le curve\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType != QGis.WKBLineString and wkbType != QGis.WKBMultiLineString:\n return None\n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = closestSegmentWithContext(pt, geom)\n if dummy[2] is None:\n return None\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = getSubGeomAtVertex(geom, dummy[2])\n \n LinearObjectListToExtend = QadLinearObjectList()\n LinearObjectListToExtend.fromPolyline(subGeom.asPolyline())\n \n if LinearObjectListToExtend.isClosed(): # non si può fare con polilinea chiusa\n return None\n \n # stabilisco se devo considerare l'inizio o la fine della polilinea\n if subGeom.vertexAt(0) == pt:\n distFromStart = 0\n else:\n distFromStart = QgsGeometry.fromPolyline(getLinePart(subGeom, \\\n subGeom.vertexAt(0), \\\n pt)).length()\n if distFromStart > (subGeom.length() / 2):\n # parte finale\n LinearObjectToExtend = LinearObjectListToExtend.getLinearObjectAt(-1)\n else:\n # parte iniziale\n LinearObjectToExtend = QadLinearObject(LinearObjectListToExtend.getLinearObjectAt(0))\n LinearObjectToExtend.reverse()\n\n minDist = sys.float_info.max\n newPt = None\n ExtendedLinearObject = QadLinearObject()\n gTransformed = QgsGeometry()\n \n # per ciascun layer \n for limitLayerEntitySet in limitEntitySet.layerEntitySetList:\n limitLayer = limitLayerEntitySet.layer\n \n if limitLayer.crs() != geom_crs:\n coordTransform = QgsCoordinateTransform(limitLayer.crs(), geom_crs)\n ExtendedLinearObject.set(LinearObjectToExtend)\n \n # per ciascuna entità del layer\n for featureId in limitLayerEntitySet.featureIds:\n f = getFeatureById(limitLayer, featureId)\n if f is None:\n continue\n \n # Trasformo la geometria limite nel sistema di coordinate del <layer> \n gTransformed = f.geometry()\n if limitLayer.crs() != geom_crs:\n gTransformed.transform(coordTransform)\n \n intPt = getIntersectionPtExtendQgsGeometry(LinearObjectToExtend, gTransformed, edgeMode)\n if intPt is not None:\n # cerco il punto di intersezione più vicino al punto finale di linearObject\n ExtendedLinearObject.setEndPt(intPt)\n if ExtendedLinearObject.length() < minDist:\n minDist = ExtendedLinearObject.length()\n newPt = intPt\n \n if newPt is None:\n return None\n \n if distFromStart > (subGeom.length() / 2):\n # modifico la parte finale\n LinearObjectListToExtend.getLinearObjectAt(-1).setEndPt(newPt)\n else:\n # modifico la parte iniziale\n LinearObjectListToExtend.getLinearObjectAt(0).setStartPt(newPt)\n \n pts = LinearObjectListToExtend.asPolyline(tolerance2ApproxCurve)\n \n return setSubGeom(geom, QgsGeometry.fromPolyline(pts), atSubGeom) \n\n\n#===============================================================================\n# getIntersectionPtExtendQgsGeometry\n#===============================================================================\ndef getIntersectionPtExtendQgsGeometry(linearObject, limitGeom, edgeMode):\n \"\"\"\n la funzione calcola il punto di intersezione tra il prolungamento della parte lineare\n oltre il punto finale fino ad incontrare la geometria <limitGeom> secondo la modalità <edgeMode>.\n Viene restituito il punto più vicino al punto finale di <linearObject>.\n <linearObject> = parte lineare da estendere\n <limitGeom> = geometria da usare come limite di estensione\n <edgeMode> se = 0 si deve estendere la geometria fino ad incontrare l'oggetto più vicino\n se = 1 si deve estendere la geometria fino ad incontrare l'oggetto più vicino o \n anche il suo prolungamento\n \"\"\"\n intPts = []\n limitLinearObjectParts = QadLinearObjectList()\n \n # riduco in polilinee\n limitGeoms = asPointOrPolyline(limitGeom)\n for limitGeom in limitGeoms: \n Found = False\n wkbType = limitGeom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = limitGeom.asPoint()\n if linearObject.isSegment():\n if isPtOnInfinityLine(linearObject.getStartPt(), linearObject.getEndPt(), pt):\n intPts.append(pt)\n else: # arco\n circle = QadCircle()\n circle.set(linearObject.getArc().center, linearObject.getArc().radius)\n if circle.isPtOnCircle(pt):\n intPts.append(pt) \n else: # Linestring\n limitLinearObjectParts.fromPolyline(limitGeom.asPolyline())\n \n # primo tratto\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(0)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n if edgeMode == 0: # senza estendere\n # considero solo i punti sulla parte <LimitLinearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n del pts[i]\n else:\n if LimitLinearObject.isSegment():\n # considero solo i punti sulla parte <LimitLinearObject> o oltre l'inizio\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n if getDistance(LimitLinearObject.getStartPt(), pt) > \\\n getDistance(LimitLinearObject.getEndPt(), pt):\n del pts[i]\n intPts.extend(pts)\n \n # elaboro i tratti intermedi\n i = 1\n while i < limitLinearObjectParts.qty() - 1:\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(i)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n # considero solo i punti sulla parte <LimitLinearObject>\n for j in xrange(len(pts) - 1, -1, -1):\n pt = pts[j]\n if LimitLinearObject.containsPt(pt) == False:\n del pts[j]\n \n intPts.extend(pts)\n i = i + 1\n\n # ultimo tratto\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(-1)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n if edgeMode == 0: # senza estendere\n # considero solo i punti sulla parte <LimitLinearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n del pts[i]\n else:\n if LimitLinearObject.isSegment():\n # considero solo i punti sulla parte <LimitLinearObject> o oltre la fine\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n if getDistance(LimitLinearObject.getStartPt(), pt) < \\\n getDistance(LimitLinearObject.getEndPt(), pt):\n del pts[i]\n intPts.extend(pts)\n\n # cancello i punti di intersezione che non sono oltre la fine di linearObject\n for i in xrange(len(intPts) - 1, -1, -1):\n if linearObject.containsPt(intPts[i]) == True:\n del intPts[i]\n else:\n if linearObject.isSegment():\n if getDistance(linearObject.getStartPt(), intPts[i]) < \\\n getDistance(linearObject.getEndPt(), intPts[i]):\n del intPts[i]\n\n if len(intPts) == 0:\n return None\n \n # cerco il punto di intersezione più vicino al punto finale di linearObject\n minDist = sys.float_info.max\n LimitLinearObject.set(linearObject)\n for intPt in intPts:\n LimitLinearObject.setEndPt(intPt) \n if LimitLinearObject.length() < minDist:\n minDist = LimitLinearObject.length()\n pt = intPt\n \n return pt\n \n\n#===============================================================================\n# trimQgsGeometry\n#===============================================================================\ndef trimQgsGeometry(geom_crs, geom, pt, limitEntitySet, edgeMode, tolerance2ApproxCurve):\n \"\"\"\n la funzione taglia la geometria (lineare) in una parte i cui limiti sono le intersezioni più\n vicine a pt con gli oggetti del gruppo <limitEntitySet> secondo la modalità <edgeMode>.\n <geom_crs> = sistema di coordinate della geometria da tagliare\n <geom> = geometria da tagliare\n <pt> = punto che indica il sotto-oggetto grafico (se si tratta di WKBMultiLineString)\n e la parte di quell'oggetto che deve essere tagliata\n <QadEntitySet> = gruppo di entità che serve da limite di taglio\n <edgeMode> se = 0 si deve estendere la geometria fino ad incontrare l'oggetto più vicino\n se = 1 si deve estendere la geometria fino ad incontrare l'oggetto più vicino o \n anche il suo prolungamento\n <tolerance2ApproxCurve> = tolleranza di approssimazione per le curve\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType != QGis.WKBLineString and wkbType != QGis.WKBMultiLineString and \\\n wkbType != QGis.WKBPolygon and wkbType != QGis.WKBMultiPolygon:\n return None\n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = closestSegmentWithContext(pt, geom)\n if dummy[2] is None:\n return None\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = getSubGeomAtVertex(geom, dummy[2])\n \n LinearObjectListToCut = QadLinearObjectList()\n LinearObjectListToCut.fromPolyline(subGeom.asPolyline())\n \n # divido la polilinea in 2\n dummy = LinearObjectListToCut.breakOnPt(pt)\n partList1ToTrim = dummy[0]\n partList2ToTrim = dummy[1]\n\n trimmedLinearObject = QadLinearObject()\n gTransformed = QgsGeometry()\n \n # cerco intersezione più vicina a pt nella prima parte\n newPt1 = None\n geom1 = None\n if partList1ToTrim is not None:\n partList1ToTrim.reverse()\n newPt1, partNumberAtpartList1 = partList1ToTrim.getIntPtNearestToStartPt(geom_crs, limitEntitySet, edgeMode)\n if newPt1 is None: # nessuna intersezione\n if LinearObjectListToCut.isClosed(): # se é chiusa\n if partList2ToTrim is None:\n return None \n partList2ToTrim.reverse()\n newPt, partNumberAtpartList = partList2ToTrim.getIntPtNearestToStartPt(geom_crs, limitEntitySet, edgeMode)\n if newPt is None:\n return None\n for i in xrange(0, partNumberAtpartList, 1):\n partList2ToTrim.remove(0)\n # modifico la parte iniziale della prima parte\n partList2ToTrim.getLinearObjectAt(0).setStartPt(newPt)\n partList2ToTrim.reverse()\n else:\n for i in xrange(0, partNumberAtpartList1, 1):\n partList1ToTrim.remove(0)\n # modifico la parte iniziale della prima parte\n partList1ToTrim.getLinearObjectAt(0).setStartPt(newPt1)\n geom1 = QgsGeometry.fromPolyline(partList1ToTrim.asPolyline(tolerance2ApproxCurve))\n\n partList1ToTrim.reverse()\n \n # cerco intersezione più vicina a pt nella seconda parte\n newPt2 = None \n if partList2ToTrim is not None:\n newPt2, partNumberAtpartList2 = partList2ToTrim.getIntPtNearestToStartPt(geom_crs, limitEntitySet, edgeMode)\n if newPt2 is None: # nessuna intersezione\n if LinearObjectListToCut.isClosed(): # se é chiusa\n if partList1ToTrim is None:\n return None \n newPt, partNumberAtpartList = partList1ToTrim.getIntPtNearestToStartPt(geom_crs, limitEntitySet, edgeMode)\n if newPt is None:\n return None\n for i in xrange(0, partNumberAtpartList, 1):\n partList1ToTrim.remove(0)\n # modifico la parte iniziale della prima parte\n partList1ToTrim.getLinearObjectAt(0).setStartPt(newPt)\n\n if newPt1 is None and newPt2 is None: # non ci sono punti di intersezione\n return None\n if newPt1 is not None and newPt2 is not None:\n if ptNear(newPt1, newPt2): # i due punti di intersezione coincidono\n return None\n \n if newPt2 is not None:\n for i in xrange(0, partNumberAtpartList2, 1):\n partList2ToTrim.remove(0)\n # modifico la parte iniziale della seconda parte\n partList2ToTrim.getLinearObjectAt(0).setStartPt(newPt2)\n geom2 = QgsGeometry.fromPolyline(partList2ToTrim.asPolyline(tolerance2ApproxCurve))\n if geom1 is None:\n return [geom2, None, atSubGeom] \n else:\n geom2 = None\n \n return [geom1, geom2, atSubGeom] \n\n\n#===============================================================================\n# getIntersectionPtTrimQgsGeometry\n#===============================================================================\ndef getIntersectionPtTrimQgsGeometry(linearObject, limitGeom, edgeMode):\n \"\"\"\n la funzione calcola il punto di intersezione tra la parte lineare\n e la geometria <limitGeom> secondo la modalità <edgeMode>.\n Viene restituito il punto più vicino al punto iniziale di <linearObject>.\n <linearObject> = parte lineare da estendere\n <limitGeom> = geometria da usare come limite di estensione\n <edgeMode> se = 0 si deve estendere la geometria fino ad incontrare l'oggetto più vicino\n se = 1 si deve estendere la geometria fino ad incontrare l'oggetto più vicino o \n anche il suo prolungamento\n \"\"\"\n intPts = []\n limitLinearObjectParts = QadLinearObjectList()\n \n # riduco in polilinee\n limitGeoms = asPointOrPolyline(limitGeom)\n for limitGeom in limitGeoms: \n Found = False\n wkbType = limitGeom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = limitGeom.asPoint()\n if linearObject.containsPt(pt):\n intPts.append(pt)\n else: # Linestring\n limitLinearObjectParts.fromPolyline(limitGeom.asPolyline())\n \n # primo tratto\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(0)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n if edgeMode == 0: # senza estendere\n # considero solo i punti sulla parte <LimitLinearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n del pts[i]\n else:\n if LimitLinearObject.isSegment():\n # considero solo i punti sulla parte <LimitLinearObject> o oltre l'inizio\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n if getDistance(LimitLinearObject.getStartPt(), pt) > \\\n getDistance(LimitLinearObject.getEndPt(), pt):\n del pts[i]\n \n # considero solo i punti sulla parte <linearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if linearObject.containsPt(pt) == False:\n del pts[i]\n\n intPts.extend(pts)\n \n # elaboro i tratti intermedi\n i = 1\n while i < limitLinearObjectParts.qty() - 1:\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(i)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n # considero solo i punti sulla parte <LimitLinearObject> e <linearObject>\n for j in xrange(len(pts) - 1, -1, -1):\n pt = pts[j]\n if LimitLinearObject.containsPt(pt) == False or linearObject.containsPt(pt) == False:\n del pts[j]\n \n intPts.extend(pts)\n i = i + 1\n\n # ultimo tratto\n LimitLinearObject = limitLinearObjectParts.getLinearObjectAt(-1)\n pts = linearObject.getIntersectionPtsOnExtensionWithLinearObject(LimitLinearObject) \n if edgeMode == 0: # senza estendere\n # considero solo i punti sulla parte <LimitLinearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n del pts[i]\n else:\n if LimitLinearObject.isSegment():\n # considero solo i punti sulla parte <LimitLinearObject> o oltre la fine\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if LimitLinearObject.containsPt(pt) == False:\n if getDistance(LimitLinearObject.getStartPt(), pt) < \\\n getDistance(LimitLinearObject.getEndPt(), pt):\n del pts[i]\n \n # considero solo i punti sulla parte <linearObject>\n for i in xrange(len(pts) - 1, -1, -1):\n pt = pts[i]\n if linearObject.containsPt(pt) == False:\n del pts[i]\n \n intPts.extend(pts)\n\n if len(intPts) == 0:\n return None\n \n # cerco il punto di intersezione più vicino al punto iniziale di linearObject\n minDist = sys.float_info.max\n LimitLinearObject.set(linearObject)\n for intPt in intPts:\n LimitLinearObject.setEndPt(intPt) \n if LimitLinearObject.length() < minDist:\n minDist = LimitLinearObject.length()\n pt = intPt\n \n return pt\n \n\n#===============================================================================\n# breakQgsGeometry\n#===============================================================================\ndef breakQgsGeometry(geom, firstPt, secondPt, tolerance2ApproxCurve):\n \"\"\"\n la funzione spezza la geometria in un punto (se <secondPt> = None) o in due punti \n come fa il trim.\n <geom> = geometria da tagliare\n <firstPt> = primo punto di divisione\n <secondPt> = secondo punto di divisione\n <tolerance2ApproxCurve> = tolleranza di approssimazione per le curve\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType()\n \n if wkbType != QGis.WKBLineString and wkbType != QGis.WKBMultiLineString and \\\n wkbType != QGis.WKBPolygon and wkbType != QGis.WKBMultiPolygon:\n return None\n\n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = closestSegmentWithContext(firstPt, geom)\n myFirstPt = dummy[1]\n if dummy[2] is None:\n return None\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = getSubGeomAtVertex(geom, dummy[2])\n\n mySecondPt = None\n if secondPt is not None:\n dummy = closestSegmentWithContext(secondPt, geom)\n mySecondPt = dummy[1]\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeomSeconPt, atSubGeomSecondPt = getSubGeomAtVertex(geom, dummy[2])\n # se le sottogeometrie sono diverse\n if len(atSubGeom) != len(atSubGeomSecondPt):\n return None\n i = 0\n while i < len(atSubGeom):\n if atSubGeom[i] != atSubGeomSecondPt[i]:\n return None\n i = i + 1\n \n LinearObjectListToCut = QadLinearObjectList()\n LinearObjectListToCut.fromPolyline(subGeom.asPolyline())\n\n geom1 = None\n geom2 = None\n \n if mySecondPt is None or myFirstPt == mySecondPt:\n # divido la polilinea in 2\n dummy = LinearObjectListToCut.breakOnPt(myFirstPt)\n partList1ToTrim = dummy[0]\n partList2ToTrim = dummy[1]\n if LinearObjectListToCut.isClosed(): # se é chiusa\n return None\n else:\n if partList1ToTrim is not None:\n geom1 = QgsGeometry.fromPolyline(partList1ToTrim.asPolyline(tolerance2ApproxCurve))\n if partList2ToTrim is not None:\n geom2 = QgsGeometry.fromPolyline(partList2ToTrim.asPolyline(tolerance2ApproxCurve))\n \n return [geom1, geom2, atSubGeom]\n else: # c'é anche il secondo punto di divisione\n dist1 = LinearObjectListToCut.getDistanceFromStart(myFirstPt)\n dist2 = LinearObjectListToCut.getDistanceFromStart(mySecondPt)\n if dist1 < dist2:\n p1 = myFirstPt\n p2 = mySecondPt\n else:\n p1 = mySecondPt\n p2 = myFirstPt\n \n # divido la polilinea in 2\n dummy = LinearObjectListToCut.breakOnPt(p1)\n partList1ToTrim = dummy[0]\n partList2ToTrim = dummy[1]\n if partList2ToTrim is not None:\n # divido la polilinea in 2\n dummy = partList2ToTrim.breakOnPt(p2)\n partList2ToTrim = dummy[1]\n \n if LinearObjectListToCut.isClosed(): # se é chiusa\n if partList2ToTrim is None:\n partList2ToTrim = QadLinearObjectList() \n if partList1ToTrim is not None:\n for linearObject in partList1ToTrim.defList:\n partList2ToTrim.append(linearObject)\n \n if partList2ToTrim.qty() > 0:\n circle = LinearObjectListToCut.getCircle() \n if circle is not None: # se era una cerchio\n arc = QadArc()\n linearObject = partList2ToTrim.getLinearObjectAt(0)\n arc.fromStartSecondEndPts(linearObject.getStartPt(), linearObject.getEndPt(), partList2ToTrim.getEndPt()) \n geom1 = QgsGeometry.fromPolyline(arc.asPolyline(tolerance2ApproxCurve)) \n else:\n geom1 = QgsGeometry.fromPolyline(partList2ToTrim.asPolyline(tolerance2ApproxCurve)) \n else: # se é aperta\n if partList1ToTrim is not None:\n geom1 = QgsGeometry.fromPolyline(partList1ToTrim.asPolyline(tolerance2ApproxCurve)) \n if partList2ToTrim is not None:\n geom2 = QgsGeometry.fromPolyline(partList2ToTrim.asPolyline(tolerance2ApproxCurve))\n if geom1 is None and geom2 is None:\n return None\n\n return [geom1, geom2, atSubGeom]\n \n\n#===============================================================================\n# mirrorPoint\n#===============================================================================\ndef mirrorPoint(point, mirrorPt, mirrorAngle):\n \"\"\"\n la funzione sposta un punto QgsPoint secondo una linea speculare passante per un \n un punto <mirrorPt> ed avente angolo <mirrorAngle>\n \"\"\"\n pointAngle = getAngleBy2Pts(mirrorPt, point)\n dist = getDistance(mirrorPt, point)\n \n return getPolarPointByPtAngle(mirrorPt, mirrorAngle + (mirrorAngle - pointAngle), dist)\n\n#===============================================================================\n# mirrorQgsGeometry\n#===============================================================================\ndef mirrorQgsGeometry(geom, pt1, pt2):\n \"\"\"\n la funzione crea copia speculare della geometria secondo una linea <pt1> <pt2>\n \"\"\"\n if geom is None:\n return None\n\n mirrorAngle = getAngleBy2Pts(pt1, pt2)\n wkbType = geom.wkbType() \n \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = geom.asPoint() # un punto\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n return QgsGeometry.fromPoint(newPt)\n\n if wkbType == QGis.WKBMultiPoint:\n points = geom.asMultiPoint() # vettore di punti\n for pt in points:\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n pt.set(newPt.x(), newPt.y())\n return QgsGeometry.fromMultiPoint(points)\n \n if wkbType == QGis.WKBLineString:\n points = geom.asPolyline() # vettore di punti\n for pt in points:\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolyline(points)\n \n if wkbType == QGis.WKBMultiLineString:\n lines = geom.asMultiPolyline() # lista di linee\n for line in lines: \n for pt in line: # lista di punti\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n pt.set(newPt.x(), newPt.y())\n\n return QgsGeometry.fromMultiPolyline(lines)\n \n if wkbType == QGis.WKBPolygon:\n lines = geom.asPolygon() # lista di linee \n for line in lines:\n for pt in line: # lista di punti\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromPolygon(lines)\n\n if wkbType == QGis.WKBMultiPolygon:\n polygons = geom.asMultiPolygon() # vettore di poligoni\n for polygon in polygons:\n for line in polygon: # lista di linee\n for pt in line: # lista di punti\n newPt = mirrorPoint(pt, pt1, mirrorAngle)\n pt.set(newPt.x(), newPt.y())\n \n return QgsGeometry.fromMultiPolygon(polygons)\n\n return None\n\n\n#===============================================================================\n# closeQgsGeometry\n#===============================================================================\ndef closeQgsGeometry(geom, toClose, tolerance2ApproxCurve):\n \"\"\"\n la funzione chiude o apre la geometria\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType() \n \n if wkbType == QGis.WKBLineString:\n linearObjectList = QadLinearObjectList()\n linearObjectList.fromPolyline(geom.asPolyline())\n linearObjectList.setClose(toClose)\n return QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n \n if wkbType == QGis.WKBMultiLineString:\n newGeom = QgsGeometry(geom)\n lines = geom.asMultiPolyline() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = closeQgsGeometry(QgsGeometry.fromPolyline(line), toClose, tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom \n\n return None\n\n\n#===============================================================================\n# reverseQgsGeometry\n#===============================================================================\ndef reverseQgsGeometry(geom, tolerance2ApproxCurve):\n \"\"\"\n la funzione inverte l'ordine dei punti della geometria\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType() \n \n if wkbType == QGis.WKBLineString:\n linearObjectList = QadLinearObjectList()\n linearObjectList.fromPolyline(geom.asPolyline())\n linearObjectList.reverse()\n return QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n \n if wkbType == QGis.WKBMultiLineString:\n newGeom = QgsGeometry(geom)\n lines = geom.asMultiPolyline() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = reverseQgsGeometry(QgsGeometry.fromPolyline(line), tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom \n\n if wkbType == QGis.WKBPolygon:\n newGeom = QgsGeometry(geom)\n lines = geom.asPolygon() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = reverseQgsGeometry(QgsGeometry.fromPolyline(line), tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom\n \n if wkbType == QGis.WKBMultiPolygon:\n newGeom = QgsGeometry(geom)\n polygons = geom.asMultiPolygon() # vettore di poligoni\n atSubGeom = 0\n for polygon in polygons:\n subGeom = reverseQgsGeometry(QgsGeometry.fromPolygon(polygon), tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom\n\n return None\n\n\n#===============================================================================\n# curveQgsGeometry\n#===============================================================================\ndef curveQgsGeometry(geom, toCurve, tolerance2ApproxCurve):\n \"\"\"\n se toCurve = True:\n la funzione curva ogni segmento per adattarlo alla polilinea (lista di parti segmenti-archi).\n se toCurve = False:\n la funzione trasforma in segmento retto ogni arco della polilinea (lista di parti segmenti-archi).\n \"\"\"\n if geom is None:\n return None\n\n wkbType = geom.wkbType() \n \n if wkbType == QGis.WKBLineString:\n linearObjectList = QadLinearObjectList()\n linearObjectList.fromPolyline(geom.asPolyline())\n linearObjectList.curve(toCurve)\n\n return QgsGeometry.fromPolyline(linearObjectList.asPolyline(tolerance2ApproxCurve))\n \n if wkbType == QGis.WKBMultiLineString:\n newGeom = QgsGeometry(geom)\n lines = geom.asMultiPolyline() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = curveQgsGeometry(QgsGeometry.fromPolyline(line), toCurve, tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom \n\n if wkbType == QGis.WKBPolygon:\n newGeom = QgsGeometry(geom)\n lines = geom.asPolygon() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = curveQgsGeometry(QgsGeometry.fromPolyline(line), toCurve, tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom\n \n if wkbType == QGis.WKBMultiPolygon:\n newGeom = QgsGeometry(geom)\n polygons = geom.asMultiPolygon() # vettore di poligoni\n atSubGeom = 0\n for polygon in polygons:\n subGeom = curveQgsGeometry(QgsGeometry.fromPolygon(polygon), toCurve, tolerance2ApproxCurve)\n newGeom = setSubGeom(newGeom, subGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return newGeom\n\n return None\n\n\n#===============================================================================\n# funzioni di creazione rettangoli\n# getRectByCorners\n#===============================================================================\ndef getRectByCorners(firstCorner, secondCorner, rot, gapType, \\\n gapValue1 = None, gapValue2 = None, tolerance2ApproxCurve = None):\n \"\"\"\n ritorna una lista di punti che definisce il rettangolo costruito mediante \n i due spigoli opposti firstCorner e secondCorner, la rotazione con punto base firstCorner e gapType \n 0 = gli spigoli del rettangolo hanno angoli retti\n 1 = raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n 2 = smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2\n tolerance2ApproxCurve = errore minimo di tolleranza per rappresentare le curve\n \"\"\"\n # creo un rettangolo ruotato con con angoli retti\n secondCornerProj = getPolarPointByPtAngle(firstCorner, rot, 10)\n pt2 = getPerpendicularPointOnInfinityLine(firstCorner, secondCornerProj, secondCorner)\n angle = getAngleBy2Pts(firstCorner, pt2)\n pt4 = getPolarPointByPtAngle(secondCorner, angle + math.pi, \\\n getDistance(firstCorner, pt2))\n \n if gapType == 0: # gli spigoli del rettangolo hanno angoli retti\n return [QgsPoint(firstCorner), pt2, QgsPoint(secondCorner), pt4, QgsPoint(firstCorner)]\n else:\n length = getDistance(firstCorner, pt2)\n width = getDistance(pt2, secondCorner)\n \n if gapType == 1: # raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n if (gapValue1 * 2) > length or (gapValue1 * 2) > width: # il rettangolo é troppo piccolo\n return [QgsPoint(firstCorner), pt2, QgsPoint(secondCorner), pt4, QgsPoint(firstCorner)]\n \n if tolerance2ApproxCurve is None:\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n else:\n tolerance = tolerance2ApproxCurve\n \n diagonal = math.sqrt((gapValue1 * gapValue1) * 2)\n diagonal = gapValue1 - (diagonal / 2)\n LinearObjectList = QadLinearObjectList()\n \n # lato\n p1 = getPolarPointByPtAngle(firstCorner, angle, gapValue1)\n p2 = getPolarPointByPtAngle(pt2, angle + math.pi, gapValue1) \n LinearObjectList.append([p1, p2])\n # arco\n angle = getAngleBy2Pts(pt2, secondCorner)\n p3 = getPolarPointByPtAngle(pt2, angle, gapValue1)\n pMiddle = getMiddlePoint(p2, p3)\n pMiddle = getPolarPointByPtAngle(pMiddle, getAngleBy2Pts(pMiddle, pt2), diagonal) \n arc = QadArc()\n arc.fromStartSecondEndPts(p2, pMiddle, p3)\n Inverse = False if ptNear(arc.getStartPt(), p2) else True\n LinearObjectList.append([arc, Inverse])\n # lato\n p4 = getPolarPointByPtAngle(secondCorner, angle + math.pi, gapValue1)\n LinearObjectList.append([p3, p4])\n # arco \n angle = getAngleBy2Pts(secondCorner, pt4)\n p5 = getPolarPointByPtAngle(secondCorner, angle, gapValue1)\n pMiddle = getMiddlePoint(p4, p5)\n pMiddle = getPolarPointByPtAngle(pMiddle, getAngleBy2Pts(pMiddle, secondCorner), diagonal) \n arc = QadArc()\n arc.fromStartSecondEndPts(p4, pMiddle, p5)\n Inverse = False if ptNear(arc.getStartPt(), p4) else True\n LinearObjectList.append([arc, Inverse]) \n # lato\n p6 = getPolarPointByPtAngle(pt4, angle + math.pi, gapValue1)\n LinearObjectList.append([p5, p6])\n # arco\n angle = getAngleBy2Pts(pt4, firstCorner)\n p7 = getPolarPointByPtAngle(pt4, angle, gapValue1)\n pMiddle = getMiddlePoint(p6, p7)\n pMiddle = getPolarPointByPtAngle(pMiddle, getAngleBy2Pts(pMiddle, pt4), diagonal) \n arc = QadArc()\n arc.fromStartSecondEndPts(p6, pMiddle, p7)\n Inverse = False if ptNear(arc.getStartPt(), p6) else True\n LinearObjectList.append([arc, Inverse]) \n # lato\n p8 = getPolarPointByPtAngle(firstCorner, angle + math.pi, gapValue1)\n LinearObjectList.append([p7, p8])\n # arco\n pMiddle = getMiddlePoint(p8, p1)\n pMiddle = getPolarPointByPtAngle(pMiddle, getAngleBy2Pts(pMiddle, firstCorner), diagonal) \n arc = QadArc()\n arc.fromStartSecondEndPts(p8, pMiddle, p1)\n Inverse = False if ptNear(arc.getStartPt(), p8) else True\n LinearObjectList.append([arc, Inverse])\n return LinearObjectList.asPolyline(tolerance)\n elif gapType == 2: # smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2\n if (gapValue1 + gapValue2) > length or (gapValue1 + gapValue2) > width: # il rettangolo é troppo piccolo\n return [QgsPoint(firstCorner), pt2, QgsPoint(secondCorner), pt4, QgsPoint(firstCorner)]\n\n p1 = getPolarPointByPtAngle(firstCorner, angle, gapValue2)\n p2 = getPolarPointByPtAngle(pt2, angle + math.pi, gapValue1)\n angle = getAngleBy2Pts(pt2, secondCorner)\n p3 = getPolarPointByPtAngle(pt2, angle, gapValue2)\n p4 = getPolarPointByPtAngle(secondCorner, angle + math.pi, gapValue1)\n angle = getAngleBy2Pts(secondCorner, pt4)\n p5 = getPolarPointByPtAngle(secondCorner, angle, gapValue2)\n p6 = getPolarPointByPtAngle(pt4, angle+ math.pi, gapValue1)\n angle = getAngleBy2Pts(pt4, firstCorner)\n p7 = getPolarPointByPtAngle(pt4, angle, gapValue2)\n p8 = getPolarPointByPtAngle(firstCorner, angle + math.pi, gapValue1)\n return [p1, p2, p3, p4, p5, p6, p7, p8, p1]\n \n return []\n \n#===============================================================================\n# getRectByCornerAndDims\n#===============================================================================\ndef getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1 = None, gapValue2 = None, tolerance2ApproxCurve = None):\n \"\"\"\n ritorna una lista di punti che definisce il rettangolo costruito mediante \n uno spigolo , la lunghezza, la larghezza, la rotazione con punto base firstCorner e gapType \n 0 = gli spigoli del rettangolo hanno angoli retti\n 1 = raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n 2 = smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2 \n tolerance2ApproxCurve = errore minimo di tolleranza per rappresentare le curve\n \"\"\"\n pt2 = getPolarPointByPtAngle(firstCorner, rot, lengthDim)\n secondCorner = getPolarPointByPtAngle(pt2, rot + (math.pi / 2), widthDim)\n return getRectByCorners(firstCorner, secondCorner, rot, gapType, gapValue1, gapValue2)\n\n#===============================================================================\n# getRectByAreaAndLength\n#===============================================================================\ndef getRectByAreaAndLength(firstCorner, area, lengthDim, rot, gapType, \\\n gapValue1 = None, gapValue2 = None, tolerance2ApproxCurve = None):\n \"\"\"\n ritorna una lista di punti che definisce il rettangolo costruito mediante \n uno spigolo , l'area, la larghezza, la rotazione con punto base firstCorner e gapType \n 0 = gli spigoli del rettangolo hanno angoli retti\n 1 = raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n 2 = smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2 \n tolerance2ApproxCurve = errore minimo di tolleranza per rappresentare le curve\n \"\"\" \n if gapType == 0: # gli spigoli del rettangolo hanno angoli retti\n widthDim = area / lengthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n else:\n if gapType == 1: # raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n angleArea = ((2 * gapValue1) * (2 * gapValue1)) - (math.pi * gapValue1 * gapValue1)\n widthDim = (area + angleArea) / lengthDim\n if (gapValue1 * 2) > lengthDim or (gapValue1 * 2) > widthDim: # il rettangolo é troppo piccolo\n widthDim = area / lengthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n elif gapType == 2: # smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2\n angleArea = 2 * (gapValue1 * gapValue2)\n widthDim = (area + angleArea) / lengthDim\n if (gapValue1 + gapValue2) > lengthDim or (gapValue1 + gapValue2) > widthDim: # il rettangolo é troppo piccolo\n widthDim = area / lengthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n\n#===============================================================================\n# getRectByAreaAndWidth\n#===============================================================================\ndef getRectByAreaAndWidth(firstCorner, area, widthDim, rot, gapType, \\\n gapValue1 = None, gapValue2 = None, tolerance2ApproxCurve = None):\n \"\"\"\n ritorna una lista di punti che definisce il rettangolo costruito mediante \n uno spigolo , l'area, la larghezza, la rotazione con punto base firstCorner e gapType \n 0 = gli spigoli del rettangolo hanno angoli retti\n 1 = raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n 2 = smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2 \n tolerance2ApproxCurve = errore minimo di tolleranza per rappresentare le curve\n \"\"\" \n if gapType == 0: # gli spigoli del rettangolo hanno angoli retti\n lengthDim = area / widthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n else: \n if gapType == 1: # raccorda gli spigoli del rettangolo con un raggio di curvatura gapValue1\n angleArea = math.pi * gapValue1 * gapValue1\n lengthDim = (area + angleArea) / widthDim\n if (gapValue1 * 2) > lengthDim or (gapValue1 * 2) > widthDim: # il rettangolo é troppo piccolo\n lengthDim = area / widthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n elif gapType == 2: # smussa gli spigoli del rettangolo con 2 distanze di cimatura gapValue1, gapValue2\n angleArea = 2 * (gapValue1 * gapValue2)\n lengthDim = (area + angleArea) / widthDim\n if (gapValue1 + gapValue2) > lengthDim or (gapValue1 + gapValue2) > widthDim: # il rettangolo é troppo piccolo\n lengthDim = area / widthDim\n return getRectByCornerAndDims(firstCorner, lengthDim, widthDim, rot, gapType, \\\n gapValue1, gapValue2, tolerance2ApproxCurve)\n\n\n#===============================================================================\n# funzioni di creazione poligoni\n# getPolygonByNsidesCenterRadius\n#===============================================================================\ndef getPolygonByNsidesCenterRadius(sideNumber, centerPt, radius, Inscribed, ptStart = None):\n \"\"\"\n ritorna una lista di punti che definisce il poligono costruito mediante \n sideNumber = numero di lati \n centerPt = centro del poligono\n radius = raggio del cerchio\n Inscribed = se True significa poligono inscritto altrimento circoscritto\n ptStart = punto da cui partire\n \"\"\"\n result = [] \n angleIncrement = 2 * math.pi / sideNumber\n # poligono circoscritto\n if Inscribed == False:\n # calcolo il nuovo raggio \n myRadius = radius / math.cos(angleIncrement / 2)\n\n if ptStart is None:\n myPtStart = getPolarPointByPtAngle(centerPt, math.pi / 2 * 3 + (angleIncrement / 2), myRadius)\n angle = getAngleBy2Pts(centerPt, myPtStart)\n else:\n angle = getAngleBy2Pts(centerPt, ptStart) \n myPtStart = getPolarPointByPtAngle(centerPt, angle + (angleIncrement / 2), myRadius)\n angle = getAngleBy2Pts(centerPt, myPtStart) \n else: # poligono inscritto\n myRadius = radius\n \n if ptStart is None:\n myPtStart = getPolarPointByPtAngle(centerPt, math.pi / 2 * 3 + (angleIncrement / 2), myRadius)\n angle = getAngleBy2Pts(centerPt, myPtStart)\n else:\n myPtStart = ptStart\n angle = getAngleBy2Pts(centerPt, ptStart) \n \n result.append(myPtStart)\n for i in xrange(1, sideNumber, 1):\n angle = angle + angleIncrement\n result.append(getPolarPointByPtAngle(centerPt, angle, myRadius)) \n result.append(myPtStart)\n \n return result\n\n#===============================================================================\n# getPolygonByNsidesEdgePts\n#===============================================================================\ndef getPolygonByNsidesEdgePts(sideNumber, firstEdgePt, secondEdgePt):\n \"\"\"\n ritorna una lista di punti che definisce il poligono costruito mediante \n sideNumber = numero di lati \n firstEdgePt = primo punto di un lato\n secondEdgePt = secondo punto di un lato\n \"\"\"\n result = [] \n angleIncrement = 2 * math.pi / sideNumber\n angle = getAngleBy2Pts(firstEdgePt, secondEdgePt)\n sideLength = getDistance(firstEdgePt, secondEdgePt)\n \n result.append(firstEdgePt)\n result.append(secondEdgePt)\n lastPoint = secondEdgePt\n for i in xrange(1, sideNumber - 1, 1):\n angle = angle + angleIncrement\n lastPoint = getPolarPointByPtAngle(lastPoint, angle, sideLength)\n result.append(lastPoint) \n result.append(firstEdgePt)\n \n return result\n\n#===============================================================================\n# getPolygonByNsidesArea\n#===============================================================================\ndef getPolygonByNsidesArea(sideNumber, centerPt, area):\n \"\"\"\n ritorna una lista di punti che definisce il poligono costruito mediante \n sideNumber = numero di lati \n centerPt = centro del poligono\n area = area del poligono\n \"\"\"\n angle = 2 * math.pi / sideNumber\n triangleArea = area / sideNumber / 2\n # divido il poligono in sideNumber triangoli\n # ogni trinagolo viene diviso in 2 generando 2 trinagoli rettangoli in cui\n # \"(base * altezza) / 2 = Area\" che equivale a \"base = 2 * Area / altezza\"\n # \"tan(alfa) = base / altezza\" che equivale a \"tan(alfa) * altezza = base\n # per sostituzione si ha\n # \"tan(alfa) * altezza = 2 * Area / altezza\" quindi\n # \"altezza = sqrt(2 * Area / tan(alfa))\"\n h = math.sqrt(2 * triangleArea / math.tan(angle / 2))\n \n return getPolygonByNsidesCenterRadius(sideNumber, centerPt, h, False)\n\n\n#===============================================================================\n# getSubGeomAtVertex\n#===============================================================================\ndef getSubGeomAtVertex(geom, atVertex):\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n # la posizione é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])\n wkbType = geom.wkbType()\n \n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n if atVertex != 0:\n return None\n else:\n return QgsGeometry(geom), [0]\n\n if wkbType == QGis.WKBMultiPoint:\n pts = geom.asMultiPoint() # lista di punti\n if atVertex > len(pts) - 1:\n return None, None\n else:\n return QgsGeometry.fromPoint(pts[atVertex]), [atVertex]\n\n if wkbType == QGis.WKBLineString:\n pts = geom.asPolyline() # lista di punti\n if atVertex > len(pts) - 1:\n return None, None\n else:\n return QgsGeometry(geom), [0]\n \n if wkbType == QGis.WKBMultiLineString:\n # cerco in quale linea é il vertice <atVertex>\n i = 0\n iLine = 0\n lines = geom.asMultiPolyline() # lista di linee \n for line in lines:\n lineLen = len(line)\n if atVertex >= i and atVertex < i + lineLen:\n return QgsGeometry.fromPolyline(line), [iLine]\n i = lineLen \n iLine = iLine + 1\n return None, None\n \n if wkbType == QGis.WKBPolygon:\n i = 0\n iLine = 0\n lines = geom.asPolygon() # lista di linee \n for line in lines:\n lineLen = len(line)\n if atVertex >= i and atVertex < i + lineLen:\n return QgsGeometry.fromPolyline(line), [iLine]\n i = lineLen \n iLine = iLine + 1\n return None, None\n\n if wkbType == QGis.WKBMultiPolygon:\n i = 0\n iPolygon = 0\n polygons = geom.asMultiPolygon() # lista di poligoni\n for polygon in polygons:\n iLine = 0\n for line in lines:\n lineLen = len(line)\n if atVertex >= i and atVertex < i + lineLen:\n return QgsGeometry.fromPolyline(line), [iPolygon, iLine]\n i = lineLen \n iLine = iLine + 1\n iPolygon = iPolygon + 1\n \n return None\n\n\n#===============================================================================\n# setSubGeomAt\n#===============================================================================\ndef getSubGeomAt(geom, atSubGeom):\n # ritorna la sotto-geometria la cui posizione\n # é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])\n wkbType = geom.wkbType()\n \n ndx = 0\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D or wkbType == QGis.WKBLineString:\n if atSubGeom[0] == 0:\n return QgsGeometry(geom)\n \n if wkbType == QGis.WKBMultiPoint:\n nPoint = atSubGeom[0]\n return QgsGeometry(geom.vertexAt(nPoint))\n \n if wkbType == QGis.WKBMultiLineString:\n nLine = atSubGeom[0]\n lines = geom.asMultiPolyline() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n return QgsGeometry.fromPolyline(lines[nLine])\n \n if wkbType == QGis.WKBPolygon:\n nLine = atSubGeom[0]\n lines = geom.asPolygon() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n return QgsGeometry.fromPolyline(lines[nLine])\n\n if wkbType == QGis.WKBMultiPolygon:\n nPolygon = atSubGeom[0]\n nLine = atSubGeom[1]\n polygons = geom.asMultiPolygon() # lista di poligoni\n if nPolygon < len(polygons) and nPolygon >= -len(polygons):\n lines = polygons[nPolygon] \n if nLine < len(lines) and nLine >= -len(lines):\n return QgsGeometry.fromPolyline(lines[nLine])\n \n return None\n\n\n#===============================================================================\n# setSubGeom\n#===============================================================================\ndef setSubGeom(geom, SubGeom, atSubGeom):\n # restituisce una geometria con la sotto-geometria alla posizione <atSubGeom> \n # la posizione é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])\n wkbType = geom.wkbType()\n subWkbType = SubGeom.wkbType()\n \n ndx = 0\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D or wkbType == QGis.WKBLineString:\n if atSubGeom[0] == 0 and \\\n (subWkbType == QGis.WKBPoint or subWkbType == QGis.WKBPoint25D or subWkbType == QGis.WKBLineString):\n return QgsGeometry(SubGeom)\n \n if wkbType == QGis.WKBMultiPoint:\n nPoint = atSubGeom[0]\n if subWkbType == QGis.WKBPoint or subWkbType == QGis.WKBPoint25D:\n result = QgsGeometry(geom)\n pt = SubGeom.asPoint()\n if result.moveVertex(pt.x, pt.y(), nPoint) == True:\n return result\n \n if wkbType == QGis.WKBMultiLineString:\n if subWkbType == QGis.WKBLineString:\n nLine = atSubGeom[0]\n lines = geom.asMultiPolyline() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n lines.insert(nLine, SubGeom.asPolyline())\n return QgsGeometry.fromMultiPolyline(lines)\n \n if wkbType == QGis.WKBPolygon:\n if subWkbType == QGis.WKBLineString:\n nLine = atSubGeom[0]\n lines = geom.asPolygon() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n lines.insert(nLine, SubGeom.asPolyline())\n # per problemi di approssimazione con LL il primo punto e l'ultimo non sono uguali quindi lo forzo\n lines[0][-1].set(lines[0][0].x(), lines[0][0].y())\n return QgsGeometry.fromPolygon(lines)\n\n if wkbType == QGis.WKBMultiPolygon:\n if subWkbType == QGis.WKBLineString:\n nPolygon = atSubGeom[0]\n nLine = atSubGeom[1]\n polygons = geom.asMultiPolygon() # lista di poligoni\n if nPolygon < len(polygons) and nPolygon >= -len(polygons):\n lines = polygons[nPolygon] \n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n lines.insert(nLine, SubGeom.asPolyline())\n # per problemi di approssimazione con LL il primo punto e l'ultimo non sono uguali quindi lo forzo\n lines[0][-1].set(lines[0][0].x(), lines[0][0].y())\n return QgsGeometry.fromMultiPolygon(polygons)\n elif subWkbType == QGis.WKBPolygon:\n nPolygon = atSubGeom[0]\n polygons = geom.asMultiPolygon() # lista di poligoni\n if nPolygon < len(polygons) and nPolygon >= -len(polygons):\n del polygons[nPolygon]\n polygons.insert(nPolygon, SubGeom.asPolygon())\n return QgsGeometry.fromMultiPolygon(polygons)\n \n return None\n\n\n#===============================================================================\n# delSubGeom\n#===============================================================================\ndef delSubGeom(geom, atSubGeom):\n # restituisce una geometria con la sotto-geometria alla posizione <atSubGeom> cancellata\n # la posizione é espressa con una lista (<index ogg. princ> [<index ogg. sec.>])\n wkbType = geom.wkbType()\n \n ndx = 0\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D or wkbType == QGis.WKBLineString:\n return None\n \n if wkbType == QGis.WKBMultiPoint:\n nPoint = atSubGeom[0]\n result = QgsGeometry(geom)\n pt = SubGeom.asPoint()\n if result.deleteVertex(nPoint) == True:\n return result\n \n if wkbType == QGis.WKBMultiLineString:\n nLine = atSubGeom[0]\n lines = geom.asMultiPolyline() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n return QgsGeometry.fromMultiPolyline(lines)\n \n if wkbType == QGis.WKBPolygon:\n nLine = atSubGeom[0]\n lines = geom.asPolygon() # lista di linee\n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n return QgsGeometry.fromPolygon(lines)\n\n if wkbType == QGis.WKBMultiPolygon:\n nPolygon = atSubGeom[0]\n nLine = atSubGeom[1] if len(atSubGeom) > 1 else None\n polygons = geom.asMultiPolygon() # lista di poligoni\n if nPolygon < len(polygons) and nPolygon >= -len(polygons):\n if nLine is not None:\n lines = polygons[nPolygon] \n if nLine < len(lines) and nLine >= -len(lines):\n del lines[nLine]\n return QgsGeometry.fromMultiPolygon(polygons)\n else:\n del polygons[nPolygon]\n return QgsGeometry.fromMultiPolygon(polygons) \n \n return None\n\n\n#===============================================================================\n# getOffSetCircle\n#===============================================================================\ndef getOffSetCircle(circle, offSetDist, offSetSide):\n \"\"\"\n la funzione ritorna l'offset di un cerchio\n secondo una distanza e un lato di offset (\"internal\" o \"external\") \n \"\"\"\n if offSetSide == \"internal\":\n # offset verso l'interno del cerchio\n radius = circle.radius - offSetDist\n if radius <= 0:\n return None\n else:\n # offset verso l'esterno del cerchio\n radius = circle.radius + offSetDist\n\n result = QadCircle(circle)\n result.radius = radius\n \n return result\n\n\n#===============================================================================\n# getOffSetArc\n#===============================================================================\ndef getOffSetArc(arc, offSetDist, offSetSide):\n \"\"\"\n la funzione ritorna l'offset di un arco\n secondo una distanza e un lato di offset (\"internal\" o \"external\") \n \"\"\"\n if offSetSide == \"internal\":\n # offset verso l'interno del cerchio\n radius = arc.radius - offSetDist\n if radius <= 0:\n return None\n else:\n # offset verso l'esterno del cerchio\n radius = arc.radius + offSetDist\n\n result = QadArc(arc)\n result.radius = radius\n \n return result\n\n\n#===============================================================================\n# getOffSetLine\n#===============================================================================\ndef getOffSetLine(pt1, pt2, offSetDist, offSetSide):\n \"\"\"\n la funzione ritorna l'offset di una linea (lista di 2 punti)\n secondo una distanza e un lato di offset (\"right\" o \"left\") \n \"\"\"\n if offSetSide == \"right\":\n AngleProjected = getAngleBy2Pts(pt1, pt2) - (math.pi / 2)\n else:\n AngleProjected = getAngleBy2Pts(pt1, pt2) + (math.pi / 2)\n # calcolo il punto proiettato\n pt1Proj = getPolarPointByPtAngle(pt1, AngleProjected, offSetDist)\n pt2Proj = getPolarPointByPtAngle(pt2, AngleProjected, offSetDist)\n \n return [pt1Proj, pt2Proj]\n\n\n#===============================================================================\n# offsetBridgeTheGapBetweenLines\n#===============================================================================\ndef offsetBridgeTheGapBetweenLines(line1, line2, offset, gapType):\n \"\"\" \n la funzione colma il vuoto tra 2 segmenti retti (QadLinearObject) nel comando offset \n secondo una distanza <offset> (che corrisponde alla distanza di offset s \n chiamata da tale comando) ed un modo <gapType>:\n 0 = Estende i segmenti alle relative intersezioni proiettate\n 1 = Raccorda i segmenti attraverso un arco di raccordo di raggio <offset>\n 2 = Cima i segmenti di linea in corrispondenza delle intersezioni proiettate.\n La distanza perpendicolare da ciascuna cima al rispettivo vertice\n sull'oggetto originale é uguale alla distanza <offset>.\n \n Se \n Ritorna una lista di 3 elementi (None in caso di errore): \n una linea che sostituisce <line1>, se = None <line1> va rimossa\n un arco, se = None non c'é arco di raccordo tra le due linee\n una linea che sostituisce <line2>, se = None <line2> va rimossa\n \"\"\"\n # cerco il punto di intersezione tra le due linee\n ptInt = getIntersectionPointOn2InfinityLines(line1.getStartPt(), line1.getEndPt(), \\\n line2.getStartPt(), line2.getEndPt())\n if ptInt is None: # linee parallele\n return None\n distBetweenLine1Pt1AndPtInt = getDistance(line1.getStartPt(), ptInt)\n distBetweenLine1Pt2AndPtInt = getDistance(line1.getEndPt(), ptInt)\n distBetweenLine2Pt1AndPtInt = getDistance(line2.getStartPt(), ptInt)\n distBetweenLine2Pt2AndPtInt = getDistance(line2.getEndPt(), ptInt)\n \n if gapType == 0: # Estende i segmenti \n if distBetweenLine1Pt1AndPtInt > distBetweenLine1Pt2AndPtInt:\n # secondo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([line1.getStartPt(), ptInt])\n else:\n # primo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([ptInt, line1.getEndPt()])\n \n if distBetweenLine2Pt1AndPtInt > distBetweenLine2Pt2AndPtInt:\n # secondo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([line2.getStartPt(), ptInt])\n else:\n # primo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([ptInt, line2.getEndPt()])\n \n return [newLine1, None, newLine2]\n elif gapType == 1: # Raccorda i segmenti\n pt1Distant = line1.getStartPt() if distBetweenLine1Pt1AndPtInt > distBetweenLine1Pt2AndPtInt else line1.getEndPt()\n angleLine1 = getAngleBy2Pts(ptInt, pt1Distant)\n \n pt2Distant = line2.getStartPt() if distBetweenLine2Pt1AndPtInt > distBetweenLine2Pt2AndPtInt else line2.getEndPt()\n angleLine2 = getAngleBy2Pts(ptInt, pt2Distant)\n\n bisectorLine = getBisectorInfinityLine(pt1Distant, ptInt, pt2Distant, True)\n # cerco il punto di intersezione tra la bisettrice e \n # la retta che congiunge i punti più distanti delle due linee\n pt = getIntersectionPointOn2InfinityLines(bisectorLine[0], bisectorLine[1], \\\n pt1Distant, pt2Distant)\n angleBisectorLine = getAngleBy2Pts(ptInt, pt)\n #angleBisectorLine = getAngleBy2Pts(bisectorLine[0], bisectorLine[1])\n\n # calcolo l'angolo (valore assoluto) tra un lato e la bisettrice \n alfa = angleLine1 - angleBisectorLine\n if alfa < 0:\n alfa = angleBisectorLine - angleLine1 \n if alfa > math.pi:\n alfa = (2 * math.pi) - alfa \n\n # calcolo l'angolo del triangolo rettangolo sapendo che la somma degli angoli interni = 180\n # - alfa - 90 gradi (angolo retto)\n distFromPtInt = math.tan(math.pi - alfa - (math.pi / 2)) * offset\n pt1Proj = getPolarPointByPtAngle(ptInt, angleLine1, distFromPtInt)\n pt2Proj = getPolarPointByPtAngle(ptInt, angleLine2, distFromPtInt)\n # Pitagora\n distFromPtInt = math.sqrt((distFromPtInt * distFromPtInt) + (offset * offset)) \n secondPt = getPolarPointByPtAngle(ptInt, angleBisectorLine, distFromPtInt - offset)\n arc = QadArc()\n arc.fromStartSecondEndPts(pt1Proj, secondPt, pt2Proj)\n \n if distBetweenLine1Pt1AndPtInt > distBetweenLine1Pt2AndPtInt:\n # secondo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([pt1Distant, pt1Proj])\n else:\n # primo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([pt1Proj, pt1Distant]) \n\n if distBetweenLine2Pt1AndPtInt > distBetweenLine2Pt2AndPtInt:\n # secondo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([pt2Distant, pt2Proj])\n else:\n # primo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([pt2Proj, pt2Distant])\n \n # se i punti sono così vicini da essere considerati uguali \n inverse = False if ptNear(newLine1.getEndPt(), arc.getStartPt()) else True\n return [newLine1, QadLinearObject([arc, inverse]), newLine2] \n elif gapType == 2: # Cima i segmenti\n bisectorLine = getBisectorInfinityLine(line1.getEndPt(), ptInt, line2.getEndPt(), True)\n angleBisectorLine = getAngleBy2Pts(bisectorLine[0], bisectorLine[1])\n ptProj = getPolarPointByPtAngle(ptInt, angleBisectorLine, offset)\n\n pt1Proj = getPerpendicularPointOnInfinityLine(line1.getStartPt(), line1.getEndPt(), ptProj)\n if distBetweenLine1Pt1AndPtInt > distBetweenLine1Pt2AndPtInt:\n # secondo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([line1.getStartPt(), pt1Proj])\n else:\n # primo punto di line1 più vicino al punto di intersezione\n newLine1 = QadLinearObject([pt1Proj, line1.getEndPt()]) \n\n pt2Proj = getPerpendicularPointOnInfinityLine(line2.getStartPt(), line2.getEndPt(), ptProj)\n if distBetweenLine2Pt1AndPtInt > distBetweenLine2Pt2AndPtInt:\n # secondo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([line2.getStartPt(), pt2Proj])\n else:\n # primo punto di line2 più vicino al punto di intersezione\n newLine2 = QadLinearObject([pt2Proj, line2.getEndPt()])\n\n return [newLine1, QadLinearObject([pt1Proj, pt2Proj]), newLine2]\n\n return None\n\n\n#===============================================================================\n# bridgeTheGapBetweenLines\n#===============================================================================\ndef bridgeTheGapBetweenLines(line1, ptOnLine1, line2, ptOnLine2, radius, filletMode):\n \"\"\" \n la funzione raccorda 2 segmenti retti (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che più si avvicinza ai punti di selezione\n sul segmento 1 <ptOnLine1> e sul segmento 2 <ptOnLine2>.\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n una linea che sostituisce <line1>, se = None <line1> va rimossa\n un arco, se = None non c'é arco di raccordo tra le due linee\n una linea che sostituisce <line2>, se = None <line2> va rimossa\n \"\"\" \n if radius == 0: # Estende i segmenti \n # cerco il punto di intersezione tra le due linee\n ptInt = getIntersectionPointOn2InfinityLines(line1.getStartPt(), line1.getEndPt(), \\\n line2.getStartPt(), line2.getEndPt())\n if ptInt is None: # linee parallele\n return None\n \n distBetweenLine1Pt1AndPtInt = getDistance(line1.getStartPt(), ptInt)\n distBetweenLine1Pt2AndPtInt = getDistance(line1.getEndPt(), ptInt)\n distBetweenLine2Pt1AndPtInt = getDistance(line2.getStartPt(), ptInt)\n distBetweenLine2Pt2AndPtInt = getDistance(line2.getEndPt(), ptInt)\n \n if distBetweenLine1Pt1AndPtInt > distBetweenLine1Pt2AndPtInt:\n # secondo punto di line1 più vicino al punto di intersezione\n resLine1 = QadLinearObject([line1.getStartPt(), ptInt])\n else:\n # primo punto di line1 più vicino al punto di intersezione\n resLine1 = QadLinearObject([ptInt, line1.getEndPt()])\n \n if distBetweenLine2Pt1AndPtInt > distBetweenLine2Pt2AndPtInt:\n # secondo punto di line2 più vicino al punto di intersezione\n resLine2 = QadLinearObject([line2.getStartPt(), ptInt])\n else:\n # primo punto di line2 più vicino al punto di intersezione\n resLine2 = QadLinearObject([ptInt, line2.getEndPt()])\n \n return [resLine1, None, resLine2]\n else: # Raccorda i segmenti\n filletArcs = getFilletArcsBetweenLines(line1, line2, radius)\n\n # cerco l'arco valido più vicino a ptOnLine1 e ptOnLine2\n AvgList = []\n Avg = sys.float_info.max \n \n resLine1 = QadLinearObject()\n resFilletArc = QadLinearObject()\n resLine2 = QadLinearObject()\n for filletArc in filletArcs:\n # ricavo il nuovo segmento in modo che sia tangente con l'arco di raccordo \n newLine1, distFromPtOnLine1 = getNewLineAccordingFilletArc(line1, filletArc, ptOnLine1)\n if newLine1 is None:\n continue \n # ricavo il nuovo segmento in modo che sia tangente con l'arco di raccordo \n newLine2, distFromPtOnLine2 = getNewLineAccordingFilletArc(line2, filletArc, ptOnLine2)\n if newLine2 is None:\n continue \n \n del AvgList[:] \n AvgList.append(distFromPtOnLine1)\n AvgList.append(distFromPtOnLine2)\n \n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n resLine1.set(newLine1)\n resFilletArc.setArc(filletArc, False)\n resLine2.set(newLine2)\n \n if Avg == sys.float_info.max:\n return None \n \n if filletMode == 1: # 1=Taglia-estendi\n return [resLine1, resFilletArc, resLine2]\n else:\n return [None, resFilletArc, None]\n\n\n#===============================================================================\n# getNewLineAccordingFilletArc\n#===============================================================================\ndef getNewLineAccordingFilletArc(line, filletArc, ptOnLine):\n \"\"\"\n dato un segmento retto (line di tipo <QadLinearObject>) e un arco che si \n raccorda ad esso (<filleArc>), la funzione restituisce un nuovo segmento retto\n modificando <line> in modo che sia tangente all'arco di raccordo. \n Inoltre, usando un punto indicato sul segmento <ptOnLine> restituisce \n la distanza di quel punto dal punto di tangenza con l'arco di raccordo.\n \"\"\"\n newLine = QadLinearObject()\n\n # determino quale punto (iniziale o finale) dell'arco di raccordo \n # si interseca sul prolugamento del segmento retto\n if isPtOnInfinityLine(line.getStartPt(), line.getEndPt(), filletArc.getStartPt()):\n filletPtOnLine = filletArc.getStartPt()\n isStartFilletPtOnLine = True\n else:\n filletPtOnLine = filletArc.getEndPt()\n isStartFilletPtOnLine = False\n\n if line.containsPt(filletPtOnLine) == True: # se il punto é all'interno del segmento \n newLine.set([filletPtOnLine, line.getEndPt()])\n \n if isStartFilletPtOnLine: # se il punto iniziale dell'arco di raccordo é sulla linea\n # se il nuovo segmento non é un segmento valido\n if ptNear(newLine.getStartPt(), newLine.getEndPt()): \n # se l'arco di raccordo é tangente sul punto finale del nuovo segmento\n if TanDirectionNear(line.getTanDirectionOnEndPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnStartPt())) == True:\n newLine.set(line) # ripristino il segmento originale\n else:\n # se l'arco di raccordo non é tangente sul punto iniziale del nuovo segmento \n if TanDirectionNear(newLine.getTanDirectionOnStartPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnStartPt() + math.pi)) == False:\n newLine.set([line.getStartPt(), filletPtOnLine])\n \n # se il nuovo segmento non é un segmento valido\n if ptNear(newLine.getStartPt(), newLine.getEndPt()) or \\\n newLine.containsPt(ptOnLine) == False:\n return None, None \n \n # calcolo la distanza dal punto ptOnLine\n distFromPtOnLine = getDistance(ptOnLine, filletPtOnLine)\n else: # se il punto finale dell'arco di raccordo é sulla linea\n # se il nuovo segmento non é un segmento valido\n if ptNear(newLine.getStartPt(), newLine.getEndPt()): \n # se l'arco di raccordo é tangente sul punto finale del nuovo segmento\n if TanDirectionNear(line.getTanDirectionOnEndPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnEndPt() + math.pi)) == True:\n newLine.set(line) # ripristino il segmento originale\n else:\n # se l'arco di raccordo non é tangente sul punto iniziale del nuovo segmento \n if TanDirectionNear(newLine.getTanDirectionOnStartPt(), \\\n filletArc.getTanDirectionOnEndPt()) == False:\n newLine.set([line.getStartPt(), filletPtOnLine])\n \n # se il nuovo segmento non é un segmento valido\n if ptNear(newLine.getStartPt(), newLine.getEndPt()) or \\\n newLine.containsPt(ptOnLine) == False:\n return None, None \n \n # calcolo la distanza dal punto ptOnLine\n distFromPtOnLine = getDistance(ptOnLine, filletPtOnLine)\n \n return newLine, distFromPtOnLine\n else: # se il punto é all'esterno del segmento \n if getDistance(line.getStartPt(), filletPtOnLine) < getDistance(line.getEndPt(), filletPtOnLine):\n newLine.set([filletPtOnLine, line.getEndPt()])\n else:\n newLine.set([line.getStartPt(), filletPtOnLine])\n\n return getNewLineAccordingFilletArc(newLine, filletArc, ptOnLine)\n \n\n#===============================================================================\n# auxFilletArcsBetweenLines\n#===============================================================================\ndef auxFilletArcsBetweenLines(ptLine1, ptLine2, intPt, radius, both = True):\n \"\"\"\n la funzione di ausilio a getFilletArcsBetweenLines\n Ritorna una lista dei possibili archi di raccordo tra la \n linea 1 che va da <ptLine1> fino al punto di intersezione con la linea 2 <intPt>\n e \n linea2 che va da <ptLine2> fino al punto di intersezione con la linea 1 <intPt>\n \"\"\"\n res = []\n\n angleLine1 = getAngleBy2Pts(intPt, ptLine1)\n angleLine2 = getAngleBy2Pts(intPt, ptLine2)\n\n bisectorLine = getBisectorInfinityLine(ptLine1, intPt, ptLine2, True)\n # cerco il punto di intersezione tra la bisettrice e \n # la retta che congiunge i punti più distanti delle due linee\n pt = getIntersectionPointOn2InfinityLines(bisectorLine[0], bisectorLine[1], \\\n ptLine1, ptLine2)\n angleBisectorLine = getAngleBy2Pts(intPt, pt)\n\n # calcolo l'angolo (valore assoluto) tra un lato e la bisettrice \n alfa = angleLine1 - angleBisectorLine\n if alfa < 0:\n alfa = angleBisectorLine - angleLine1 \n if alfa > math.pi:\n alfa = (2 * math.pi) - alfa \n\n # calcolo l'angolo del triangolo rettangolo sapendo che la somma degli angoli interni = 180\n # - alfa - 90 gradi (angolo retto)\n distFromIntPt = math.tan(math.pi - alfa - (math.pi / 2)) * radius\n pt1Proj = getPolarPointByPtAngle(intPt, angleLine1, distFromIntPt)\n pt2Proj = getPolarPointByPtAngle(intPt, angleLine2, distFromIntPt)\n # Pitagora\n distFromIntPt = math.sqrt((distFromIntPt * distFromIntPt) + (radius * radius)) \n secondPt = getPolarPointByPtAngle(intPt, angleBisectorLine, distFromIntPt - radius)\n filletArc = QadArc()\n if filletArc.fromStartSecondEndPts(pt1Proj, secondPt, pt2Proj) == True:\n res.append(filletArc)\n if both:\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc(filletArc)\n filletArc.inverse()\n res.append(filletArc)\n\n return res\n\n#===============================================================================\n# getFilletArcsBetweenCircleLine\n#===============================================================================\ndef getFilletArcsBetweenLines(line1, line2, radius):\n \"\"\"\n la funzione raccorda due linee rette (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\"\n res = []\n \n # cerco il punto di intersezione tra le due linee\n intPt = getIntersectionPointOn2InfinityLines(line1.getStartPt(), line1.getEndPt(), \\\n line2.getStartPt(), line2.getEndPt())\n if intPt is None: # linee parallele\n # calcolo la proiezione perpendicolare del punto iniziale di <line1> su <line2> \n ptPerp = getPerpendicularPointOnInfinityLine(line2.getStartPt(), line2.getEndPt(), line1.getStartPt())\n d = getDistance(line1.getStartPt(), ptPerp)\n # d deve essere 2 volte <radius>\n if doubleNear(radius * 2, d):\n angle = getAngleBy2Pts(line1.getStartPt(), ptPerp)\n ptCenter = getPolarPointByPtAngle(line1.getStartPt(), angle, radius)\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(line1.getStartPt(), ptCenter, ptPerp) == True:\n res.append(filletArc)\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(ptPerp, ptCenter, line1.getStartPt()) == True:\n res.append(filletArc)\n \n ptPerp = getPolarPointByPtAngle(line1.getEndPt(), angle, d)\n ptCenter = getPolarPointByPtAngle(line1.getEndPt(), angle, radius)\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(line1.getEndPt(), ptCenter, ptPerp) == True:\n res.append(filletArc)\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(ptPerp, ptCenter, line1.getEndPt()) == True:\n res.append(filletArc) \n else: # linee non parallele\n angleLine1 = getAngleBy2Pts(line1.getStartPt(), line1.getEndPt())\n angleLine2 = getAngleBy2Pts(line2.getStartPt(), line2.getEndPt())\n\n ptLine1 = getPolarPointByPtAngle(intPt, angleLine1, 1)\n ptLine2 = getPolarPointByPtAngle(intPt, angleLine2, 1)\n res.extend(auxFilletArcsBetweenLines(ptLine1, ptLine2, intPt, radius))\n\n ptLine2 = getPolarPointByPtAngle(intPt, angleLine2, -1)\n res.extend(auxFilletArcsBetweenLines(ptLine1, ptLine2, intPt, radius))\n \n ptLine1 = getPolarPointByPtAngle(intPt, angleLine1, -1)\n res.extend(auxFilletArcsBetweenLines(ptLine1, ptLine2, intPt, radius))\n\n ptLine2 = getPolarPointByPtAngle(intPt, angleLine2, 1)\n res.extend(auxFilletArcsBetweenLines(ptLine1, ptLine2, intPt, radius))\n\n return res\n\n\n#===============================================================================\n# bridgeTheGapBetweenCircleLine\n#===============================================================================\ndef bridgeTheGapBetweenCircleLine(circle, ptOnCircle, line, ptOnLine, radius, filletMode):\n \"\"\"\n la funzione raccorda un cerchio e un segmento retto (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che più si avvicinza ai punti di selezione\n sul cerchio <ptOnCircle> e sul segmento retto <ptOnLine>.\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n None\n un arco, se = None non c'é arco di raccordo tra le due linee\n una linea che sostituisce <line>\n \"\"\"\n # ricavo i possibili archi di raccordo\n _circle = circle.getCircle() \n filletArcs = getFilletArcsBetweenCircleLine(_circle, line, radius)\n \n # cerco l'arco valido più vicino a ptOnArc e ptOnLine\n AvgList = []\n Avg = sys.float_info.max \n\n resFilletArc = QadLinearObject()\n resLine = QadLinearObject()\n for filletArc in filletArcs:\n # ricavo il nuovo segmento in modo che sia tangente con l'arco di raccordo \n newLine, distFromPtOnLine = getNewLineAccordingFilletArc(line, filletArc, ptOnLine)\n if newLine is None:\n continue \n\n if _circle.isPtOnCircle(filletArc.getStartPt()):\n distFromPtOnCircle = _circle.lengthBetween2Points(filletArc.getStartPt(), \\\n ptOnCircle, \\\n filletArc.getTanDirectionOnStartPt() + math.pi)\n else:\n distFromPtOnCircle = _circle.lengthBetween2Points(filletArc.getEndPt(), \\\n ptOnCircle, \\\n filletArc.getTanDirectionOnEndPt())\n\n del AvgList[:] \n AvgList.append(distFromPtOnLine)\n AvgList.append(distFromPtOnCircle)\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente piùvicino\n Avg = currAvg\n resLine.set(newLine)\n resFilletArc.setArc(filletArc, False)\n \n if Avg == sys.float_info.max:\n return None \n\n if filletMode == 1: # 1=Taglia-estendi\n return [None, resFilletArc, resLine]\n else:\n return [None, resFilletArc, None]\n\n\n#===============================================================================\n# auxFilletArcsBetweenCircleLine\n#===============================================================================\ndef auxFilletArcsBetweenCircleLine(circle, line, origCircle, origLine, both = True):\n \"\"\"\n la funzione di ausilio a getFilletArcsBetweenArcLine\n Ritorna una lista dei possibili archi di raccordo tra <circle> e <line>\n \"\"\"\n res = []\n # calcolo le intersezioni tra la circonferenza del cerchio e la retta parallela a <line> \n # che daranno origine ai centri degli archi di raccordo\n intPts = circle.getIntersectionPointsWithInfinityLine(line[0], line[1])\n if len(intPts) > 0:\n # un punto di tangenza é dato dal punto a distanza radius dal centro di <origCircle> \n # in direzione centro dell'arco di raccordo\n angle = getAngleBy2Pts(origCircle.center, intPts[0])\n tanCirclePt = getPolarPointByPtAngle(origCircle.center, angle, origCircle.radius) \n # un punto di tangenza é la proiezione perpendicolare del centro dell'arco di raccordo\n # con <origLine> \n ptPerp = getPerpendicularPointOnInfinityLine(origLine.getStartPt(), origLine.getEndPt(), intPts[0])\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(tanCirclePt, \\\n intPts[0], \\\n ptPerp) == True:\n res.append(filletArc)\n if both:\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc(filletArc)\n filletArc.inverse()\n res.append(filletArc)\n\n if len(intPts) > 1: # # due centri per i due archi di raccordo\n # un punto di tangenza é dato dal punto a distanza arc.radius dal centro di <arc> \n # in direzione centro dell'arco di raccordo\n angle = getAngleBy2Pts(origCircle.center, intPts[1])\n tanCirclePt = getPolarPointByPtAngle(origCircle.center, angle, origCircle.radius) \n # un punto di tangenza é la proiezione perpendicolare del centro dell'arco di raccordo\n # con <line> \n ptPerp = getPerpendicularPointOnInfinityLine(origLine.getStartPt(), origLine.getEndPt(), intPts[1])\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(tanCirclePt, \\\n intPts[1], \\\n ptPerp) == True:\n res.append(filletArc)\n if both:\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc(filletArc)\n filletArc.inverse()\n res.append(filletArc)\n \n return res\n\n#===============================================================================\n# getFilletArcsBetweenCircleLine\n#===============================================================================\ndef getFilletArcsBetweenCircleLine(circle, line, radius):\n \"\"\"\n la funzione raccorda un arco e una linea retta (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\"\n res = []\n \n offsetCircle = QadCircle(circle)\n\n intPts = circle.getIntersectionPointsWithInfinityLine(line.getStartPt(), line.getEndPt())\n if len(intPts) == 0:\n # se il cerchio e la retta generata dall'estensione di line\n # non hanno punti in comune\n leftOfLine = line.leftOf(circle.center)\n # creo una retta parallela a <line> ad una distanza <radius> verso il centro di <circle> \n linePar = []\n angle = line.getTanDirectionOnStartPt()\n if leftOfLine < 0: # a sinistra\n linePar.append(getPolarPointByPtAngle(line.getStartPt(), angle + math.pi / 2, radius))\n linePar.append(getPolarPointByPtAngle(line.getEndPt(), angle + math.pi / 2, radius))\n else :# a destra\n linePar.append(getPolarPointByPtAngle(line.getStartPt(), angle - math.pi / 2, radius))\n linePar.append(getPolarPointByPtAngle(line.getEndPt(), angle - math.pi / 2, radius))\n \n # Calcolo la distanza dal centro di <circle> a <line>\n ptPerp = getPerpendicularPointOnInfinityLine(line.getStartPt(), line.getEndPt(), circle.center)\n d = getDistance(circle.center, ptPerp)\n # <radius> deve essere >= (d - raggio cerchio) / 2\n if radius >= (d - circle.radius) / 2:\n \n # caso 1: raccordo tra <circle> e <line> formando un flesso con <circle>\n \n # creo un cerchio con raggio aumentato di <radius> \n offsetCircle.radius = circle.radius + radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n \n # caso 2: raccordo tra <circle> e <line> senza formare un flesso con <circle>\n \n # <radius> deve essere > raggio cerchio\n if radius > circle.radius: \n # creo un cerchio con raggio = <radius> - circle.radius\n offsetCircle.radius = radius - circle.radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n else:\n # se il cerchio e la retta generata dall'estensione di line\n # hanno punti in comune\n # creo una retta parallela a <line> ad una distanza <radius> verso sinistra \n linePar = []\n angle = line.getTanDirectionOnStartPt()\n linePar.append(getPolarPointByPtAngle(line.getStartPt(), angle + math.pi / 2, radius))\n linePar.append(getPolarPointByPtAngle(line.getEndPt(), angle + math.pi / 2, radius))\n\n # creo un cerchio con raggio aumentato di <radius> \n offsetCircle.radius = circle.radius + radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n \n if circle.radius > radius: \n # creo un cerchio con raggio diminuito di <radius>\n offsetCircle.radius = circle.radius - radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n\n # creo una retta parallela a <line> ad una distanza <radius> verso destra\n del linePar[:] # svuoto la lista\n linePar.append(getPolarPointByPtAngle(line.getStartPt(), angle - math.pi / 2, radius))\n linePar.append(getPolarPointByPtAngle(line.getEndPt(), angle - math.pi / 2, radius))\n\n # creo un cerchio con raggio aumentato di <radius> \n offsetCircle.radius = circle.radius + radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n # calcolo le intersezioni tra la circonferenza del cerchio e la retta parallela a <line> \n\n if circle.radius > radius: \n # creo un cerchio con raggio diminuito di <radius>\n offsetCircle.radius = circle.radius - radius\n res.extend(auxFilletArcsBetweenCircleLine(offsetCircle, linePar, circle, line))\n\n return res\n\n\n#===============================================================================\n# getNewArcAccordingFilletArc\n#===============================================================================\ndef getNewArcAccordingFilletArc(arc, filletArc, ptOnArc):\n \"\"\"\n dato un arco (<arc>) e un altro arco che si raccorda ad esso (<filleArc>),\n la funzione restituisce un nuovo arco modificando <arc> in modo che sia \n tangente all'arco di raccordo. Inoltre, usando un punto indicato sull'arco\n <ptOnArc> restituisce la distanza di quel punto dal punto di tangenza con l'arco\n di raccordo usando la direzione della tangente dell'arco di raccordo.\n \"\"\"\n circle = QadCircle() \n circle.set(arc.center, arc.radius) \n\n newArc = QadArc(arc)\n\n # determino quale punto (iniziale o finale) dell'arco di raccordo \n # si interseca sul prolugamento dell'arco \n if circle.isPtOnCircle(filletArc.getStartPt()):\n filletPtOnArc = filletArc.getStartPt()\n isStartFilletPtOnArc = True\n else:\n filletPtOnArc = filletArc.getEndPt()\n isStartFilletPtOnArc = False\n\n # verifico che l'arco di raccordo sia tangente con l'arco\n newArc.setStartAngleByPt(filletPtOnArc)\n \n if isStartFilletPtOnArc: # se il punto iniziale dell'arco di raccordo é sull'arco\n # se il nuovo arco non é un arco valido\n if doubleNear(newArc.startAngle, newArc.endAngle):\n # se l'arco di raccordo é tangente sul punto finale dell'arco\n if TanDirectionNear(arc.getTanDirectionOnEndPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnStartPt())) == True:\n newArc.startAngle = arc.startAngle # ripristino l'arco originale\n else:\n # se l'arco di raccordo non é tangente sul punto iniziale del nuovo arco \n if TanDirectionNear(newArc.getTanDirectionOnStartPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnStartPt() + math.pi)) == False:\n newArc.startAngle = arc.startAngle # ripristino l'arco originale\n newArc.setEndAngleByPt(filletPtOnArc)\n \n # se il nuovo arco non é un arco valido\n if doubleNear(newArc.startAngle, newArc.endAngle):\n return None, None\n \n # calcolo la distanza dal punto ptOnArc\n distFromPtOnArc = circle.lengthBetween2Points(filletArc.getStartPt(), \\\n ptOnArc, \\\n filletArc.getTanDirectionOnStartPt() + math.pi)\n else: # se il punto finale dell'arco di raccordo é sull'arco\n # se il nuovo arco non é un arco valido\n if doubleNear(newArc.startAngle, newArc.endAngle):\n # se l'arco di raccordo é tangente sul punto finale dell'arco\n if TanDirectionNear(arc.getTanDirectionOnEndPt(), \\\n normalizeAngle(filletArc.getTanDirectionOnEndPt() + math.pi)) == True:\n newArc.startAngle = arc.startAngle # ripristino l'arco originale\n else:\n # se l'arco di raccordo non é tangente sul punto iniziale del nuovo arco \n if TanDirectionNear(newArc.getTanDirectionOnStartPt(), \\\n filletArc.getTanDirectionOnEndPt()) == False:\n newArc.startAngle = arc.startAngle # ripristino l'arco originale\n newArc.setEndAngleByPt(filletPtOnArc)\n\n # se il nuovo arco non é un arco valido\n if doubleNear(newArc.startAngle, newArc.endAngle):\n return None, None\n\n # calcolo la distanza dal punto ptOnArc\n distFromPtOnArc = circle.lengthBetween2Points(filletArc.getEndPt(), \\\n ptOnArc, \\\n filletArc.getTanDirectionOnEndPt())\n\n return newArc, distFromPtOnArc\n\n\n#===============================================================================\n# bridgeTheGapBetweenArcLine\n#===============================================================================\ndef bridgeTheGapBetweenArcLine(arc, ptOnArc, line, ptOnLine, radius, filletMode):\n \"\"\"\n la funzione raccorda un arco e un segmento retto (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che piùsi avvicinza ai punti di selezione\n sull'arco <ptOnArc> e sul segmento retto <ptOnLine>.\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n una arco che sostituisce <arc>\n un arco, se = None non c'é arco di raccordo tra le due linee\n una linea che sostituisce <line>\n \"\"\"\n # ricavo i possibili archi di raccordo\n filletArcs = getFilletArcsBetweenArcLine(arc, line, radius)\n \n # cerco l'arco valido più vicino a ptOnArc e ptOnLine\n AvgList = []\n Avg = sys.float_info.max \n\n resArc = QadLinearObject()\n resFilletArc = QadLinearObject()\n resLine = QadLinearObject()\n for filletArc in filletArcs:\n # ricavo il nuovo segmento in modo che sia tangente con l'arco di raccordo \n newLine, distFromPtOnLine = getNewLineAccordingFilletArc(line, filletArc, ptOnLine)\n if newLine is None:\n continue \n \n # ricavo il nuovo arco in modo che sia tangente con l'arco di raccordo \n newArc, distFromPtOnArc = getNewArcAccordingFilletArc(arc.getArc(), filletArc, ptOnArc)\n if newArc is None:\n continue \n\n del AvgList[:] \n AvgList.append(distFromPtOnLine)\n AvgList.append(distFromPtOnArc)\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n resLine.set(newLine)\n resFilletArc.setArc(filletArc, False)\n resArc.setArc(newArc, False) \n \n if Avg == sys.float_info.max:\n return None \n\n if filletMode == 1: # 1=Taglia-estendi\n return [resLine, resFilletArc, resArc]\n else:\n return [None, resFilletArc, None]\n\n#===============================================================================\n# getFilletArcsBetweenArcLine\n#===============================================================================\ndef getFilletArcsBetweenArcLine(arc, line, radius):\n \"\"\"\n la funzione raccorda un arco e una linea retta (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\"\n circle = QadCircle()\n circle.set(arc.getArc().center, arc.getArc().radius)\n \n return getFilletArcsBetweenCircleLine(circle, line, radius)\n\n\n#===============================================================================\n# bridgeTheGapBetweenCircles\n#===============================================================================\ndef bridgeTheGapBetweenCircles(circle1, ptOnCircle1, circle2, ptOnCircle2, radius):\n \"\"\"\n la funzione raccorda due cerchi (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che più si avvicinza ai punti di selezione\n sui cerchi.\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n None\n un arco, se = None non c'é arco di raccordo tra le due linee\n None\n \"\"\"\n # ricavo i possibili archi di raccordo\n _circle1 = circle1.getCircle()\n _circle2 = circle2.getCircle()\n filletArcs = getFilletArcsBetweenCircles(_circle1, _circle2, radius)\n \n # cerco l'arco valido più vicino a ptOnCircle1 e ptOnCircle2\n AvgList = []\n Avg = sys.float_info.max \n\n resFilletArc = QadLinearObject()\n for filletArc in filletArcs:\n if _circle1.isPtOnCircle(filletArc.getStartPt()):\n distFromPtOnCircle1 = _circle1.lengthBetween2Points(filletArc.getStartPt(), \\\n ptOnCircle1, \\\n filletArc.getTanDirectionOnStartPt() + math.pi)\n distFromPtOnCircle2 = _circle2.lengthBetween2Points(filletArc.getEndPt(), \\\n ptOnCircle2, \\\n filletArc.getTanDirectionOnEndPt())\n else:\n distFromPtOnCircle1 = _circle1.lengthBetween2Points(filletArc.getEndPt(), \\\n ptOnCircle1, \\\n filletArc.getTanDirectionOnEndPt())\n distFromPtOnCircle2 = _circle2.lengthBetween2Points(filletArc.getStartPt(), \\\n ptOnCircle2, \\\n filletArc.getTanDirectionOnStartPt()+ math.pi)\n\n del AvgList[:] \n AvgList.append(distFromPtOnCircle1)\n AvgList.append(distFromPtOnCircle2)\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n resFilletArc.setArc(filletArc, False)\n \n if Avg == sys.float_info.max:\n return None \n\n return [None, resFilletArc, None]\n\n\n#===============================================================================\n# auxFilletArcsBetweenCircles\n#===============================================================================\ndef auxFilletArcsBetweenCircles(circle1, circle2, radius, both = True):\n \"\"\"\n la funzione di ausilio a getFilletArcsBetweenCircles \n Ritorna una lista dei possibili archi di raccordo tra i cerchi <circle1> e <circle2>\n \"\"\"\n res = []\n # calcolo le intersezioni tra le due circonferenze \n # che daranno origine ai centri degli archi di raccordo\n intPts = circle1.getIntersectionPointsWithCircle(circle2)\n\n if len(intPts) > 0:\n # un punto di tangenza é dato dal punto a distanza radius dal centro dell'arco di raccordo\n # in direzione centro dell'arco <circle1>\n angle = getAngleBy2Pts(intPts[0], circle1.center)\n tanC1Pt = getPolarPointByPtAngle(intPts[0], angle, radius)\n # un punto di tangenza é dato dal punto a distanza radius dal centro dell'arco di raccordo\n # in direzione centro dell'arco <circle2>\n angle = getAngleBy2Pts(intPts[0], circle2.center)\n tanC2Pt = getPolarPointByPtAngle(intPts[0], angle, radius)\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(tanC1Pt, intPts[0], tanC2Pt) == True:\n res.append(filletArc)\n if both:\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc(filletArc)\n filletArc.inverse()\n res.append(filletArc)\n\n if len(intPts) > 1:\n # un punto di tangenza é dato dal punto a distanza radius dal centro dell'arco di raccordo\n # in direzione centro dell'arco <circle1>\n angle = getAngleBy2Pts(intPts[1], circle1.center)\n tanC1Pt = getPolarPointByPtAngle(intPts[1], angle, radius)\n # un punto di tangenza é dato dal punto a distanza radius dal centro dell'arco di raccordo\n # in direzione centro dell'arco <circle2>\n angle = getAngleBy2Pts(intPts[1], circle2.center)\n tanC2Pt = getPolarPointByPtAngle(intPts[1], angle, radius)\n filletArc = QadArc()\n if filletArc.fromStartCenterEndPts(tanC1Pt, intPts[1], tanC2Pt) == True:\n res.append(filletArc)\n if both:\n # stesso arco con il punto iniziale e finale invertiti\n filletArc = QadArc(filletArc)\n filletArc.inverse()\n res.append(filletArc)\n \n return res\n \n#===============================================================================\n# getFilletArcsBetweenCircles\n#===============================================================================\ndef getFilletArcsBetweenCircles(circle1, circle2, radius):\n \"\"\"\n la funzione raccorda due cerchi attraverso un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\"\n res = []\n \n # caso 1: raccordo tra <circle1> e <circle2> formando un flesso con ciascuno dei cerchi\n # creo un nuovo cerchio concentrico a circle1 con raggio aumentato di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = newCircle1.radius + radius\n # creo un nuovo cerchio concentrico a circle2 con raggio aumentato di <radius>\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = newCircle2.radius + radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n \n # caso 2: raccordo tra <circle1> e <circle2> senza formare un flesso con ciascuno dei cerchi \n if radius - circle1.radius > 0 and radius - circle2.radius > 0: \n # creo un nuovo cerchio concentrico a circle1 con raggio = <radius> - raggio di circle1\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = radius - newCircle1.radius\n # creo un nuovo cerchio concentrico a circle2 con raggio = <radius> - raggio di circle2\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = radius - newCircle2.radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n\n # caso 3: raccordo tra <circle1> e <circle2> formando un flesso solo con circle1\n if radius - circle2.radius > 0: \n # creo un nuovo cerchio concentrico a circle1 con raggio aumentato di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = newCircle1.radius + radius\n # creo un nuovo cerchio concentrico a circle2 con raggio = <radius> - raggio di circle2\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = radius - newCircle2.radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n \n # caso 4: raccordo tra <circle1> e <circle2> formando un flesso solo con circle2\n if radius - circle1.radius > 0: \n # creo un nuovo cerchio concentrico a circle1 con raggio aumentato di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = radius - newCircle1.radius\n # creo un nuovo cerchio concentrico a circle2 con raggio = <radius> - raggio di circle2\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = newCircle2.radius + radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n \n # caso 5: raccordo tra <circle1> e <circle2> interno a <circle1> formando un flesso solo con circle2\n if getDistance(circle1.center, circle2.center) + circle2.radius <= circle1.radius and \\\n circle1.radius - radius > 0: \n # creo un nuovo cerchio concentrico a circle1 con raggio diminuito di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = newCircle1.radius - radius\n # creo un nuovo cerchio concentrico a circle2 con raggio aumentato di <radius>\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = newCircle2.radius + radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n \n # caso 6: raccordo tra <circle1> interno a <circle2> e <circle2> formando un flesso solo con circle1\n if getDistance(circle1.center, circle2.center) + circle1.radius <= circle2.radius and \\\n circle2.radius - radius > 0: \n # creo un nuovo cerchio concentrico a circle1 con raggio aumentato di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = newCircle1.radius + radius\n # creo un nuovo cerchio concentrico a circle2 con raggio diminuito di <radius>\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = newCircle2.radius - radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n\n # caso 7: raccordo tra <circle1> e <circle2> interno a <circle1> senza formare alcun flesso\n if getDistance(circle1.center, circle2.center) + circle2.radius <= circle1.radius and \\\n circle1.radius - radius > 0 and radius - circle2.radius: \n # creo un nuovo cerchio concentrico a circle1 con raggio diminuito di <radius>\n newCircle1 = QadCircle(circle1)\n newCircle1.radius = newCircle1.radius - radius\n # creo un nuovo cerchio concentrico a circle2 con raggio = <radius> - raggio di circle2\n newCircle2 = QadCircle(circle2)\n newCircle2.radius = radius - newCircle2.radius\n \n res.extend(auxFilletArcsBetweenCircles(newCircle1, newCircle2, radius))\n\n return res\n\n\n#===============================================================================\n# bridgeTheGapBetweenArcs\n#===============================================================================\ndef bridgeTheGapBetweenArcs(arc1, ptOnArc1, arc2, ptOnArc2, radius, filletMode):\n \"\"\"\n la funzione raccorda due archi (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che più si avvicinza ai punti di selezione\n sull'arco1 <ptOnArc1> e sull'arco2 <ptOnArc2>.\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n una arco che sostituisce <arc1>\n un arco, se = None non c'é arco di raccordo tra le due linee\n una arco che sostituisce <arc2>\n \"\"\"\n # ricavo i possibili archi di raccordo\n filletArcs = getFilletArcsBetweenArcs(arc1, arc2, radius)\n \n # cerco l'arco valido più vicino a ptOnArc1 e ptOnArc2\n AvgList = []\n Avg = sys.float_info.max \n\n resFilletArc = QadLinearObject()\n resArc1 = QadLinearObject()\n resArc2 = QadLinearObject()\n for filletArc in filletArcs:\n # ricavo il nuovo arco1 in modo che sia tangente con l'arco di raccordo \n newArc1, distFromPtOnArc1 = getNewArcAccordingFilletArc(arc1.getArc(), filletArc, ptOnArc1)\n if newArc1 is None:\n continue\n # ricavo il nuovo arco in modo che sia tangente con l'arco di raccordo \n newArc2, distFromPtOnArc2 = getNewArcAccordingFilletArc(arc2.getArc(), filletArc, ptOnArc2)\n if newArc2 is None:\n continue\n\n del AvgList[:] \n AvgList.append(distFromPtOnArc1)\n AvgList.append(distFromPtOnArc2)\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n resArc1.setArc(newArc1, False) \n resFilletArc.setArc(filletArc, False)\n resArc2.setArc(newArc2, False) \n \n if Avg == sys.float_info.max:\n return None \n\n if filletMode == 1: # 1=Taglia-estendi\n return [resArc1, resFilletArc, resArc2]\n else:\n return [None, resFilletArc, None]\n\n#===============================================================================\n# getFilletArcsBetweenArcs\n#===============================================================================\ndef getFilletArcsBetweenArcs(arc1, arc2, radius):\n \"\"\"\n la funzione raccorda due archi (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\" \n circle1 = QadCircle()\n circle1.set(arc1.getArc().center, arc1.getArc().radius)\n circle2 = QadCircle()\n circle2.set(arc2.getArc().center, arc2.getArc().radius)\n\n return getFilletArcsBetweenCircles(circle1, circle2, radius)\n\n\n#===============================================================================\n# bridgeTheGapBetweenArcCircle\n#===============================================================================\ndef bridgeTheGapBetweenArcCircle(arc, ptOnArc, circle, ptOnCircle, radius, filletMode):\n \"\"\"\n la funzione raccorda un arco e un cerchio (QadLinearObject) attraverso \n un arco di raccordo di raggio <radius> che più si avvicinza ai punti di selezione\n sull'arco <ptOnArc> e sul cerchio <ptCircle>.\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n \n Ritorna una lista di 3 elementi (None in caso di errore): \n una arco che sostituisce <arc>\n un arco, se = None non c'é arco di raccordo tra le due linee\n None\n \"\"\"\n # ricavo i possibili archi di raccordo\n _circle = circle.getCircle()\n filletArcs = getFilletArcsBetweenArcCircle(arc, _circle, radius)\n \n # cerco l'arco valido più vicino a ptOnArc e ptOnCircle\n AvgList = []\n Avg = sys.float_info.max \n\n resFilletArc = QadLinearObject()\n resArc = QadLinearObject()\n for filletArc in filletArcs:\n # ricavo il nuovo arco in modo che sia tangente con l'arco di raccordo \n newArc, distFromPtOnArc = getNewArcAccordingFilletArc(arc.getArc(), filletArc, ptOnArc)\n if newArc is None:\n continue\n \n # calcolo la distanza dal punto ptOnCircle\n if _circle.isPtOnCircle(filletArc.getStartPt()): # se il punto iniziale dell'arco di raccordo é sul cerchio\n distFromPtOnCircle = _circle.lengthBetween2Points(filletArc.getStartPt(), \\\n ptOnCircle, \\\n filletArc.getTanDirectionOnStartPt() + math.pi)\n else: # se il punto finale dell'arco di raccordo é sul cerchio\n distFromPtOnCircle = _circle.lengthBetween2Points(filletArc.getEndPt(), \\\n ptOnCircle, \\\n filletArc.getTanDirectionOnEndPt())\n\n del AvgList[:] \n AvgList.append(distFromPtOnArc)\n AvgList.append(distFromPtOnCircle)\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n resArc.setArc(newArc, False) \n resFilletArc.setArc(filletArc, False)\n \n if Avg == sys.float_info.max:\n return None \n\n if filletMode == 1: # 1=Taglia-estendi\n return [resArc, resFilletArc, None]\n else:\n return [None, resFilletArc, None]\n\n#===============================================================================\n# getFilletArcsBetweenArcCircle\n#===============================================================================\ndef getFilletArcsBetweenArcCircle(arc, circle, radius):\n \"\"\"\n la funzione raccorda un arco (QadLinearObject) e un cerchio attraverso \n un arco di raccordo di raggio <radius>.\n \n Ritorna una lista dei possibili archi\n \"\"\" \n circle1 = QadCircle()\n circle1.set(arc.getArc().center, arc.getArc().radius)\n\n return getFilletArcsBetweenCircles(circle1, circle, radius)\n\n\n#===============================================================================\n# pretreatment_offset\n#===============================================================================\ndef pretreatment_offset(partList):\n \"\"\"\n la funzione controlla le \"local self intersection\"> :\n se il segmento (o arco) i-esimo e il successivo hanno 2 intersezioni allora si inserisce un vertice\n nel segmento (o arco) i-esimo tra i 2 punti di intersezione.\n La funzione riceve una lista di segmenti ed archi e ritorna una nuova lista di parti\n \"\"\"\n # verifico se polilinea chiusa\n i = -1 if partList.isClosed() else 0 \n \n result = QadLinearObjectList()\n while i < partList.qty() - 1:\n if i == -1: # polilinea chiusa quindi prendo in esame l'ultimo segmento e il primo\n part = partList.getLinearObjectAt(-1)\n nextPart = partList.getLinearObjectAt(0)\n else: \n part = partList.getLinearObjectAt(i)\n nextPart = partList.getLinearObjectAt(i + 1)\n\n ptIntList = part.getIntersectionPtsWithLinearObject(nextPart)\n if len(ptIntList) == 2: # 2 punti di intersezione\n # calcolo il punto medio tra i 2 punti di intersezione in part\n if part.isSegment(): # segmento\n ptMiddle = getMiddlePoint(ptIntList[0], ptIntList[1])\n result.append([part.getStartPt(), ptMiddle])\n result.append([ptMiddle, part.getEndPt()])\n else: # arco\n arc1 = QadArc(part.getArc())\n arc2 = QadArc(part.getArc())\n # se i punti sono così vicini da essere considerati uguali\n if ptNear(part.getArc().getEndPt(), ptIntList[0]):\n ptInt = part.getArc().getEndPt()\n else:\n ptInt = part.getArc().getStartPt()\n \n angleInt = getAngleBy2Pts(part.getArc().center, ptInt)\n arc1.endAngle = angleInt\n arc2.startAngle = angleInt \n result.append([arc1, part.isInverseArc()])\n result.append([arc2, part.isInverseArc()])\n else: # un solo punto di intersezione\n result.append(part)\n \n i = i + 1\n \n if partList.isClosed() == False: # se non é chiusa aggiungo l'ultima parte\n if partList.qty() > 1:\n result.append(nextPart) \n else:\n result.append(partList.getLinearObjectAt(0)) \n \n return result\n\n\n#===============================================================================\n# getIntersectionPointInfo_offset\n#===============================================================================\ndef getIntersectionPointInfo_offset(part, nextPart):\n \"\"\"\n la funzione restituisce il punto di intersezione tra le 2 parti e\n e il tipo di intersezione per <part> e per <nextPart>.\n Alle parti deve essere già stato fatto l'offset singolarmente:\n \n 1 = TIP (True Intersection Point) se il punto di intersezione ottenuto estendendo \n le 2 parti si trova su <part>\n \n 2 = FIP (False Intersection Point) se il punto di intersezione ottenuto estendendo\n \n le 2 parti non si trova su <part>\n 3 = PFIP (Positive FIP) se il punto di intersezione é nella stessa direzione di part\n\n 4 = NFIP (Negative FIP) se il punto di intersezione é nella direzione opposta di part\n \"\"\"\n\n ptIntList = part.getIntersectionPtsOnExtensionWithLinearObject(nextPart)\n\n if len(ptIntList) == 0:\n if part.getEndPt() == nextPart.getStartPt(): # <nextPart> inizia dove finisce <part>\n return [part.getEndPt(), 1, 1] # TIP-TIP\n else:\n return None\n elif len(ptIntList) == 1:\n if part.isSegment(): # segmento\n if part.containsPt(ptIntList[0]):\n intTypePart = 1 # TIP\n else: # l'intersezione non é sul segmento (FIP)\n # se la direzione é la stessa del segmento\n if doubleNear(getAngleBy2Pts(part.getStartPt(), part.getEndPt()), \\\n getAngleBy2Pts(part.getStartPt(), ptIntList[0])):\n intTypePart = 3 # PFIP\n else:\n intTypePart = 4 # NFIP\n else: # arco\n if part.containsPt(ptIntList[0]):\n intTypePart = 1 # TIP\n else:\n intTypePart = 2 # FIP\n\n if nextPart.isSegment(): # segmento \n if nextPart.containsPt(ptIntList[0]):\n intTypeNextPart = 1 # TIP\n else: # l'intersezione non é sul segmento (FIP)\n # se la direzione é la stessa del segmento\n if doubleNear(getAngleBy2Pts(nextPart.getStartPt(), nextPart.getEndPt()), \\\n getAngleBy2Pts(nextPart.getStartPt(), ptIntList[0])):\n intTypeNextPart = 3 # PFIP\n else:\n intTypeNextPart = 4 # NFIP\n else: # arco\n if nextPart.containsPt(ptIntList[0]):\n intTypeNextPart = 1 # TIP\n else:\n intTypeNextPart = 2 # FIP\n\n return [ptIntList[0], intTypePart, intTypeNextPart]\n else: # 2 punti di intersezione\n # scelgo il punto più vicino al punto finale di part \n if part.isSegment(): # segmento\n if getDistance(ptIntList[0], part.getEndPt()) < getDistance(ptIntList[1], part.getEndPt()):\n ptInt = ptIntList[0]\n else:\n ptInt = ptIntList[1]\n\n if part.containsPt(ptInt):\n intTypePart = 1 # TIP\n else: # l'intersezione non é sul segmento (FIP)\n # se la direzione é la stessa del segmento\n if doubleNear(getAngleBy2Pts(part.getStartPt(), part.getEndPt()), \\\n getAngleBy2Pts(part.getStartPt(), ptInt)):\n intTypePart = 3 # PFIP\n else:\n intTypePart = 4 # NFIP\n\n # la seconda parte é sicuramente un'arco\n if nextPart.containsPt(ptInt):\n intTypeNextPart = 1 # TIP\n else: # l'intersezione non é sull'arco (FIP)\n intTypeNextPart = 2 # FIP \n\n return [ptInt, intTypePart, intTypeNextPart]\n else: # arco\n finalPt = part.getEndPt()\n\n if getDistance(ptIntList[0], finalPt) < getDistance(ptIntList[1], finalPt):\n ptInt = ptIntList[0]\n else:\n ptInt = ptIntList[1]\n\n if part.containsPt(ptInt):\n intTypePart = 1 # TIP\n else: # l'intersezione non é sull'arco (FIP)\n intTypePart = 2 # FIP \n\n if nextPart.isSegment(): # segmento\n if nextPart.containsPt(ptInt):\n intTypeNextPart = 1 # TIP\n else: # l'intersezione non é sul segmento (FIP)\n # se la direzione é la stessa del segmento\n if doubleNear(getAngleBy2Pts(nextPart.getStartPt(), nextPart.getEndPt()), \\\n getAngleBy2Pts(nextPart.getStartPt(), ptInt)):\n intTypeNextPart = 3 # PFIP\n else:\n intTypeNextPart = 4 # NFIP\n else : # arco\n if nextPart.containsPt(ptInt):\n intTypeNextPart = 1 # TIP\n else: # l'intersezione non é sull'arco (FIP)\n intTypeNextPart = 2 # FIP\n \n return [ptInt, intTypePart, intTypeNextPart]\n \n \n#===============================================================================\n# fillet2Parts_offset\n#===============================================================================\ndef fillet2Parts_offset(part, nextPart, offSetSide, offSetDist):\n \"\"\"\n la funzione raccorda 2 parti nei seguenti casi: \n 1) segmento-arco (PFIP-FIP, nessuna intersezione)\n 2) arco-segmento (FIP-NFIP, nessuna intersezione)\n 3) arco-arco (nessuna intersezione)\n \"\"\"\n # se la prima parte é un segmento e la seconda é un arco\n if part.isSegment():\n newNextPart = QadLinearObject(part)\n newNextPart.reverse() # rovescio la direzione\n newPart = QadLinearObject(nextPart)\n newPart.reverse() # rovescio la direzione\n newOffSetSide = \"left\" if offSetSide == \"right\" else \"right\"\n result = fillet2Parts_offset(newPart, newNextPart, newOffSetSide, offSetDist)\n result.setInverseArc(not result.isInverseArc()) # cambio verso\n return result\n else: # se la prima parte é un arco\n arc = part.getArc()\n inverse = part.isInverseArc()\n AngleProjected = getAngleBy2Pts(arc.center, part.getEndPt())\n if inverse == False: # l'arco gira verso sin\n if offSetSide == \"right\": # l'offset era verso l'esterno\n # calcolo il punto proiettato per ri-ottenere quello originale \n center = getPolarPointByPtAngle(arc.center, AngleProjected, arc.radius - offSetDist)\n else: # l'offset era verso l'interno\n center = getPolarPointByPtAngle(arc.center, AngleProjected, arc.radius + offSetDist) \n else: # l'arco gira verso destra\n if offSetSide == \"right\": # l'offset era verso l'interno\n center = getPolarPointByPtAngle(arc.center, AngleProjected, arc.radius + offSetDist) \n else: # l'offset era verso l'esterno\n center = getPolarPointByPtAngle(arc.center, AngleProjected, arc.radius - offSetDist)\n \n newArc = QadArc() \n # se il centro dell'arco di raccordo é interno all'arco di offset\n if getDistance(arc.center, center) < arc.radius: \n newArcInverse = inverse\n if inverse == False:\n newArc.fromStartCenterEndPts(arc.getEndPt(), \\\n center, \\\n nextPart.getStartPt())\n else:\n newArc.fromStartCenterEndPts(nextPart.getStartPt(), \\\n center, \\\n arc.getStartPt()) \n else: # se il centro dell'arco di raccordo é esterno all'arco di offset\n newArcInverse = not inverse\n if inverse == False:\n newArc.fromStartCenterEndPts(nextPart.getStartPt(), \\\n center, \\\n arc.getEndPt())\n else:\n newArc.fromStartCenterEndPts(arc.getStartPt(), \\\n center, \\\n nextPart.getStartPt())\n \n return QadLinearObject([newArc, newArcInverse]) \n\n\n#===============================================================================\n# getUntrimmedOffSetPartList\n#===============================================================================\ndef getUntrimmedOffSetPartList(partList, offSetDist, offSetSide, gapType, tolerance2ApproxCurve = None):\n \"\"\"\n la funzione fa l'offset non pulito da eventuali tagli da apportare (vedi\n getTrimmedOffSetPartList\") di una polilinea (lista di parti <partList> é QadLinearObjectList)\n secondo una distanza e un lato di offset (\"right\" o \"left\") \n ed un modo <gapType>:\n 0 = Estende i segmenti di linea alle relative intersezioni proiettate\n 1 = Raccorda i segmenti di linea in corrispondenza delle relative intersezioni proiettate.\n Il raggio di ciascun segmento di arco é uguale alla distanza di offset\n 2 = Cima i segmenti di linea in corrispondenza delle intersezioni proiettate.\n La distanza perpendicolare da ciascuna cima al rispettivo vertice\n sull'oggetto originale é uguale alla distanza di offset.\n tolerance2ApproxCurve = errore minimo di tolleranza\n \n La funzione ritorna una lista di parti della polilinee (lista di segmenti o archi) \n \"\"\"\n # verifico se polilinea chiusa\n isClosedPolyline = partList.isClosed()\n\n # creo una lista dei segmenti e archi che formano la polilinea\n partList = pretreatment_offset(partList)\n \n # faccio l'offset di ogni parte della polilinea\n newPartList = QadLinearObjectList()\n for part in partList.defList:\n if part.isSegment(): # segmento\n newPart = QadLinearObject(getOffSetLine(part.getStartPt(), part.getEndPt(), offSetDist, offSetSide))\n newPartList.append(newPart)\n else: # arco\n if part.isInverseArc(): # l'arco gira verso destra\n arcOffSetSide = \"internal\" if offSetSide == \"right\" else \"external\" \n else: # l'arco gira verso sin\n arcOffSetSide = \"external\" if offSetSide == \"right\" else \"internal\"\n \n newArc = getOffSetArc(part.getArc(), offSetDist, arcOffSetSide)\n if newArc is not None:\n newPart = QadLinearObject([newArc, part.isInverseArc()]) # <arco> e <inverse>\n newPartList.append(newPart)\n\n # calcolo i punti di intersezione tra parti adiacenti\n # per ottenere una linea di offset non tagliata\n if isClosedPolyline == True:\n i = -1\n else:\n i = 0 \n\n untrimmedOffsetPartList = QadLinearObjectList()\n virtualPartPositionList = []\n while i < newPartList.qty() - 1:\n if i == -1: # polylinea chiusa quindi prendo in esame l'ultimo segmento e il primo\n part = newPartList.getLinearObjectAt(-1) # ultima parte\n nextPart = newPartList.getLinearObjectAt(0) # prima parte\n else: \n part = newPartList.getLinearObjectAt(i)\n nextPart = newPartList.getLinearObjectAt(i + 1)\n\n if untrimmedOffsetPartList.qty() == 0:\n lastUntrimmedOffsetPt = part.getStartPt()\n else:\n lastUntrimmedOffsetPt = untrimmedOffsetPartList.getLinearObjectAt(-1).getEndPt() # ultima parte\n \n IntPointInfo = getIntersectionPointInfo_offset(part, nextPart)\n if IntPointInfo is not None: # se c'é un'intersezione\n IntPoint = IntPointInfo[0]\n IntPointTypeForPart = IntPointInfo[1]\n IntPointTypeForNextPart = IntPointInfo[2]\n\n if part.isSegment(): # segmento\n if nextPart.isSegment(): # segmento-segmento\n if IntPointInfo is not None: # se esiste un punto di intersezione\n if IntPointTypeForPart == 1: # TIP\n if IntPointTypeForNextPart == 1: # TIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, IntPoint])\n else: # FIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()]) \n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # FIP\n if IntPointTypeForPart == 3: # PFIP\n if gapType != 0:\n newLines = offsetBridgeTheGapBetweenLines(part, nextPart, offSetDist, gapType)\n untrimmedOffsetPartList.append(newLines[0]) \n untrimmedOffsetPartList.append(newLines[1]) # arco o linea di raccordo\n else: \n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, IntPoint])\n else: # NFIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()])\n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # segmento-arco\n if IntPointInfo is not None: # se esiste un punto di intersezione\n if IntPointTypeForPart == 1: # TIP\n if IntPointTypeForNextPart == 1: # TIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, IntPoint])\n else: # FIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()])\n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # FIP\n if IntPointTypeForPart == 3: # PFIP\n if IntPointTypeForNextPart == 2: # FIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()])\n untrimmedOffsetPartList.append(fillet2Parts_offset(part, nextPart, offSetSide, offSetDist)) \n else: # NFIP\n if IntPointTypeForNextPart == 1: # TIP\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()])\n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # non esiste un punto di intersezione\n untrimmedOffsetPartList.append([lastUntrimmedOffsetPt, part.getEndPt()])\n untrimmedOffsetPartList.append(fillet2Parts_offset(part, nextPart, offSetSide, offSetDist)) \n else: # arco\n if nextPart.isSegment(): # arco-segmento \n if IntPointInfo is not None: # se esiste un punto di intersezione\n if IntPointTypeForPart == 1: # TIP\n if IntPointTypeForNextPart == 1: # TIP\n newPart = QadLinearObject(part)\n newPart.setStartEndPts(lastUntrimmedOffsetPt, IntPoint) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n else: # FIP\n if IntPointTypeForNextPart == 3: # PFIP\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # FIP\n if IntPointTypeForNextPart == 4: # NFIP\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n untrimmedOffsetPartList.append(fillet2Parts_offset(part, nextPart, offSetSide, offSetDist)) \n elif IntPointTypeForNextPart == 1: # TIP\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n untrimmedOffsetPartList.append([part.getEndPt(), nextPart.getStartPt()])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # non esiste un punto di intersezione\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n untrimmedOffsetPartList.append(fillet2Parts_offset(part, nextPart, offSetSide, offSetDist)) \n else: # arco-arco\n arc = part.getArc()\n inverse = part.isInverseArc()\n nextArc = nextPart.getArc()\n nextInverse = nextPart.isInverseArc()\n\n if IntPointInfo is not None: # se esiste un punto di intersezione\n if IntPointTypeForPart == 1: # TIP\n if IntPointTypeForNextPart == 1: # TIP\n newPart = QadLinearObject(part)\n newPart.setStartEndPts(lastUntrimmedOffsetPt, IntPoint) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n else : # FIP\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n \n if inverse == False:\n center = getPolarPointByPtAngle(arc.center, arc.endAngle, arc.radius - offSetDist)\n else:\n center = getPolarPointByPtAngle(arc.center, arc.startAngle, arc.radius - offSetDist)\n \n secondPtNewArc = getPolarPointByPtAngle(center, \\\n getAngleBy2Pts(center, IntPoint), \\\n offSetDist) \n newArc = QadArc()\n newArc.fromStartSecondEndPts(part.getEndPt(), \\\n secondPtNewArc, \\\n nextPart.getStartPt())\n\n if ptNear(newArc.getStartPt(), part.getEndPt()):\n untrimmedOffsetPartList.append([newArc, False])\n else:\n untrimmedOffsetPartList.append([newArc, True])\n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # FIP\n if IntPointTypeForNextPart == 1: # TIP\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n \n if inverse == False:\n center = getPolarPointByPtAngle(arc.center, arc.endAngle, arc.radius - offSetDist)\n else:\n center = getPolarPointByPtAngle(arc.center, arc.startAngle, arc.radius - offSetDist)\n \n secondPtNewArc = getPolarPointByPtAngle(center, \\\n getAngleBy2Pts(center, IntPoint), \\\n offSetDist) \n newArc = QadArc()\n newArc.fromStartSecondEndPts(part.getEndPt(), \\\n secondPtNewArc, \\\n nextPart.getStartPt())\n if ptNear(newArc.getStartPt(), part.getEndPt()):\n untrimmedOffsetPartList.append([newArc, False])\n else:\n untrimmedOffsetPartList.append([newArc, True]) \n # aggiungo la posizione di questa parte virtuale\n virtualPartPositionList.append(untrimmedOffsetPartList.qty() - 1)\n else: # FIP\n newPart = QadLinearObject(part)\n newPart.setStartEndPts(lastUntrimmedOffsetPt, IntPoint) # modifico l'arco\n untrimmedOffsetPartList.append(newPart) \n else: # non esiste un punto di intersezione\n newPart = QadLinearObject(part)\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'arco\n untrimmedOffsetPartList.append(newPart)\n \n # prima di raccordare verifico se l'arco <part> si trova interamente dentro la zona di offset\n # dell'arco <nextPart> e viceversa. \n # Per replicare questa eccezione fare una polilinea composta da 2 archi:\n # il primo con centro in ..., raggio..., angolo iniziale ... angolo finale ...\n # il secondo con centro in ..., raggio..., angolo iniziale ... angolo finale ...\n # offset a destra = 8\n arc = part.getArc()\n nextArc = nextPart.getArc()\n dist = getDistance(arc.center, nextArc.center) \n minDistArc, maxDistArc = getOffsetDistancesFromCenterOnOffsetedArc(arc, inverse, offSetDist, offSetSide)\n minDistNextArc, maxDistNextArc = getOffsetDistancesFromCenterOnOffsetedArc(nextArc, nextInverse, offSetDist, offSetSide)\n \n if (dist + nextArc.radius <= maxDistArc and dist - nextArc.radius >= minDistArc) or \\\n (dist + arc.radius <= maxDistNextArc and dist - arc.radius >= minDistNextArc):\n untrimmedOffsetPartList.append([newPart.getEndPt(), nextPart.getStartPt()]) \n else: \n untrimmedOffsetPartList.append(fillet2Parts_offset(part, nextPart, offSetSide, offSetDist))\n \n i = i + 1\n\n if newPartList.qty() > 0:\n if isClosedPolyline == False:\n if untrimmedOffsetPartList.qty() == 0:\n # primo punto della prima parte di newPartList\n lastUntrimmedOffsetPt = newPartList.getLinearObjectAt(0).getStartPt()\n else:\n # ultimo punto dell'ultima parte di untrimmedOffsetPartList\n lastUntrimmedOffsetPt = untrimmedOffsetPartList.getLinearObjectAt(-1).getEndPt()\n \n newPart = QadLinearObject(newPartList.getLinearObjectAt(-1))\n newPart.setStartPt(lastUntrimmedOffsetPt) # modifico l'inizio\n untrimmedOffsetPartList.append(newPart)\n else:\n # primo punto = ultimo punto\n untrimmedOffsetPartList.getLinearObjectAt(0).setStartPt(untrimmedOffsetPartList.getLinearObjectAt(-1).getEndPt()) # modifico l'inizio\n\n # faccio un pre-clipping sulle parti virtuali\n return virtualPartClipping(untrimmedOffsetPartList, virtualPartPositionList)\n # test\n #return untrimmedOffsetPartList\n\n\n#===============================================================================\n# getOffsetDistancesFromCenterOnOffsetedArc\n#===============================================================================\ndef getOffsetDistancesFromCenterOnOffsetedArc(arc, isInverseArc, offSetDist, offSetSide):\n \"\"\"\n la funzione restituisce la distanza minima e massima dal centro dell'arco su cui è già stato fatto un offset.\n Queste distanze generano un'area di offset intorno all'arco originale.\n <arc> arco a cui è già stato fatto un offset\n <isInverseArc> come gira l'arco, se true gira verso destra altrimento gira verso sinistra\n <offSetDist> distanza di offset\n <offSetSide> parte in cui si vuole l'offset \"right\" o \"left\"\n \"\"\" \n if isInverseArc: # l'arco gira verso destra\n if offSetSide == \"right\": # offset sulla parte interna dell'arco\n minDist = arc.radius \n maxDist = arc.radius + 2 * offSetDist \n else: # offset sulla parte esterna dell'arco\n maxDist = arc.radius \n minDist = arc.radius - 2 * offSetDist\n else: # l'arco gira verso sin\n if offSetSide == \"right\": # offset sulla parte esterna dell'arco\n maxDist = arc.radius \n minDist = arc.radius - 2 * offSetDist\n else: # offset sulla parte interna dell'arco\n minDist = arc.radius \n maxDist = arc.radius + 2 * offSetDist\n \n if minDist < 0: minDist = 0 \n\n return minDist, maxDist\n\n\n#===============================================================================\n# virtualPartClipping\n#===============================================================================\ndef virtualPartClipping(untrimmedOffsetPartList, virtualPartPositionList):\n \"\"\"\n la funzione restituisce una lista di parti in cui vengono tagliate le isole generate\n da parti virtuali (che invertono il senso della linea).\n Per ogni parte virtuale, si verifica se le parti che precedono e che seguono formano un'isola.\n In caso affermativo, se possibile (vedi casi specifici), l'sola viene rimossa.\n <untrimmedOffsetPartList> lista delle parti\n <virtualPartPositionList> lista delle posizioni delle parti virtuali (viene modificata)\n \"\"\"\n result = QadLinearObjectList(untrimmedOffsetPartList)\n \n # per prima cosa elimino tutte le isole con parti virtuali che hanno le parti \n # direttamente adiacenti intersecanti\n i = len(virtualPartPositionList) - 1\n while i >= 0:\n virtualPartPosition = virtualPartPositionList[i]\n # parte successiva a quella virtuale\n nextPos = result.getNextPos(virtualPartPosition)\n # parte precedente\n prevPos = result.getPrevPos(virtualPartPosition)\n \n if (prevPos is not None) and (nextPos is not None):\n nextPart = result.getLinearObjectAt(nextPos)\n prevPart = result.getLinearObjectAt(prevPos)\n # verifico se hanno un solo punto di intersezione\n ptIntList = prevPart.getIntersectionPtsWithLinearObject(nextPart) \n if len(ptIntList) == 1:\n nextPart.setStartPt(ptIntList[0]) # modifico l'inizio\n prevPart.setEndPt(ptIntList[0]) # modifico la fine\n result.remove(virtualPartPosition)\n del virtualPartPositionList[i]\n \n i = i - 1\n \n prevPart_1 = QadLinearObject()\n prevPart_2 = QadLinearObject()\n nextPart_1 = QadLinearObject()\n nextPart_2 = QadLinearObject()\n\n # elimino tutte le isole con parti virtuali che hanno le parti adiacenti intersecanti\n # ma che non formino con il resto della linea altre isole.\n # quando considero un lato adiacente alla parte virtuale da un lato devo considerare le intersezioni \n # partendo dal lato successivo quello adicente nella parte opposta di quello virtuale \n for i in xrange(len(virtualPartPositionList) - 1, -1, -1): \n virtualPartPosition = virtualPartPositionList[i]\n # finché non trovo l'intersezione\n nPrevPartsToRemove = -1\n prevPos = virtualPartPosition\n ptIntList = [] \n while len(ptIntList) == 0:\n virtualPart = result.getLinearObjectAt(virtualPartPosition)\n # parte successiva a quella virtuale\n nextPos = result.getNextPos(virtualPartPosition)\n nNextPartsToRemove = 0\n # parte precedente\n prevPos = result.getPrevPos(prevPos)\n # se trovo una parte virtuale mi fermo\n if virtualPartPositionList.count(prevPos) > 0:\n break \n \n # l'ultima condizione é nel caso la polilinea sia chiusa\n if (prevPos is None) or (nextPos is None) or prevPos == nextPos:\n break\n\n nPrevPartsToRemove = nPrevPartsToRemove + 1\n prevPart = result.getLinearObjectAt(prevPos)\n \n # ciclo finche non ci sono più parti successive\n while (nextPos is not None) and (prevPos != nextPos):\n # se trovo una parte virtuale mi fermo\n if virtualPartPositionList.count(nextPos) > 0:\n break \n nextPart = result.getLinearObjectAt(nextPos)\n ptIntList = prevPart.getIntersectionPtsWithLinearObject(nextPart)\n if len(ptIntList) > 0:\n break\n nextPos = result.getNextPos(nextPos) # parte successiva\n nNextPartsToRemove = nNextPartsToRemove + 1\n \n if len(ptIntList) == 1 and \\\n not ptNear(ptIntList[0], virtualPart.getStartPt()) and \\\n not ptNear(ptIntList[0], virtualPart.getEndPt()):\n prevPart_1.set(prevPart) \n # se il punto iniziale della parte non coincide con quella del punto di intersezione\n if not ptNear(ptIntList[0], prevPart.getStartPt()):\n prevPart_1.setEndPt(ptIntList[0]) # modifico la fine \n prevPart_2.set(prevPart) \n prevPart_2.setStartPt(ptIntList[0]) # modifico l'inizio \n else:\n prevPart_2.clear()\n \n nextPart_1.set(nextPart) \n # se il punto finale della parte non coincide con quella del punto di intersezione\n if not ptNear(ptIntList[0], nextPart.getEndPt()):\n nextPart_1.setEndPt(ptIntList[0]) # modifico la fine \n nextPart_2.set(nextPart) \n nextPart_2.setStartPt(ptIntList[0]) # modifico l'inizio \n else:\n nextPart_2.clear() \n \n ########################################################\n # Creo una lista di parti che definisce l'isola - inizio\n islandPartList = QadLinearObjectList() \n \n islandPart = QadLinearObject(prevPart_2 if prevPart_2.isInitialized() else prevPart_1)\n islandPartList.append(islandPart)\n \n pos = virtualPartPosition \n for j in xrange(nPrevPartsToRemove, 0, - 1):\n pos = result.getPrevPos(pos) # parte precedente \n islandPartList.append(QadLinearObject(result.getLinearObjectAt(pos)))\n\n islandPartList.append(virtualPart)\n\n pos = virtualPartPosition \n for j in xrange(1, nNextPartsToRemove + 1, 1):\n pos = result.getNextPos(pos) # parte successiva \n islandPartList.append(QadLinearObject(result.getLinearObjectAt(pos)))\n\n islandPart = QadLinearObject(nextPart_1)\n islandPartList.append(islandPart)\n \n # Creo una lista di parti che definisce l'isola - fine\n ########################################################\n\n # verifico se le parti seguenti formano con islandPartList delle aree (più di 2 intersezioni) \n if nextPart_2.isInitialized():\n nIntersections = 1\n else:\n nIntersections = 0\n\n for j in xrange(nextPos + 1, result.qty(), 1): \n dummy = islandPartList.getIntersectionPtsWithLinearObject(result.getLinearObjectAt(j))\n intPtList = dummy[0] \n nIntersections = nIntersections + len(intPtList)\n\n # se é positivo e minore o uguale a 2 verifico anche dall'altra parte\n if nIntersections > 0 and nIntersections <= 2:\n # verifico se le parti precedenti formano con islandPartList delle aree (almeno 2 intersezioni)\n if prevPart_2.isInitialized():\n nIntersections = 1\n else:\n nIntersections = 0\n\n for j in xrange(prevPos - 1, -1, -1): \n dummy = islandPartList.getIntersectionPtsWithLinearObject(result.getLinearObjectAt(j))\n intPtList = dummy[0] \n nIntersections = nIntersections + len(intPtList)\n\n # se é positivo e minore o uguale a 2 verifico anche dall'altra parte\n if nIntersections > 0 and nIntersections <= 2:\n # rimuovo island da result\n if nextPart_2.isInitialized():\n nextPart.setStartPt(nextPart_2.getStartPt()) # modifico l'inizio\n else:\n result.remove(nextPos)\n\n # cancello le parti inutili\n for j in xrange(0, nNextPartsToRemove, 1):\n result.remove(virtualPartPosition + 1)\n \n # cancello la parte virtuale\n result.remove(virtualPartPosition)\n \n # cancello le parti inutili\n for j in xrange(0, nPrevPartsToRemove, 1):\n result.remove(virtualPartPosition - nPrevPartsToRemove)\n\n if prevPart_2.isInitialized():\n prevPart.setEndPt(nextPart_2.getStartPt()) # modifico la fine \n else:\n result.remove(prevPos)\n\n del virtualPartPositionList[i]\n\n return result\n\n\n#===============================================================================\n# getIntPtListBetweenPartAndPartList_offset\n#===============================================================================\ndef getIntPtListBetweenPartAndPartList_offset(part, partList):\n \"\"\"\n la funzione restituisce due liste:\n la prima é una lista di punti di intersezione tra la parte <part>\n e una lista di parti <partList ordinata per distanza dal punto iniziale\n di part (scarta i doppioni e i punti iniziale-finale di part)\n la seconda é una lista che contiene, rispettivamente per ogni punto di intersezione,\n il numero della parte (0-based) di <partList> in cui si trova quel punto.\n <part>: un segmento o arco \n <partList>: lista delle parti di una polilinea \n \"\"\"\n startPtOfPart = part.getStartPt()\n endPtOfPart = part.getEndPt()\n intPtSortedList = [] # lista di ((punto, distanza dall'inizio della parte) ...)\n partNumber = -1\n # per ogni parte di partList\n for part2 in partList.defList:\n partNumber = partNumber + 1\n partialIntPtList = part.getIntersectionPtsWithLinearObject(part2)\n for partialIntPt in partialIntPtList:\n # escludo i punti che sono all'inizio-fine di part\n \n # se i punti sono così vicini da essere considerati uguali \n if ptNear(startPtOfPart, partialIntPt) == False and \\\n ptNear(endPtOfPart, partialIntPt) == False:\n # escludo i punti che sono già in intPtSortedList\n found = False\n for intPt in intPtSortedList:\n if ptNear(intPt[0], partialIntPt):\n found = True\n break\n \n if found == False:\n # inserisco il punto ordinato per distanza dal inizio di part\n distFromStart = part.getDistanceFromStart(partialIntPt)\n insertAt = 0\n for intPt in intPtSortedList:\n if intPt[1] < distFromStart:\n insertAt = insertAt + 1\n else:\n break \n intPtSortedList.insert(insertAt, [partialIntPt, distFromStart, partNumber])\n resultIntPt = []\n resultPartNumber = []\n for intPt in intPtSortedList:\n resultIntPt.append(intPt[0])\n resultPartNumber.append(intPt[2])\n\n return resultIntPt, resultPartNumber\n\n\n#===============================================================================\n# dualClipping\n#===============================================================================\ndef dualClipping(partList, untrimmedOffsetPartList, untrimmedReversedOffsetPartList, offSetDist):\n \"\"\"\n la funzione effettua il dual clipping su untrimmedOffsetPartList.\n <partList>: lista delle parti originali della polilinea \n <untrimmedOffsetPartList>: lista delle parti non tagliate derivate dall'offset\n <untrimmedReversedOffsetPartList>: lista delle parti non tagliate derivate dall'offset in senso inverso\n \n La funzione ritorna una lista di parti risultato del dual clipping \n \"\"\"\n \n # inizio Dual Clipping\n dualClippedPartList = QadLinearObjectList()\n \n # linea spezzata sui self intersection points e \n # sui punti di intersezione con untrimmedReversedOffsetPartList\n \n # per ogni parte di untrimmedOffsetPartList\n for part in untrimmedOffsetPartList.defList:\n # calcola i punti di intersezione di part con untrimmedOffsetPartList ordinati x distanza\n # (self intersection points) \n dummy = getIntPtListBetweenPartAndPartList_offset(part, untrimmedOffsetPartList)\n intPtList = dummy[0]\n\n if len(intPtList) > 0:\n # inserisco dividendo part\n intPt = intPtList[0]\n newPart = QadLinearObject(part) \n newPart.setEndPt(intPt)\n dualClippedPartList.append(newPart)\n i = 1\n while i < len(intPtList):\n newPart = QadLinearObject(part) \n newPart.setStartPt(intPt)\n intPt = intPtList[i]\n newPart.setEndPt(intPt)\n dualClippedPartList.append(newPart)\n i = i + 1\n newPart = QadLinearObject(part) \n newPart.setStartPt(intPt)\n dualClippedPartList.append(newPart) \n else: # inserisco part intera\n dualClippedPartList.append(part)\n \n # ciclo per spezzare dualClippedPartList \n # sui punti di intersezione con untrimmedReversedOffsetPartList\n i = 0\n while i < dualClippedPartList.qty():\n part = dualClippedPartList.getLinearObjectAt(i)\n # calcola i punti di intersezione di part con untrimmedReversedOffsetPartList ordinati x distanza \n dummy = getIntPtListBetweenPartAndPartList_offset(part, untrimmedReversedOffsetPartList) \n intPtList = dummy[0]\n\n for intPt in intPtList:\n newPart = QadLinearObject(part)\n newPart.setEndPt(intPt)\n dualClippedPartList.insert(i + 1, newPart) \n newPart = QadLinearObject(part)\n newPart.setStartPt(intPt)\n dualClippedPartList.insert(i + 2, newPart)\n dualClippedPartList.remove(i)\n i = i + 1\n \n i = i + 1\n\n isClosedPolyline = dualClippedPartList.isClosed() # verifico se polilinea chiusa\n splittedParts = QadLinearObjectList()\n circle = QadCircle()\n i = 0\n # per ogni parte\n while i < dualClippedPartList.qty():\n part = dualClippedPartList.getLinearObjectAt(i)\n # calcola i punti di intersezione con partList \n dummy = getIntPtListBetweenPartAndPartList_offset(part, partList)\n intPtList = dummy[0]\n partNumberList = dummy[1]\n \n if len(intPtList) > 0:\n if isClosedPolyline:\n firstOrLastPart = False\n else:\n # verifico se tutti i punti di intersezione sono sul primo o sull'ultimo segmento di partList\n firstOrLastPart = True\n for partNumber in partNumberList:\n if partNumber != 0 and partNumber != partList.qty() -1:\n firstOrLastPart = False\n break\n \n # se tutti i punti di intersezione sono sul primo o sull'ultimo segmento di partList\n if firstOrLastPart:\n splittedParts.removeAll() # pulisco la lista\n splittedParts.append(QadLinearObject(part))\n for intPt in intPtList:\n j = 0\n while j < splittedParts.qty():\n splittedPart = splittedParts.getLinearObjectAt(j) \n # creo un cerchio nel punto di intersezione\n circle.set(intPt, offSetDist)\n # ottengo le parti esterne al cerchio \n externalPartsOfIntPt = splittedPart.getPartsExternalToCircle(circle)\n if externalPartsOfIntPt.qty() > 0:\n for externalPartOfIntPt in externalPartsOfIntPt.defList:\n splittedParts.insert(j, externalPartOfIntPt)\n j = j + 1\n splittedParts.remove(j)\n \n # le sostituisco a part\n for splittedPart in splittedParts.defList:\n dualClippedPartList.insert(i, splittedPart)\n i = i + 1\n dualClippedPartList.remove(i)\n else: # se tutti i punti di intersezione non sono sul primo o sull'ultimo segmento di partList\n dualClippedPartList.remove(i)\n else:\n i = i + 1\n \n return dualClippedPartList\n\n\n#===============================================================================\n# generalClosedPointPairClipping\n#===============================================================================\ndef generalClosedPointPairClipping(partList, dualClippedPartList, offSetDist):\n \"\"\"\n la funzione effettua il general closed point pair clipping su dualClippedPartList.\n <partList>: lista delle parti originali della polilinea \n <dualClippedPartList>: lista delle parti risultato del dual clipping\n <offSetDist> distanza di offset\n \n La funzione ritorna una lista di parti risultato del dual clipping \n \"\"\"\n # inizio di General Closed Point Pair clipping\n GCPPCList = QadLinearObjectList(dualClippedPartList) # duplico la lista di parti \n circle = QadCircle()\n \n # per ogni parte di partList\n for part in partList.defList:\n # per ogni parte di GCPPCList\n i = 0\n while i < GCPPCList.qty():\n # ripeto finché viene fatto lo split \n splitted = True\n while splitted:\n splitted = False\n GCPPCPart = GCPPCList.getLinearObjectAt(i)\n # verifico quale é il punto di part più vicino a GCPPCPart\n # (<punto di distanza minima sulla parte 1><punto di distanza minima sulla parte 2><distanza minima>)\n MinDistancePts = part.getMinDistancePtsWithLinearObject(GCPPCPart)\n # se la distanza é inferiore a offSetDist (e non così vicina da essere considerata uguale)\n if MinDistancePts[2] < offSetDist and not doubleNear(MinDistancePts[2], offSetDist):\n # creo un cerchio nel punto di part più vicino a GCPPCPart\n circle.set(MinDistancePts[0], offSetDist)\n # ottengo le parti di GCPPCPart esterne al cerchio \n splittedParts = GCPPCPart.getPartsExternalToCircle(circle)\n # se la splittedParts è composta da una sola parte che è uguale a GCPPCPart\n # ad es. se GCPPCPart è tangente al cerchio allora non faccio niente\n if splittedParts.qty() == 0 or \\\n splittedParts.qty() == 1 and splittedParts.getLinearObjectAt(0) == GCPPCPart:\n i = i + 1\n else:\n # le sostituisco a GCPPCPart\n for splittedPart in splittedParts.defList:\n GCPPCList.insert(i, splittedPart)\n i = i + 1\n GCPPCList.remove(i)\n if splittedParts.qty() > 0:\n splitted = True\n i = i - splittedParts.qty() # torno alla prima parte risultato dello split\n else:\n i = i + 1\n \n return GCPPCList\n\n\n#===============================================================================\n# getTrimmedOffSetPartList\n#===============================================================================\ndef getTrimmedOffSetPartList(partList, epsg, untrimmedOffsetPartList, untrimmedReversedOffsetPartList, \\\n offSetDist):\n \"\"\"\n la funzione taglia la polilinea dove necessario.\n <partList>: lista delle parti originali della polilinea \n <epsg> = the authority identifier for this srs \n <untrimmedOffsetPartList>: lista delle parti non tagliate derivate dall'offset\n <untrimmedReversedOffsetPartList>: lista delle partinon tagliate derivate dall'offset in senso inverso\n <offSetDist> distanza di offset\n \n La funzione ritorna una lista di parti della polilinee (lista di segmenti o archi) \n \"\"\"\n \n # faccio il dual clipping\n dualClippedPartList = dualClipping(partList, untrimmedOffsetPartList, untrimmedReversedOffsetPartList, offSetDist)\n # test\n #GCPPCList = untrimmedOffsetPartList\n #GCPPCList = dualClipping(partList, untrimmedOffsetPartList, untrimmedReversedOffsetPartList, offSetDist)\n \n # faccio il general closed point pair clipping\n # test\n GCPPCList = generalClosedPointPairClipping(partList, dualClippedPartList, offSetDist)\n\n # faccio il join tra le parti\n return GCPPCList.selfJoin(epsg)\n \n#===============================================================================\n# offSetPolyline\n#===============================================================================\ndef offSetPolyline(points, epsg, offSetDist, offSetSide, gapType, tolerance2ApproxCurve = None):\n \"\"\"\n la funzione fa l'offset di una polilinea (lista di punti = <points>)\n secondo una distanza e un lato di offset (\"right\" o \"left\") \n ed un modo <gapType>:\n 0 = Estende i segmenti di linea alle relative intersezioni proiettate\n 1 = Raccorda i segmenti di linea in corrispondenza delle relative intersezioni proiettate.\n Il raggio di ciascun segmento di arco é uguale alla distanza di offset\n 2 = Cima i segmenti di linea in corrispondenza delle intersezioni proiettate.\n La distanza perpendicolare da ciascuna cima al rispettivo vertice\n sull'oggetto originale é uguale alla distanza di offset.\n <epsg> = the authority identifier for this srs \n <tolerance2ApproxCurve> = errore minimo di tolleranza\n \n La funzione ritorna una lista di polilinee (lista di liste di punti) \n \"\"\"\n if tolerance2ApproxCurve is None:\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n else:\n tolerance = tolerance2ApproxCurve\n \n result = []\n \n pointsLen = len(points)\n\n # verifico se é un cerchio\n circle = QadCircle()\n startEndVertices = circle.fromPolyline(points, 0)\n if startEndVertices is not None and \\\n startEndVertices[0] == 0 and startEndVertices[1] == (pointsLen - 1):\n # siccome i punti del cerchio sono disegnati in senso antiorario\n # se offSetSide = \"right\" significa verso l'esterno del cerchio\n # se offSetSide = \"left\" significa verso l'interno del cerchio\n if offSetSide == \"left\":\n # offset verso l'interno del cerchio\n offSetCircle = getOffSetCircle(circle, offSetDist, \"internal\")\n else:\n # offset verso l'esterno del cerchio\n offSetCircle = getOffSetCircle(circle, offSetDist, \"external\") \n \n if offSetCircle is not None:\n result.append(offSetCircle.asPolyline(tolerance))\n \n return result\n \n # creo una lista dei segmenti e archi che formano la polilinea\n partList = QadLinearObjectList()\n partList.fromPolyline(points)\n # ottengo la polilinea di offset non tagliata\n untrimmedOffsetPartList = getUntrimmedOffSetPartList(partList, offSetDist, offSetSide, gapType, tolerance)\n # inverto il senso dei punti x ottenere la polilinea di offset non tagliata invertita\n reversedPoints = list(points) # duplico la lista\n reversedPoints.reverse()\n reversedPartList = QadLinearObjectList()\n reversedPartList.fromPolyline(reversedPoints)\n\n untrimmedReversedOffsetPartList = getUntrimmedOffSetPartList(reversedPartList, offSetDist, offSetSide, gapType, tolerance)\n # taglio la polilinea dove necessario\n trimmedOffsetPartList = getTrimmedOffSetPartList(partList, epsg, \\\n untrimmedOffsetPartList, \\\n untrimmedReversedOffsetPartList, \\\n offSetDist)\n \n # ottengo una lista di punti delle nuove polilinee\n result = []\n for trimmedOffsetPart in trimmedOffsetPartList:\n result.append(trimmedOffsetPart.asPolyline())\n \n return result\n\n#===============================================================================\n# getAdjustedRubberBandVertex\n#===============================================================================\ndef getAdjustedRubberBandVertex(vertexBefore, vertex):\n adjustedVertex = QgsPoint(vertex)\n \n # per un baco non ancora capito in QGIS: se la linea ha solo 2 vertici e \n # hanno la stessa x o y (linea orizzontale o verticale) \n # la linea non viene disegnata perciò sposto un pochino la x o la y\n # del secondo vertice \n if vertexBefore.x() == vertex.x():\n adjustedVertex.setX(vertex.x() + 1.e-9)\n if vertexBefore.y() == vertex.y():\n adjustedVertex.setY(vertex.y() + 1.e-9)\n \n return adjustedVertex\n\n\n#===============================================================================\n# ApproxCurvesOnGeom\n#===============================================================================\ndef ApproxCurvesOnGeom(geom, atLeastNSegmentForArc = None, atLeastNSegmentForCircle = None,\n tolerance2ApproxCurve = None):\n \"\"\"\n ritorna una geometria le cui curve sono approssimate secondo una tolleranza di errore\n atLeastNSegment = numero minimo di segmenti per riconoscere una curva\n tolerance2ApproxCurve = errore minimo di tolleranza\n \"\"\" \n if tolerance2ApproxCurve is None:\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n else:\n tolerance = tolerance2ApproxCurve\n \n if atLeastNSegmentForArc is None:\n _atLeastNSegmentForArc = QadVariables.get(QadMsg.translate(\"Environment variables\", \"ARCMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegmentForArc = atLeastNSegmentForArc\n \n if atLeastNSegmentForCircle is None:\n _atLeastNSegmentForCircle = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegmentForCircle = atLeastNSegmentForCircle\n \n g = QgsGeometry(geom) # copio la geometria\n \n # verifico se ci sono archi\n arcList = QadArcList()\n arcList.fromGeom(g, _atLeastNSegmentForArc)\n \n # verifico se ci sono cerchi\n circleList = QadCircleList()\n circleList.fromGeom(g, _atLeastNSegmentForCircle)\n\n beforeVertex = 1\n \n # dall'ultimo arco al primo\n for i in xrange(len(arcList.arcList) - 1, -1, -1): \n arc = arcList.arcList[i]\n startVertex = arcList.startEndVerticesList[i][0]\n endVertex = arcList.startEndVerticesList[i][1]\n points = arc.asPolyline(tolerance)\n # inserisco i nuovi vertici saltando il primo e l'ultimo\n if arc.getStartPt() == g.vertexAt(startVertex):\n for i in xrange(len(points) - 2, 0, -1): \n if g.insertVertex(points[i].x(), points[i].y(), endVertex) == False:\n return None\n else:\n for i in xrange(1, len(points), 1): \n if g.insertVertex(points[i].x(), points[i].y(), endVertex) == False:\n return None\n # cancello i vecchi vertici\n for i in range(0, endVertex - startVertex - 1):\n if g.deleteVertex(startVertex + 1) == False:\n return None\n\n # dall'ultimo cerchio al primo\n for i in xrange(len(circleList.circleList) - 1, -1, -1): \n circle = circleList.circleList[i]\n startVertex = circleList.startEndVerticesList[i][0]\n endVertex = circleList.startEndVerticesList[i][1]\n points = circle.asPolyline(tolerance)\n # inserisco i nuovi vertici saltando il primo e l'ultimo\n for i in xrange(len(points) - 2, 0, -1): \n if g.insertVertex(points[i].x(), points[i].y(), endVertex) == False:\n return None\n # cancello i vecchi vertici\n for i in range(0, endVertex - startVertex - 1):\n if g.deleteVertex(startVertex + 1) == False:\n return None\n\n return g\n\n#===============================================================================\n# whatGeomIs\n#===============================================================================\ndef whatGeomIs(pt, geom):\n if type(pt) == int: # pt é il numero del vertice\n afterVertex = pt\n else: \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>)\n dummy = closestSegmentWithContext(pt, geom)\n afterVertex = dummy[2]\n if afterVertex is None:\n return None\n\n arcList = QadArcList()\n circleList = QadCircleList()\n\n # verifico se pt si riferisce ad un arco\n if arcList.fromGeom(geom) > 0:\n info = arcList.arcAt(afterVertex)\n if info is not None:\n return info[0]\n \n # verifico se pt si riferisce ad un cerchio\n if circleList.fromGeom(geom) > 0:\n info = circleList.circleAt(afterVertex)\n if info is not None:\n return info[0]\n \n # se non é un cerchio é una linea\n pt1 = geom.vertexAt(afterVertex - 1)\n pt2 = geom.vertexAt(afterVertex)\n return pt1, pt2\n\n\n#===============================================================================\n# solveApollonius\n#===============================================================================\ndef solveApollonius(c1, c2, c3, s1, s2, s3):\n '''\n >>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), 1,1,1)\n Circle(x=2.0, y=2.1, r=3.9)\n >>> solveApollonius((0, 0, 1), (4, 0, 1), (2, 4, 2), -1,-1,-1)\n Circle(x=2.0, y=0.8333333333333333, r=1.1666666666666667) \n Trova il cerchio tangente a tre cerchi (sarebbero 8 cerchi che si trovano con le \n 8 combinazioni di s1, s2, s3 che assumo valore -1 o 1)\n '''\n x1 = c1.center.x()\n y1 = c1.center.y()\n r1 = c1.radius\n x2 = c2.center.x()\n y2 = c2.center.y()\n r2 = c2.radius\n x3 = c3.center.x()\n y3 = c3.center.y()\n r3 = c3.radius\n \n v11 = 2*x2 - 2*x1\n v12 = 2*y2 - 2*y1\n v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2\n v14 = 2*s2*r2 - 2*s1*r1\n \n v21 = 2*x3 - 2*x2\n v22 = 2*y3 - 2*y2\n v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3\n v24 = 2*s3*r3 - 2*s2*r2\n \n if v11 == 0:\n return None\n \n w12 = v12/v11\n w13 = v13/v11\n w14 = v14/v11\n \n if v21-w12 == 0 or v21-w13 == 0 or v21-w14 == 0:\n return None\n \n w22 = v22/v21-w12\n w23 = v23/v21-w13\n w24 = v24/v21-w14\n \n if w22 == 0:\n return None\n \n P = -w23/w22\n Q = w24/w22\n M = -w12*P-w13\n N = w14 - w12*Q\n \n a = N*N + Q*Q - 1\n b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1\n c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1\n \n # Find a root of a quadratic equation. This requires the circle centers not to be e.g. colinear\n if a == 0:\n return None\n D = (b * b) - (4 * a * c)\n \n # se D é così vicino a zero \n if doubleNear(D, 0.0):\n D = 0\n elif D < 0: # non si può fare la radice quadrata di un numero negativo\n return None\n \n rs = (-b-math.sqrt(D))/(2*a)\n \n xs = M+N*rs\n ys = P+Q*rs\n \n center = QgsPoint(xs, ys)\n circle = QadCircle() \n circle.set(center, rs)\n return circle\n\n\n#===============================================================================\n# solveCircleTangentTo2LinesAndCircle\n#===============================================================================\ndef solveCircleTangentTo2LinesAndCircle(line1, line2, circle, s1, s2):\n '''\n Trova i due cerchi tangenti a due rette e un cerchio (sarebbero 8 cerchi che si trovano con le \n 4 combinazioni di s1, s2 che assumo valore -1 o 1)\n e restituisce quello più vicino a pt\n '''\n circleList = []\n # http://www.batmath.it/matematica/a_apollonio/rrc.htm\n\n # Questa costruzione utilizza una particolare trasformazione geometrica, che alcuni chiamano dilatazione parallela:\n # si immagina che il raggio r del cerchio dato c si riduca a zero (il cerchio é ridotto al suo centro),\n # mentre le rette rimangono parallele con distanze dal centro del cerchio che si é ridotto a zero aumentate o\n # diminuite di r. Si é così ricondotti al caso di un punto e due rette e si può applicare una delle tecniche viste\n # in quel caso. \n\n line1Par = []\n angle = getAngleBy2Pts(line1[0], line1[1])\n line1Par.append(getPolarPointByPtAngle(line1[0], angle + math.pi / 2, circle.radius * s1))\n line1Par.append(getPolarPointByPtAngle(line1[1], angle + math.pi / 2, circle.radius * s1))\n\n line2Par = []\n angle = getAngleBy2Pts(line2[0], line2[1])\n line2Par.append(getPolarPointByPtAngle(line2[0], angle + math.pi / 2, circle.radius * s2))\n line2Par.append(getPolarPointByPtAngle(line2[1], angle + math.pi / 2, circle.radius * s2))\n \n circleTan = QadCircle() \n circleList = circleTan.from1IntPtLineLineTanPts(circle.center, line1Par, None, line2Par, None, True)\n\n for circleTan in circleList:\n ptPerp = getPerpendicularPointOnInfinityLine(line1[0], line1[1], circleTan.center)\n circleTan.radius = getDistance(ptPerp, circleTan.center)\n \n return circleList\n \n\n#===============================================================================\n# solveCircleTangentToLineAnd2Circles\n#===============================================================================\ndef solveCircleTangentToLineAnd2Circles(line, circle1, circle2, s1, s2):\n '''\n Trova i due cerchi tangenti a una retta e due cerchi (sarebbero 8 cerchi che si trovano con le \n 4 combinazioni di s1, s2 che assumo valore -1 o 1)\n e restituisce quello più vicino a pt\n '''\n # http://www.batmath.it/matematica/a_apollonio/rcc.htm\n\n # Il modo più semplice per risolvere questo problema é quello di utilizzare una particolare \n # trasformazione geometrica, che alcuni chiamano dilatazione parallela: si immagina che il raggio r \n # del più piccolo dei cerchi in questione si riduca a zero (il cerchio é ridotto al suo centro), \n # mentre le rette (risp. gli altri cerchi) rimangono parallele (risp. concentrici) con distanze\n # dal centro del cerchio che si é ridotto a zero (rispettivamente con raggi dei cerchi) aumentati o \n # diminuiti di r. \n # Se applichiamo questa trasformazione al nostro caso, riducendo a zero il raggio del cerchio più piccolo\n # (o di uno dei due se hanno lo stesso raggio) ci ritroveremo con un punto, un cerchio e una retta:\n # trovate le circonferenze passanti per il punto e tangenti alla retta e al cerchio (nel modo già noto)\n # potremo applicare la trasformazione inversa della dilatazione parallela precedente per determinare\n # le circonferenze richieste.\n if circle1.radius <= circle2.radius:\n smallerCircle = circle1\n greaterCircle = circle2\n else:\n smallerCircle = circle2\n greaterCircle = circle1\n \n linePar = []\n angle = getAngleBy2Pts(line[0], line[1])\n linePar.append(getPolarPointByPtAngle(line[0], angle + math.pi / 2, smallerCircle.radius * s1))\n linePar.append(getPolarPointByPtAngle(line[1], angle + math.pi / 2, smallerCircle.radius * s1))\n\n circlePar = QadCircle(greaterCircle)\n circlePar.radius = circlePar.radius + smallerCircle.radius * s1\n \n circleTan = QadCircle()\n circleList = circleTan.from1IntPtLineCircleTanPts(smallerCircle.center, linePar, None, circlePar, None, True)\n\n for circleTan in circleList:\n ptPerp = getPerpendicularPointOnInfinityLine(line[0], line[1], circleTan.center)\n circleTan.radius = getDistance(ptPerp, circleTan.center)\n \n return circleList\n\n\ndef getCircularInversionOfpoint(circleRef, pt):\n \"\"\"\n la funzione ritorna l'inversione circolare di un punto\n \"\"\"\n dist = getDistance(circleRef.center, pt)\n angle = getAngleBy2Pts(circleRef.center, pt)\n circInvDist = circleRef.radius * circleRef.radius / dist\n return getPolarPointByPtAngle(circleRef.center, angle, circInvDist)\n\n \ndef getCircularInversionOfLine(circleRef, line):\n \"\"\"\n la funzione ritorna l'inversione circolare di una linea (che é un cerchio)\n \"\"\"\n angleLine = getAngleBy2Pts(line[0], line[1])\n ptNearestLine = getPerpendicularPointOnInfinityLine(line[0], line[1], circleRef.center)\n dist = getDistance(circleRef.center, ptNearestLine)\n\n pt1 = getCircularInversionOfpoint(circleRef, ptNearestLine)\n\n pt = getPolarPointByPtAngle(ptNearestLine, angleLine, dist)\n pt2 = getCircularInversionOfpoint(circleRef, pt)\n\n pt = getPolarPointByPtAngle(ptNearestLine, angleLine + math.pi, dist)\n pt3 = getCircularInversionOfpoint(circleRef, pt)\n \n result = QadCircle()\n if result.from3Pts(pt1, pt2, pt3) == False:\n return None\n \n return result\n\n\ndef getCircularInversionOfCircle(circleRef, circle):\n \"\"\"\n la funzione ritorna l'inversione circolare di un cerchio (che é un cerchio)\n \"\"\"\n\n angleLine = getAngleBy2Pts(circle.center, circleRef.center)\n ptNearestLine = getPolarPointByPtAngle(circle.center, angleLine, circle.radius)\n dist = getDistance(circleRef.center, circle.center)\n\n pt1 = getCircularInversionOfpoint(circleRef, ptNearestLine)\n\n pt = getPolarPointByPtAngle(circle.center, angleLine + math.pi / 2, circle.radius)\n pt2 = getCircularInversionOfpoint(circleRef, pt)\n\n pt = getPolarPointByPtAngle(circle.center, angleLine - math.pi / 2, circle.radius)\n pt3 = getCircularInversionOfpoint(circleRef, pt)\n \n result = QadCircle()\n if result.from3Pts(pt1, pt2, pt3) == False:\n return None\n \n return result\n\n\n#===============================================================================\n# lineFrom2TanPts\n#===============================================================================\ndef lineFrom2TanPts(geom1, pt1, geom2, pt2):\n '''\n Trova la linea tangente a 2 oggetti \n geometria 1 di tangenza (arco o cerchio)\n punto di selezione geometria 1\n geometria 2 di tangenza (arco o cerchio)\n punto di selezione geometria 2\n '''\n obj1 = whatGeomIs(pt1, geom1)\n obj2 = whatGeomIs(pt2, geom2)\n\n if (type(obj1) == list or type(obj1) == tuple): # se linea esco\n return None\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle1 = QadCircle()\n circle1.set(obj1.center, obj1.radius)\n else:\n circle1 = QadCircle(obj1)\n\n if (type(obj2) == list or type(obj2) == tuple): # se linea esco\n return None\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle2 = QadCircle()\n circle2.set(obj2.center, obj2.radius)\n else:\n circle2 = QadCircle(obj2)\n\n tangents = circle1.getTangentsWithCircle(circle2)\n \n if obj1Type == \"ARC\" or obj2Type == \"ARC\":\n # cancello le linee di tangenza che non abbiano un punto di tangenza nell'arco\n for i in xrange(len(tangents) - 1, -1, -1): \n toDelete1 = False \n toDelete2 = False \n if obj1Type == \"ARC\":\n toDelete1 = True \n for point in tangents[i]:\n if obj1.isPtOnArc(point) == True:\n toDelete1 = False\n if obj2Type == \"ARC\":\n toDelete2 = True \n for point in tangents[i]:\n if obj2.isPtOnArc(point) == True:\n toDelete2 = False\n \n if toDelete1 == True or toDelete2 == True:\n del tangents[i] \n\n if len(tangents) == 0:\n return None\n \n AvgList = []\n Avg = sys.float_info.max\n for tangent in tangents:\n del AvgList[:] # svuoto la lista\n \n ptInt = getPerpendicularPointOnInfinityLine(tangent[0], tangent[1], obj1.center)\n AvgList.append(getDistance(ptInt, pt1))\n\n ptInt = getPerpendicularPointOnInfinityLine(tangent[0], tangent[1], obj2.center)\n AvgList.append(getDistance(ptInt, pt2))\n\n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n result = tangent \n \n return result\n\n\n#===============================================================================\n# lineFromTanPerPts\n#===============================================================================\ndef lineFromTanPerPts(tanGeom1, tanPt1, perGeom2, perPt2):\n '''\n Trova la linea tangente a 1 oggetto e perpendicolare ad un altro \n geometria di tangenza (arco o cerchio)\n punto di selezione geometria di tangenza\n geometria di perpendicolarità (linea, arco o cerchio)\n punto di selezione geometria di perpendicolarità\n '''\n obj1 = whatGeomIs(tanPt1, tanGeom1)\n obj2 = whatGeomIs(perPt2, perGeom2)\n\n if (type(obj1) == list or type(obj1) == tuple): # se linea esco\n return None\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle1 = QadCircle()\n circle1.set(obj1.center, obj1.radius)\n else:\n circle1 = QadCircle(obj1)\n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle2 = QadCircle()\n circle2.set(obj2.center, obj2.radius)\n else:\n circle2 = QadCircle(obj2)\n\n lines = []\n if obj2Type == \"LINE\":\n # linee tangenti ad un cerchio e perpendicolari ad una linea\n angle = getAngleBy2Pts(obj2[0], obj2[1])\n pt1 = getPolarPointByPtAngle(circle1.center, angle, circle1.radius)\n pt2 = getPerpendicularPointOnInfinityLine(obj2[0], obj2[1], pt1)\n if pt1 != pt2: # se la linea non passa per il centro del cerchio\n lines.append([pt1, pt2]) # primo punto tangente e secondo punto perpendicolare \n pt1 = getPolarPointByPtAngle(circle1.center, angle, -1 * circle1.radius)\n pt2 = getPerpendicularPointOnInfinityLine(obj2[0], obj2[1], pt1)\n lines.append([pt1, pt2]) # primo punto tangente e secondo punto perpendicolare \n elif obj2Type == \"CIRCLE\" or obj2Type == \"ARC\":\n # linee tangenti ad un cerchio e perpendicolari ad un cerchio\n points = circle1.getTanPoints(circle2.center)\n for point in points:\n angle = getAngleBy2Pts(circle2.center, point)\n pt1 = getPolarPointByPtAngle(circle2.center, angle, circle2.radius) \n lines.append([point, pt1]) # primo punto tangente e secondo punto perpendicolare \n pt1 = getPolarPointByPtAngle(circle2.center, angle, -1 * circle2.radius) \n lines.append([point, pt1]) # primo punto tangente e secondo punto perpendicolare \n\n if obj1Type == \"ARC\" or obj2Type == \"ARC\":\n # cancello le linee che non abbiano un punto nell'arco\n for i in xrange(len(lines) - 1, -1, -1): \n toDelete1 = False \n toDelete2 = False \n if obj1Type == \"ARC\":\n toDelete1 = True \n for point in lines[i]:\n if obj1.isPtOnArc(point) == True:\n toDelete1 = False\n if obj2Type == \"ARC\":\n toDelete2 = True \n for point in lines[i]:\n if obj2.isPtOnArc(point) == True:\n toDelete2 = False\n \n if toDelete1 == True or toDelete2 == True:\n del lines[i] \n\n if obj2Type == \"LINE\":\n # cancello le linee che non abbiano un punto nel segmento\n for i in xrange(len(lines) - 1, -1, -1): \n line = lines[i]\n # primo punto tangente e secondo punto perpendicolare \n if isPtOnSegment(obj2[0], obj2[1], line[1]) == False:\n del lines[i]\n\n if len(lines) == 0:\n return None\n\n AvgList = []\n Avg = sys.float_info.max\n for line in lines:\n del AvgList[:] # svuoto la lista\n # primo punto tangente e secondo punto perpendicolare\n # tangente\n AvgList.append(getDistance(line[0], tanPt1))\n # perpendicolare\n AvgList.append(getDistance(line[1], perPt2))\n \n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n result = line \n \n return result\n\n\n#===============================================================================\n# lineFrom2PerPts\n#===============================================================================\ndef lineFrom2PerPts(geom1, pt1, geom2, pt2):\n '''\n Trova la linea perpendicolare a 2 oggetti: \n geometria di perpendicolarità (linea, arco o cerchio)\n punto di selezione geometria di perpendicolarità\n geometria di perpendicolarità (linea, arco o cerchio)\n punto di selezione geometria di perpendicolarità\n '''\n obj1 = whatGeomIs(pt1, geom1)\n obj2 = whatGeomIs(pt2, geom2)\n \n if (type(obj1) == list or type(obj1) == tuple):\n obj1Type = \"LINE\"\n else:\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle1 = QadCircle()\n circle1.set(obj1.center, obj1.radius)\n else:\n circle1 = QadCircle(obj1)\n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se é arco lo trasformo in cerchio\n circle2 = QadCircle()\n circle2.set(obj2.center, obj2.radius)\n else:\n circle2 = QadCircle(obj2)\n \n lines = []\n if obj1Type == \"LINE\":\n if obj2Type == \"LINE\":\n # linea perpendicolare a due linee\n return None\n else:\n # linea perpendicolare ad una linea e ad un cerchio\n ptPer1 = getPerpendicularPointOnInfinityLine(obj1[0], obj1[1], circle2.center)\n angle = getAngleBy2Pts(circle2.center, ptPer1)\n ptPer2 = getPolarPointByPtAngle(circle2.center, angle, circle2.radius)\n if ptPer1 != ptPer2: # se la linea non é tangente nel punto ptPer2\n lines.append([ptPer1, ptPer2]) \n ptPer2 = getPolarPointByPtAngle(circle2.center, angle, -1 * circle2.radius)\n if ptPer1 != ptPer2: # se la linea non é tangente nel punto ptPer2\n lines.append([ptPer1, ptPer2]) \n else:\n if obj2Type == \"LINE\":\n # linea perpendicolare ad un cerchio e ad una linea \n ptPer2 = getPerpendicularPointOnInfinityLine(obj2[0], obj2[1], circle1.center)\n angle = getAngleBy2Pts(circle1.center, ptPer2)\n ptPer1 = getPolarPointByPtAngle(circle1.center, angle, circle1.radius)\n if ptPer1 != ptPer2: # se la linea non é tangente nel punto ptPer1\n lines.append([ptPer1, ptPer2]) \n ptPer1 = getPolarPointByPtAngle(circle1.center, angle, -1 * circle1.radius)\n if ptPer1 != ptPer2: # se la linea non é tangente nel punto ptPer1\n lines.append([ptPer1, ptPer2]) \n else:\n perPoints1 = circle1.getIntersectionPointsWithInfinityLine(circle1.center, circle2.center)\n perPoints2 = circle2.getIntersectionPointsWithInfinityLine(circle1.center, circle2.center)\n for ptPer1 in perPoints1:\n for ptPer2 in perPoints2:\n if ptPer1 != ptPer2:\n lines.append([ptPer1, ptPer2]) \n\n if obj1Type == \"ARC\" or obj2Type == \"ARC\":\n # cancello le linee che non abbiano un punto nell'arco\n for i in xrange(len(lines) - 1, -1, -1): \n toDelete1 = False \n toDelete2 = False \n if obj1Type == \"ARC\":\n toDelete1 = True \n for point in lines[i]:\n if obj1.isPtOnArc(point) == True:\n toDelete1 = False\n if obj2Type == \"ARC\":\n toDelete2 = True \n for point in lines[i]:\n if obj2.isPtOnArc(point) == True:\n toDelete2 = False\n \n if toDelete1 == True or toDelete2 == True:\n del lines[i] \n\n if obj1Type == \"LINE\" or obj2Type == \"LINE\":\n # cancello le linee che non abbiano un punto nell'arco\n for i in xrange(len(lines) - 1, -1, -1): \n toDelete1 = False \n toDelete2 = False \n if obj1Type == \"LINE\":\n toDelete1 = True \n for point in lines[i]:\n if isPtOnSegment(obj1[0], obj1[1], point) == True:\n toDelete1 = False\n if obj2Type == \"LINE\":\n toDelete2 = True \n for point in lines[i]:\n if isPtOnSegment(obj2[0], obj2[1], point) == True:\n toDelete2 = False\n \n if toDelete1 == True or toDelete2 == True:\n del lines[i] \n \n if len(lines) == 0:\n return None\n\n AvgList = []\n Avg = sys.float_info.max\n for line in lines:\n del AvgList[:] # svuoto la lista\n AvgList.append(getDistance(line[0], pt1))\n AvgList.append(getDistance(line[1], pt2))\n \n currAvg = numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n result = line \n \n return result\n\n\n#===============================================================================\n# QadLinearObject class\n# Classe che definisce un oggetto lineare che può essere un segmento o un arco\n#===============================================================================\nclass QadLinearObject():\n\n \n def __init__(self, linearObject = None):\n # deflist = (<QgsPoint1> <QgsPoint2>) se si tratta di segmento\n # (<QadArc> <inverse>) se si tratta di arco\n # dove <inverse> = True significa che il punto iniziale dell'arco deve essere \n # considerato finale nel senso del verso dell'arco\n self.defList = None\n if linearObject is not None:\n self.set(linearObject)\n\n \n #============================================================================\n # isInitialized\n #============================================================================\n def isInitialized(self):\n \"\"\"\n la funzione ritorna True se l'oggetto é inizializzato.\n \"\"\"\n return False if self.defList is None else True\n\n\n #============================================================================\n # __eq__\n #============================================================================\n def __eq__(self, other):\n \"\"\"\n la funzione ritorna True se l'oggetto é uguale a other.\n \"\"\"\n if self.isInitialized() == False and other.isInitialized() == False:\n return True\n if self.isInitialized() and other.isInitialized():\n if self.isSegment() and other.isSegment():\n return self.getStartPt() == other.getStartPt() and self.getEndPt() == other.getEndPt() \n elif self.isArc() and other.isArc():\n return self.getArc() == other.getArc()\n else:\n return False\n else:\n return False \n \n \n #============================================================================\n # clear\n #============================================================================\n def clear(self):\n \"\"\"\n la funzione pulisce l'oggetto.\n \"\"\"\n if self.defList is not None:\n del self.defList[:]\n self.defList = None\n \n \n #============================================================================\n # isSegment\n #============================================================================\n def isSegment(self):\n \"\"\"\n la funzione ritorna True se l'oggetto é un segmento.\n \"\"\"\n if self.isInitialized() == False:\n return False\n return True if type(self.defList[0]) == QgsPoint else False\n\n\n #============================================================================\n # isArc\n #============================================================================\n def isArc(self):\n \"\"\"\n la funzione ritorna True se l'oggetto é un arco.\n \"\"\"\n if self.isInitialized() == False:\n return False\n return False if type(self.defList[0]) == QgsPoint else True\n\n\n #============================================================================\n # whatIs\n #============================================================================\n def whatIs(self):\n return \"LINE\" if self.isSegment() else \"ARC\"\n\n\n #============================================================================\n # isInverseArc\n #============================================================================\n def isInverseArc(self):\n \"\"\"\n la funzione ritorna True se il punto iniziale dell'arco é da considerare come finale\n nel verso impostato all'arco.\n \"\"\"\n if self.isArc() == False:\n return False\n return self.defList[1]\n \n \n #============================================================================\n # setInverseArc\n #============================================================================\n def setInverseArc(self, inverse):\n \"\"\"\n la funzione imposta il verso dell'arco.\n \"\"\"\n if self.isArc() == False:\n return False\n self.defList[1] = inverse\n\n \n #============================================================================\n # getArc\n #============================================================================\n def getArc(self):\n \"\"\"\n la funzione ritorna l'oggetto QadArc.\n \"\"\"\n if self.isArc() == False:\n return None\n return self.defList[0]\n\n \n #============================================================================\n # setArc\n #============================================================================\n def setArc(self, arc, inverse):\n \"\"\"\n la funzione ritorna l'oggetto arco.\n \"\"\"\n if self.isInitialized():\n del self.defList[:] # svuoto la lista\n self.defList = [QadArc(arc), inverse]\n\n \n #============================================================================\n # setSegment\n #============================================================================\n def setSegment(self, p1, p2):\n \"\"\"\n la funzione imposta il segmento.\n \"\"\"\n if self.isInitialized():\n del self.defList[:] # svuoto la lista\n self.defList = [QgsPoint(p1), QgsPoint(p2)]\n\n \n #============================================================================\n # set\n #============================================================================\n def set(self, linearObject):\n \"\"\"\n la funzione imposta l'oggetto come <linearObject>.\n \"\"\"\n if self.isInitialized():\n del self.defList[:] # svuoto la lista\n \n if type(linearObject) == list or type(linearObject) == tuple: # é una lista\n if type(linearObject[0]) == QgsPoint: # é un segmento\n self.defList = [QgsPoint(linearObject[0]), QgsPoint(linearObject[1])]\n else: # é un arco\n self.defList = [QadArc(linearObject[0]), linearObject[1]]\n else: # é un oggetto QadLinearObject\n if linearObject.isSegment():\n self.defList = [QgsPoint(linearObject.defList[0]), QgsPoint(linearObject.defList[1])]\n else:\n self.defList = [QadArc(linearObject.defList[0]), linearObject.defList[1]]\n \n \n #============================================================================\n # setByGeom\n #============================================================================\n def setByClosestSegmentOfGeom(self, pt, geom):\n \"\"\"\n la funzione imposta l'oggetto attraverso una geometria di cui si conosce un punto\n nelle vicinanze.\n \"\"\"\n if self.isInitialized():\n del self.defList[:] # svuoto la lista\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = closestSegmentWithContext(pt, geom)\n if dummy is None or dummy[2] is None:\n return False\n\n afterVertex = dummy[2]\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom = getSubGeomAtVertex(geom, afterVertex)[0]\n dummy = closestSegmentWithContext(pt, subGeom)\n afterVertex = dummy[2]\n points = subGeom.asPolyline()\n\n arcList = QadArcList()\n arcList.fromPoints(points)\n \n # verifico se il punto afterVertex fa parte di un arco\n arcInfo = arcList.arcAt(afterVertex)\n if arcInfo is not None:\n arc = arcInfo[0]\n startEndVertices = arcInfo[1]\n # verifico il verso\n if points[startEndVertices[0]] == arc.getStartPt():\n inverse = False\n else:\n inverse = True\n self.setArc(arc, inverse)\n else: \n pt1 = points[afterVertex - 1 ]\n pt2 = points[afterVertex]\n if pt1 != pt2: # solo se il punto iniziale é diverso da quello finale\n self.setSegment(pt1, pt2)\n \n return True\n \n\n #============================================================================\n # getStartPt\n #============================================================================\n def getStartPt(self):\n \"\"\"\n la funzione ritorna il punto iniziale dell'oggetto (ne alloca uno nuovo).\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n return QgsPoint(self.defList[0])\n else: # arco\n if self.isInverseArc():\n return self.defList[0].getEndPt()\n else:\n return self.defList[0].getStartPt()\n \n \n #============================================================================\n # setStartPt\n #============================================================================\n def setStartPt(self, pt):\n \"\"\"\n la funzione imposta il punto iniziale dell'oggetto.\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n return self.defList[0].set(pt.x(), pt.y())\n else: # arco\n if self.isInverseArc():\n return self.defList[0].setEndAngleByPt(pt)\n else:\n return self.defList[0].setStartAngleByPt(pt)\n \n \n #============================================================================\n # getEndPt\n #============================================================================\n def getEndPt(self):\n \"\"\"\n la funzione ritorna il punto finale dell'oggetto.\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n return self.defList[1]\n else: # arco\n if self.isInverseArc():\n return self.defList[0].getStartPt()\n else:\n return self.defList[0].getEndPt() \n \n \n #============================================================================\n # setEndPt\n #============================================================================\n def setEndPt(self, pt):\n \"\"\"\n la funzione imposta il punto finale dell'oggetto.\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n return self.defList[1].set(pt.x(), pt.y())\n else: # arco\n if self.isInverseArc():\n return self.defList[0].setStartAngleByPt(pt)\n else:\n return self.defList[0].setEndAngleByPt(pt)\n\n \n #============================================================================\n # getStartEndPts\n #============================================================================\n def getStartEndPts(self):\n \"\"\"\n la funzione ritorna il punto iniziale e finale dell'oggetto.\n \"\"\"\n return [self.getStartPt(), self.getEndPt()]\n\n \n #============================================================================\n # setStartEndPts\n #============================================================================\n def setStartEndPts(self, startPt, endPt):\n \"\"\"\n la funzione imposta il punto iniziale e finale dell'oggetto.\n \"\"\"\n self.setStartPt(startPt)\n self.setEndPt(endPt)\n\n \n #============================================================================\n # getTanDirectionOnStartPt\n #============================================================================\n def getTanDirectionOnStartPt(self):\n \"\"\"\n la funzione ritorna la direzione della tangente al punto iniziale dell'oggetto.\n \"\"\"\n if self.isSegment(): # segmento\n return getAngleBy2Pts(self.getStartPt(), self.getEndPt())\n else: # se é un arco\n arc = QadArc()\n if self.isInverseArc():\n return self.getArc().getTanDirectionOnEndPt() + math.pi\n else:\n return self.getArc().getTanDirectionOnStartPt()\n\n \n #============================================================================\n # getTanDirectionOnEndPt\n #============================================================================\n def getTanDirectionOnEndPt(self):\n \"\"\"\n la funzione ritorna la direzione della tangente al punto finale dell'oggetto.\n \"\"\"\n if self.isSegment(): # segmento\n return getAngleBy2Pts(self.getStartPt(), self.getEndPt())\n else: # se é un arco\n arc = QadArc()\n if self.isInverseArc():\n return self.getArc().getTanDirectionOnStartPt() + math.pi\n else:\n return self.getArc().getTanDirectionOnEndPt()\n \n \n #============================================================================\n # getMiddlePt\n #============================================================================\n def getMiddlePt(self):\n \"\"\"\n la funzione restituisce il punto medio della parte.\n \"\"\"\n if self.isInitialized() == False:\n return None \n if self.isSegment(): # segmento\n return getMiddlePoint(self.getStartPt(), self.getEndPt())\n else: # arco\n return self.getArc().getMiddlePt()\n\n\n #============================================================================\n # getTanDirectionOnMiddlePt\n #============================================================================\n def getTanDirectionOnMiddlePt(self):\n \"\"\"\n la funzione ritorna la direzione della tangente al punto medio dell'oggetto.\n \"\"\"\n if self.isSegment(): # segmento\n return getAngleBy2Pts(self.getStartPt(), self.getEndPt())\n else: # se é un arco\n arc = QadArc()\n middlePt = self.getMiddlePt()\n if self.isInverseArc():\n return self.getArc().getTanDirectionOnPt(middlePt) + math.pi\n else:\n return self.getArc().getTanDirectionOnPt(middlePt)\n\n \n #============================================================================\n # length\n #============================================================================\n def length(self):\n \"\"\"\n la funzione restituisce la lunghezza della parte.\n \"\"\"\n if self.isInitialized() == False:\n return None \n if self.isSegment(): # segmento\n return getDistance(self.getStartPt(), self.getEndPt())\n else: # arco\n return self.getArc().length()\n \n\n #============================================================================\n # move\n #============================================================================\n def move(self, offSetX, offSetY):\n \"\"\"\n la funzione sposta le parti secondo un offset X e uno Y\n \"\"\"\n if self.isInitialized():\n if self.isSegment(): # segmento\n self.defList[0].set(self.defList[0].x() + offSetX, self.defList[0].y() + offSetY)\n self.defList[1].set(self.defList[1].x() + offSetX, self.defList[1].y() + offSetY)\n else: # arco\n self.getArc().center.set(self.getArc().center.x() + offSetX, self.getArc().center.y() + offSetY)\n \n\n #============================================================================\n # lengthen_delta\n #============================================================================\n def lengthen_delta(self, move_startPt, delta):\n \"\"\"\n la funzione sposta il punto iniziale (se move_startPt = True) o finale (se move_startPt = False)\n di una distanza delta estendendo la parte lineare\n \"\"\"\n if self.isInitialized() == False:\n return False\n\n length = self.length()\n # lunghezza della parte + delta non può essere <= 0\n if length + delta <= 0:\n return False\n \n if self.isSegment(): # segmento\n if move_startPt == True:\n angle = getAngleBy2Pts(self.getEndPt(), self.getStartPt())\n self.setStartPt(getPolarPointByPtAngle(self.getStartPt(), angle, delta))\n else:\n angle = getAngleBy2Pts(self.getStartPt(), self.getEndPt())\n self.setEndPt(getPolarPointByPtAngle(self.getEndPt(), angle, delta))\n return True\n else: # arco\n # lunghezza arco + delta non può essere >= alla circonferenza del cerchio\n if length + delta >= 2 * math.pi * self.getArc().radius:\n return False\n # (2*pi) : (2*pi*r) = angle : delta \n angle = delta / self.getArc().radius\n \n if move_startPt == True:\n if self.isInverseArc():\n self.getArc().endAngle = self.getArc().endAngle + angle\n else:\n self.getArc().startAngle = self.getArc().startAngle - angle\n else:\n if self.isInverseArc():\n self.getArc().startAngle = self.getArc().startAngle - angle\n else:\n self.getArc().endAngle = self.getArc().endAngle + angle\n return True\n\n\n #============================================================================\n # lengthen_deltaAngle\n #============================================================================\n def lengthen_deltaAngle(self, move_startPt, delta):\n \"\"\"\n la funzione sposta il punto iniziale (se move_startPt = True) o finale (se move_startPt = False)\n dell'arco di un certo numero di gradi delta estendendo la parte lineare\n \"\"\"\n if self.isInitialized() == False:\n return False\n \n if self.isArc() == False: # se non è arco\n return False\n \n totalAngle = self.getArc().totalAngle()\n # angolo dell'arco + delta non può essere >= 2 * pi\n if totalAngle + delta >= 2 * math.pi:\n return False\n # angolo dell'arco + delta non può essere <= 0\n if totalAngle + delta <= 0:\n return False\n \n if move_startPt == True:\n if self.isInverseArc():\n self.getArc().endAngle = self.getArc().endAngle + delta\n else:\n self.getArc().startAngle = self.getArc().startAngle - delta\n else:\n if self.isInverseArc():\n self.getArc().startAngle = self.getArc().startAngle - delta\n else:\n self.getArc().endAngle = self.getArc().endAngle + delta\n return True\n\n\n #============================================================================\n # getIntersectionPtsWithLinearObject\n #============================================================================\n def getIntersectionPtsWithLinearObject(self, linearObject):\n \"\"\"\n la funzione calcola i punti di intersezione tra 2 oggetti lineari.\n Ritorna una lista di punti di intersezione\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n if linearObject.isSegment(): # segmento\n ptInt = getIntersectionPointOn2Segments(self.getStartPt(), self.getEndPt(), \\\n linearObject.getStartPt(), linearObject.getEndPt())\n if ptInt is not None: # se non sono parallele\n return [ptInt]\n else:\n return [] \n else: # arco\n return linearObject.getArc().getIntersectionPointsWithSegment(self.getStartPt(), self.getEndPt())\n else: # arco\n if linearObject.isSegment(): # segmento\n return self.getArc().getIntersectionPointsWithSegment(linearObject.getStartPt(), linearObject.getEndPt())\n else: # arco\n return self.getArc().getIntersectionPointsWithArc(linearObject.getArc())\n \n return []\n \n \n #============================================================================\n # getIntersectionPtsOnExtensionWithLinearObject\n #============================================================================\n def getIntersectionPtsOnExtensionWithLinearObject(self, linearObject):\n \"\"\"\n la funzione calcola i punti di intersezione tra le estensioni di 2 oggetti lineari.\n Un arco diventa un cerchio e un segmento diventa una linea infinita.\n Ritorna una lista di punti di intersezione\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n if linearObject.isSegment(): # segmento\n ptInt = getIntersectionPointOn2InfinityLines(self.getStartPt(), self.getEndPt(), \\\n linearObject.getStartPt(), linearObject.getEndPt())\n if ptInt is not None: # se non sono parallele\n return [ptInt]\n else:\n return [] \n else: # arco\n circle = QadCircle()\n circle.set(linearObject.getArc().center, linearObject.getArc().radius)\n return circle.getIntersectionPointsWithInfinityLine(self.getStartPt(), self.getEndPt())\n else: # arco\n if linearObject.isSegment(): # segmento\n circle = QadCircle()\n circle.set(self.getArc().center, self.getArc().radius)\n return circle.getIntersectionPointsWithInfinityLine(linearObject.getStartPt(), linearObject.getEndPt())\n else: # arco\n circle1 = QadCircle()\n circle1.set(self.getArc().center, self.getArc().radius)\n circle2 = QadCircle()\n circle2.set(linearObject.getArc().center, linearObject.getArc().radius)\n return circle1.getIntersectionPointsWithCircle(circle2)\n \n return []\n\n \n #============================================================================\n # getMinDistancePtsWithLinearObject\n #============================================================================\n def getMinDistancePtsWithLinearObject(self, linearObject):\n \"\"\"\n la funzione ritorna i punti di distanza minima e la distanza minima tra due parti\n (<punto di distanza minima su self><punto di distanza minima su linearObject><distanza minima>)\n \"\"\"\n if self.isInitialized() == False:\n return None\n if self.isSegment(): # segmento\n if linearObject.isSegment(): # segmento-segmento\n return getMinDistancePtsBetween2Segments(self.getStartPt(), self.getEndPt(), \\\n linearObject.getStartPt(), linearObject.getEndPt())\n else: # segmento-arco\n return getMinDistancePtsBetweenSegmentAndArc(self.getStartPt(), self.getEndPt(), \\\n linearObject.getArc()) \n else: # arco\n if linearObject.isSegment(): # arco-segmento\n return getMinDistancePtsBetweenSegmentAndArc(linearObject.getStartPt(), linearObject.getEndPt(), \\\n self.getArc())\n else: # arco-arco\n return getMinDistancePtsBetween2Arcs(self.getArc(), linearObject.getArc())\n\n \n #============================================================================\n # getDistanceFromStart\n #============================================================================\n def getDistanceFromStart(self, pt):\n \"\"\"\n la funzione restituisce la distanza di <pt> (che deve essere sull'oggetto o sua estensione)\n dal punto iniziale.\n \"\"\"\n if self.isInitialized() == False:\n return None\n \n dummy = QadLinearObject(self)\n dummy.setEndPt(pt)\n\n # se il punto é sull'estensione dalla parte del punto iniziale \n if self.containsPt(pt) == False and \\\n getDistance(self.getStartPt(), pt) < getDistance(self.getEndPt(), pt):\n return -dummy.length()\n \n return dummy.length()\n \n\n #============================================================================\n # getPointFromStart\n #============================================================================\n def getPointFromStart(self, distance):\n \"\"\"\n la funzione restituisce un punto della parte alla distanza <distance> (che deve essere sull'oggetto) dal punto iniziale.\n \"\"\"\n if distance < 0:\n return None\n l = self.length()\n if distance > l:\n return None\n \n if self.isSegment(): # segmento\n angle = getAngleBy2Pts(self.getStartPt(), self.getEndPt())\n return getPolarPointByPtAngle(self.getStartPt(), angle, distance)\n else: # arco\n # (2*pi) : (2*pi*r) = angle : delta \n angle = delta / self.getArc().radius\n \n if self.isInverseArc():\n angle = self.getArc().endAngle - angle\n else:\n angle = self.getArc().startAngle + angle\n \n return getPolarPointByPtAngle(self.getArc().center, angle, self.getArc().radius)\n \n return None\n\n\n #============================================================================\n # getPartsExternalToCircle\n #============================================================================\n def getPartsExternalToCircle(self, circle):\n \"\"\"\n la funzione usa un cerchio per dividere l'oggetto lineare.\n Le parti esterne al cerchio vengono restituite\n nell'ordine dal punto iniziale a quello finale dell'oggetto linear.\n \"\"\"\n if self.isInitialized() == False:\n return None\n result = QadLinearObjectList()\n\n startPt = self.getStartPt()\n endPt = self.getEndPt()\n \n if self.isSegment(): # segmento\n intPtList = circle.getIntersectionPointsWithSegment(startPt, endPt)\n else: # arco\n intPtList = self.getArc().getIntersectionPointsWithCircle(circle)\n \n intPtSortedList = []\n for pt in intPtList:\n # inserisco il punto ordinato per distanza dall'inizio di part\n distFromStart = self.getDistanceFromStart(pt)\n insertAt = 0\n for intPt in intPtSortedList:\n if intPt[1] < distFromStart:\n insertAt = insertAt + 1\n else:\n break \n intPtSortedList.insert(insertAt, [pt, distFromStart])\n \n del intPtList[:] # svuoto la lista\n for intPt in intPtSortedList:\n intPtList.append(intPt[0])\n \n startPtFromCenter = getDistance(circle.center, startPt) \n endPtFromCenter = getDistance(circle.center, endPt)\n intPtListLen = len(intPtList)\n if intPtListLen == 0: # se non ci sono punti di intersezione\n # se entrambi i punti terminali della parte sono esterni al cerchio\n if startPtFromCenter >= circle.radius and endPtFromCenter >= circle.radius:\n result.append(QadLinearObject(self)) \n elif intPtListLen == 1: # se c'é un solo punto di intersezione\n # se entrambi i punti terminali della parte sono esterni al cerchio\n if startPtFromCenter >= circle.radius and endPtFromCenter >= circle.radius:\n result.append(QadLinearObject(self)) \n # se il primo punto della parte é interno e il secondo esterno al cerchio\n elif startPtFromCenter < circle.radius and endPtFromCenter > circle.radius:\n newLinearobj = QadLinearObject(self)\n newLinearobj.setStartPt(intPtList[0]) \n result.append(newLinearobj) \n # se il primo punto della parte é esterno e il secondo interno al cerchio\n elif startPtFromCenter > circle.radius and endPtFromCenter < circle.radius:\n newLinearobj = QadLinearObject(self)\n newLinearobj.setEndPt(intPtList[0]) \n result.append(newLinearobj) \n else : # se ci sono due punti di intersezione\n # se il primo punto della parte é esterno al cerchio\n if startPtFromCenter > circle.radius:\n newLinearobj = QadLinearObject(self)\n newLinearobj.setEndPt(intPtList[0]) \n result.append(newLinearobj) \n # se il secondo punto della parte é esterno al cerchio\n if endPtFromCenter > circle.radius:\n newLinearobj = QadLinearObject(self)\n newLinearobj.setStartPt(intPtList[1]) \n result.append(newLinearobj) \n \n return result\n\n\n #============================================================================\n # reverse\n #============================================================================\n def reverse(self):\n \"\"\"\n la funzione rovescia il verso dell'oggetto lineare.\n \"\"\"\n if self.isInitialized() == False:\n return self \n if self.isSegment(): # segmento\n ptStart = QgsPoint(self.getStartPt())\n ptEnd = QgsPoint(self.getEndPt())\n self.setStartEndPts(ptEnd, ptStart)\n else: # arco\n self.setInverseArc(not self.isInverseArc())\n return self\n \n\n #============================================================================\n # containsPt\n #============================================================================\n def containsPt(self, pt):\n \"\"\"\n la funzione ritorna True se il punto si trova sull'oggetto lineare.\n \"\"\"\n if self.isInitialized() == False:\n return False \n if self.isSegment(): # segmento\n return isPtOnSegment(self.getStartPt(), self.getEndPt(), pt)\n else: # arco\n return self.getArc().isPtOnArc(pt)\n \n\n #============================================================================\n # join\n #============================================================================\n def join(self, linearObject):\n \"\"\"\n la funzione restituisce una lista QadLinearObjectList che contiene la polilinea\n generata dall'unione di questo oggetto lineare con <linearObject> se possibile\n altrimenti None.\n \"\"\"\n if self.getEndPt() == linearObject.getStartPt():\n result = QadLinearObjectList()\n result.append(QadLinearObject(self))\n result.append(QadLinearObject(linearObject))\n return result\n elif self.getStartPt() == linearObject.getEndPt():\n result = QadLinearObjectList()\n result.append(QadLinearObject(linearObject))\n result.append(QadLinearObject(self))\n return result\n else:\n return None\n\n \n #===============================================================================\n # asPolyline\n #===============================================================================\n def asPolyline(self, tolerance2ApproxCurve = None):\n \"\"\"\n la funzione ritorna una lista di punti che compone l'oggetto lineare.\n \"\"\"\n if self.isSegment(): # segmento\n result = [self.getStartPt(), self.getEndPt()]\n else: # arco\n result = self.getArc().asPolyline(tolerance2ApproxCurve)\n if self.isInverseArc(): # l'arco é in senso inverso\n result.reverse()\n \n return result\n\n\n #===============================================================================\n # transform\n #===============================================================================\n def transform(self, coordTransform):\n \"\"\"\n la funzione trasforma le coordinate dei punti che compone l'oggetto lineare.\n \"\"\"\n result = QadLinearObject(self)\n if result.isSegment(): # segmento\n result.setStartPt(coordTransform.transform(result.getStartPt()))\n result.setEndPt(coordTransform.transform(result.getEndPt()))\n else: # arco\n result.getArc().transform(coordTransform)\n \n return result\n \n\n #===============================================================================\n # transformFromCRSToCRS\n #===============================================================================\n def transformFromCRSToCRS(self, sourceCRS, destCRS):\n \"\"\"\n la funzione trasforma le coordinate dei punti che compone l'oggetto lineare.\n \"\"\"\n return transform(QgsCoordinateTransform(sourceCRS, destCRS))\n\n \n #============================================================================\n # leftOf\n #============================================================================\n def leftOf(self, point):\n \"\"\"\n la funzione ritorna una numero < 0 se il punto é alla sinistra della parte lineare\n \"\"\"\n if self.isSegment(): # segmento\n return leftOfLine(point, self.getStartPt(), self.getEndPt())\n else:\n if getDistance(self.getArc().center, point) - self.getArc().radius > 0:\n # esterno all'arco\n if self.isInverseArc(): # l'arco é in senso inverso\n return -1 # a sinistra\n else:\n return 1 # a destra\n else: \n # interno all'arco\n if self.isInverseArc(): # l'arco é in senso inverso\n return 1 # a destra\n else:\n return -1 # a sinistra\n\n\n #===============================================================================\n # closestPtWithContext\n #===============================================================================\n def closestPtWithContext(self, point, epsilon = 1.e-15):\n \"\"\"\n la funzione ritorna una lista con \n (<minima distanza al quadrato>\n <punto più vicino>\n <\"a sinistra di\" se il punto é alla sinista della parte (< 0 -> sinistra, > 0 -> destra)\n \"\"\"\n if self.isSegment(): # segmento\n startPt = self.getStartPt()\n endPt = self.getEndPt()\n result = sqrDistToSegment(point, startPt.x(), startPt.y(), endPt.x(), endPt.y(), epsilon)\n else: # arco\n result = sqrDistToArc(point, self.getArc())\n\n return result[0], result[1], self.leftOf(point)\n \n \n #===============================================================================\n # breakOnPt\n #===============================================================================\n def breakOnPt(self, point):\n \"\"\"\n la funzione spezza in due la parte nel punto <point>.\n Ritorna una lista di due parti: la prima parte (che può essere\n nulla se <point> conicide con il punto iniziale) e la seconda parte (che può essere\n nulla se <point> conicide con il punto finale)\n \"\"\"\n dummy = self.closestPtWithContext(point)\n nearestPt = dummy[1]\n if nearestPt is None:\n return [None, None]\n \n if ptNear(nearestPt, self.getStartPt()):\n part1 = None\n else:\n part1 = QadLinearObject(self)\n part1.setEndPt(nearestPt)\n\n if ptNear(nearestPt, self.getEndPt()):\n part2 = None\n else:\n part2 = QadLinearObject(self)\n part2.setStartPt(nearestPt)\n\n return [part1, part2]\n\n\n#===============================================================================\n# QadLinearObjectList class\n# Classe che definisce una lista di oggetti lineari che può essere una polilinea\n#===============================================================================\nclass QadLinearObjectList():\n\n \n def __init__(self, linearObjectList = None):\n self.defList = []\n # deflist = (<QadLinearObject1><QadLinearObject2>...)\n if linearObjectList is not None:\n self.set(linearObjectList)\n\n\n #============================================================================\n # whatIs\n #============================================================================\n def whatIs(self):\n return \"LINEAROBJS\"\n\n \n #============================================================================\n # set\n #============================================================================\n def set(self, linearObjectList):\n self.removeAll()\n for linearObject in linearObjectList.defList: \n self.append(linearObject)\n\n\n #============================================================================\n # append\n #============================================================================\n def append(self, linearObject):\n \"\"\"\n la funzione aggiunge un oggetto lineare in fondo alla lista.\n \"\"\"\n return self.defList.append(QadLinearObject(linearObject))\n\n\n #============================================================================\n # appendList\n #============================================================================\n def appendList(self, linearObjectList, start = None, qty = None):\n \"\"\"\n la funzione aggiunge una lista di oggetti lineari in fondo alla lista.\n Se start diverso da None significa numero della parte di <linearObjectList> da cui iniziare. \n Se <qty> diverso da None significa numero delle parti di <linearObjectList> da aggiungere,\n se = None significa fino alla fine di <linearObjectList>.\n \"\"\"\n if start is None:\n for linearObject in linearObjectList.defList:\n self.append(linearObject)\n else:\n i = start\n if qty is None:\n tot = linearObjectList.qty()\n else:\n tot = linearObjectList.qty() if qty > linearObjectList.qty() else qty\n\n while i < tot:\n self.append(linearObjectList.defList[i])\n i = i + 1\n\n \n #============================================================================\n # insert\n #============================================================================\n def insert(self, partAt, linearObject):\n \"\"\"\n la funzione aggiunge un oggetto lineare nella posizione i-esima della lista.\n \"\"\"\n if partAt >= self.qty():\n return self.append(linearObject)\n else: \n return self.defList.insert(partAt, QadLinearObject(linearObject))\n\n\n #============================================================================\n # insertList\n #============================================================================\n def insertList(self, i, linearObjectList):\n \"\"\"\n la funzione aggiunge una lista di oggetti lineari nella posizione i-esima della lista.\n \"\"\"\n ndx = i \n for linearObject in linearObjectList.defList:\n self.insert(ndx, linearObject)\n ndx = ndx + 1\n\n\n #============================================================================\n # insertPoint\n #============================================================================\n def insertPoint(self, partAt, pt):\n \"\"\"\n la funzione aggiunge un punto tra il punto iniziale e finale della parte i-esima della lista.\n se i < 0 aggiunge il punto all'inizio della polilinea\n se i >= qty() aggiunge il punto alla fine della polilinea\n \"\"\"\n if partAt < 0: # inserisco parte all'inizio\n self.insert(0, [pt, self.getStartPt()])\n elif partAt >= self.qty(): # inserisco parte in fondo\n self.append([self.getEndPt(), pt])\n else:\n linearObject = self.getLinearObjectAt(partAt)\n\n if linearObject.isArc():\n arc1 = QadArc()\n arc2 = QadArc()\n totalAngle = linearObject.getArc().totalAngle()\n inverseArc = linearObject.isInverseArc()\n if inverseArc:\n if arc1.fromStartEndPtsAngle(pt, linearObject.getArc().getEndPt(), totalAngle) == False:\n return\n if arc2.fromStartEndPtsAngle(linearObject.getArc().getStartPt(), pt, totalAngle) == False:\n return\n else:\n if arc1.fromStartEndPtsAngle(linearObject.getArc().getStartPt(), pt, totalAngle) == False:\n return\n if arc2.fromStartEndPtsAngle(pt, linearObject.getArc().getEndPt(), totalAngle) == False:\n return\n \n self.insert(partAt, [arc1, inverseArc])\n linearObject = self.getLinearObjectAt(partAt + 1)\n linearObject.setArc(arc2, inverseArc)\n else:\n self.insert(partAt, [linearObject.getStartPt(), pt])\n linearObject = self.getLinearObjectAt(partAt + 1)\n linearObject.set([pt, linearObject.getEndPt()])\n\n\n #============================================================================\n # movePoint\n #============================================================================\n def movePoint(self, vertexAt, pt):\n \"\"\"\n la funzione sposta un punto tra il punto iniziale e finale della parte i-esima della lista.\n se i < 0 aggiunge il punto all'inizio della polilinea\n se i >= qty() aggiunge il punto alla fine della polilinea\n \"\"\"\n prevLinearObject, nextLinearObject = self.getPrevNextLinearObjectsAtVertex(vertexAt)\n \n if prevLinearObject is not None:\n if prevLinearObject.isArc():\n if ptNear(prevLinearObject.getArc().getStartPt(), prevLinearObject.getEndPt()):\n # sposto il punto iniziale dell'arco\n if prevLinearObject.getArc().fromStartEndPtsAngle(pt, \\\n prevLinearObject.getArc().getEndPt(), \\\n prevLinearObject.getArc().totalAngle()) == False:\n return\n else:\n # sposto il punto finale dell'arco\n if prevLinearObject.getArc().fromStartEndPtsAngle(prevLinearObject.getArc().getStartPt(), \\\n pt, \\\n prevLinearObject.getArc().totalAngle()) == False:\n return\n else:\n prevLinearObject.setEndPt(pt)\n \n if nextLinearObject is not None:\n if nextLinearObject.isArc():\n if ptNear(nextLinearObject.getArc().getStartPt(), nextLinearObject.getStartPt()):\n # sposto il punto iniziale dell'arco\n if nextLinearObject.getArc().fromStartEndPtsAngle(pt, \\\n nextLinearObject.getArc().getEndPt(), \\\n nextLinearObject.getArc().totalAngle()) == False:\n return\n else:\n # sposto il punto finale dell'arco\n if nextLinearObject.getArc().fromStartEndPtsAngle(nextLinearObject.getArc().getStartPt(), \\\n pt, \\\n nextLinearObject.getArc().totalAngle()) == False:\n return\n else:\n nextLinearObject.setStartPt(pt)\n\n\n #============================================================================\n # remove\n #============================================================================\n def remove(self, i):\n \"\"\"\n la funzione cancella un oggetto lineare nella posizione i-esima della lista.\n \"\"\"\n del self.defList[i]\n\n \n #============================================================================\n # removeAll\n #============================================================================\n def removeAll(self):\n \"\"\"\n la funzione cancella gli oggetti della lista.\n \"\"\"\n del self.defList[:]\n\n\n #============================================================================\n # getLinearObjectAt\n #============================================================================\n def getLinearObjectAt(self, i):\n \"\"\"\n la funzione restituisce l'oggetto lineare alla posizione i-esima \n con numeri negativi parte dal fondo (es. -1 = ultima posizione)\n \"\"\"\n if self.qty() == 0 or i > self.qty() - 1:\n return None\n return self.defList[i]\n\n\n #============================================================================\n # getVertexPosAtPt\n #============================================================================\n def getVertexPosAtPt(self, pt):\n \"\"\"\n la funzione restituisce la posizione del vertice con coordinate <pt> (0-based),\n None se non trovato.\n \"\"\"\n vertexAt = 0\n for linearObject in self.defList:\n if ptNear(linearObject.getStartPt(), pt):\n return vertexAt\n vertexAt = vertexAt + 1\n if self.isClosed() == False: # se non é chiusa verifico ultimo vertice dell'ultima parte\n if ptNear(self.defList[-1].getEndPt(), pt):\n return vertexAt\n \n return None\n\n\n #============================================================================\n # getPrevNextLinearObjectsAtVertex\n #============================================================================\n def getPrevNextLinearObjectsAtVertex(self, vertexAt):\n \"\"\"\n la funzione restituisce l'oggetto lineare precedente e successivo al vertice vertexAt-esimo\n \"\"\"\n prevLinearObject = None\n nextLinearObject = None\n \n if vertexAt == 0: # primo vertice\n nextLinearObject = self.getLinearObjectAt(0) \n if self.isClosed():\n prevLinearObject = self.getLinearObjectAt(-1)\n elif vertexAt == self.qty(): # ultimo vertice\n prevLinearObject = self.getLinearObjectAt(-1) \n if self.isClosed():\n nextLinearObject = self.getLinearObjectAt(0)\n else:\n nextLinearObject = self.getLinearObjectAt(vertexAt)\n prevLinearObject = self.getLinearObjectAt(vertexAt - 1)\n\n return prevLinearObject, nextLinearObject\n\n\n #============================================================================\n # getPointAtVertex\n #============================================================================\n def getPointAtVertex(self, vertexAt):\n \"\"\"\n la funzione restituisce il punto del vertice vertexAt-esimo che compone la polilinea.\n \"\"\"\n if vertexAt == self.qty(): # ultimo vertice\n return self.getLinearObjectAt(-1).getEndPt() \n else:\n return self.getLinearObjectAt(vertexAt).getStartPt()\n\n\n #============================================================================\n # getNextPos\n #============================================================================\n def getNextPos(self, i):\n \"\"\"\n la funzione restituisce la posizione della parte successiva all' i-esima (0-based) \n \"\"\" \n if i == self.qty() - 1 or i == -1: # sono alla fine\n if self.isClosed(): # se é chiusa torno all'inizio\n return 0\n else:\n return None\n else:\n return i + 1\n\n\n #============================================================================\n # getPrevPos\n #============================================================================\n def getPrevPos(self, i):\n \"\"\"\n la funzione restituisce la posizione della parte precedente all' i-esima (0-based) \n \"\"\" \n if i == 0: # sono all'inizio\n if self.isClosed(): # se é chiusa torno alla fine\n return self.qty() - 1\n else:\n return None\n else:\n return i - 1\n\n\n #============================================================================\n # fromPolyline\n #============================================================================\n def fromPolyline(self, points):\n \"\"\"\n la funzione inizializza una lista di segmenti e archi (QadLinearObject) \n che compone la polilinea.\n Se una parte ha punto iniziale e finale coincidenti (es. 2 vertici consecutivi \n che si sovrappongono o arco con angolo totale = 0 oppure = 360)\n la parte viene rimossa dalla lista.\n \"\"\"\n pointsLen = len(points)\n arcList = QadArcList()\n arcList.fromPoints(points)\n \n # creo una lista dei segmenti e archi che formano la polilinea\n del self.defList[:] # svuoto la lista\n \n i = 0\n while i < pointsLen - 1: \n # verifico il punto i + 1 fa parte di un arco\n arcInfo = arcList.arcAt(i + 1)\n if arcInfo is not None:\n arc = arcInfo[0]\n if arc.getStartPt() != arc.getEndPt():\n # se i punti sono così vicini da essere considerati uguali \n inverse = False if ptNear(points[i], arc.getStartPt()) else True\n self.append([arc, inverse])\n startEndVertices = arcInfo[1]\n endVertex = startEndVertices[1]\n i = endVertex\n else:\n pt1 = points[i]\n pt2 = points[i + 1]\n self.append([pt1, pt2])\n i = i + 1\n \n return\n \n\n #===============================================================================\n # asPolyline\n #===============================================================================\n def asPolyline(self, tolerance2ApproxCurve = None):\n \"\"\"\n la funzione ritorna una lista di punti che compone la polilinea formata da una lista di\n parti di segmenti e archi (QadLinearObject) consecutive.\n \"\"\"\n result = []\n firstPt = True\n for linearObject in self.defList:\n pts = linearObject.asPolyline(tolerance2ApproxCurve)\n ptsLen = len(pts)\n if firstPt:\n i = 0\n firstPt = False\n else:\n i = 1\n while i < ptsLen:\n result.append(pts[i])\n i = i + 1\n \n return result\n \n\n #===============================================================================\n # reverse\n #===============================================================================\n def reverse(self):\n \"\"\"\n la funzione rovescia il verso di una lista di\n parti di segmenti e archi (QadLinearObject) consecutive.\n \"\"\"\n self.defList.reverse()\n for linearObject in self.defList:\n linearObject.reverse()\n return \n \n\n #============================================================================\n # length\n #============================================================================\n def length(self):\n \"\"\"\n la funzione restituisce la somma delle lunghezze della parti.\n \"\"\"\n tot = 0\n for linearObject in self.defList:\n tot = tot + linearObject.length()\n return tot\n\n\n #============================================================================\n # move\n #============================================================================\n def move(self, offSetX, offSetY):\n \"\"\"\n la funzione sposta le parti secondo un offset X e uno Y\n \"\"\"\n for linearObject in self.defList:\n linearObject.move(offSetX, offSetY)\n\n\n #============================================================================\n # qty\n #============================================================================\n def qty(self):\n \"\"\"\n la funzione restituisce la quantità di parti nella lista.\n \"\"\"\n return len(self.defList)\n \n\n #============================================================================\n # getStartPt\n #============================================================================\n def getStartPt(self):\n \"\"\"\n la funzione restituisce il punto iniziale della polilinea.\n \"\"\"\n linearObject = self.getLinearObjectAt(0) # primo oggetto lineare\n return None if linearObject is None else linearObject.getStartPt()\n\n\n #============================================================================\n # getEndPt\n #============================================================================\n def getEndPt(self):\n \"\"\"\n la funzione restituisce il punto finale della polilinea.\n \"\"\"\n linearObject = self.getLinearObjectAt(-1) # ultimo oggetto lineare\n return None if linearObject is None else linearObject.getEndPt()\n\n\n #============================================================================\n # getCentroid\n #============================================================================\n def getCentroid(self, tolerance2ApproxCurve = None):\n \"\"\"\n la funzione restituisce il punto centroide di una polilinea chiusa.\n \"\"\"\n if self.isClosed(): # verifico se polilinea chiusa\n ptList = self.asPolyline(tolerance2ApproxCurve)\n g = QgsGeometry.fromPolygon([ptList])\n if g is not None: \n return g.centroid().asPoint()\n\n return None\n\n\n #============================================================================\n # isClosed\n #============================================================================\n def isClosed(self):\n \"\"\"\n la funzione restituisce True se la polilinea (lista di parti segmenti-archi) é chiusa.\n \"\"\"\n if len(self.defList) == 0:\n return False\n else:\n return True if ptNear(self.getStartPt(), self.getEndPt()) else False\n\n\n #============================================================================\n # setClose\n #============================================================================\n def setClose(self, toClose = True):\n \"\"\"\n la funzione chiude o apre la polilinea (lista di parti segmenti-archi).\n \"\"\"\n if toClose: # da chiudere\n if self.isClosed() == False:\n linearObject = self.getLinearObjectAt(-1)\n if linearObject.isArc(): # se é un arco\n arc = QadArc()\n if linearObject.isInverseArc():\n if arc.fromStartEndPtsTan(linearObject.getArc().getStartPt(), \\\n self.getStartPt(), \\\n linearObject.getArc().getTanDirectionOnStartPt() + math.pi) == False:\n return\n else:\n if arc.fromStartEndPtsTan(linearObject.getArc().getEndPt(), \\\n self.getStartPt(), \\\n linearObject.getArc().getTanDirectionOnEndPt()) == False:\n return\n \n newLinearObject = QadLinearObject()\n newLinearObject.setArc(arc, linearObject.isInverseArc())\n self.append(newLinearObject)\n else: # non é un arco\n if self.qty() > 1:\n self.append([self.getEndPt(), self.getStartPt()]) \n else: # da aprire\n if self.isClosed() == True:\n if self.qty() > 1:\n self.remove(-1)\n\n\n #============================================================================\n # curve\n #============================================================================\n def curve(self, toCurve = True):\n \"\"\"\n se toCurve = True:\n la funzione curva ogni segmento per adattarlo alla polilinea (lista di parti segmenti-archi)\n facendo passare la nuova polilinea per i vertici.\n se toCurve = False:\n la funzione trasforma in segmento retto ogni arco della polilinea (lista di parti segmenti-archi).\n \"\"\"\n if toCurve == False:\n if self.getCircle() is not None: # se é un cerchio\n return\n \n for linearObject in self.defList:\n if linearObject.isArc():\n linearObject.set([linearObject.getStartPt(), linearObject.getEndPt()])\n return\n \n tot = self.qty()\n if tot < 2:\n return\n isClosed = self.isClosed()\n if isClosed:\n if self.getCircle() is not None: # se é un cerchio\n return\n\n newLinearObjectList = QadLinearObjectList()\n\n # primo oggetto lineare\n current = self.getLinearObjectAt(0) \n prev = None \n tanDirectionOnStartPt = None\n if isClosed:\n prev = self.getLinearObjectAt(-1)\n arc = QadArc()\n if arc.fromStartSecondEndPts(prev.getStartPt(), current.getStartPt(), current.getEndPt()):\n if ptNear(prev.getStartPt(), arc.getStartPt()): # arco non é inverso \n arc.setStartAngleByPt(current.getStartPt())\n tanDirectionOnStartPt = arc.getTanDirectionOnStartPt()\n else: # arco é inverso\n arc.setEndAngleByPt(current.getStartPt())\n tanDirectionOnStartPt = arc.getTanDirectionOnEndPt() + math.pi\n \n next = self.getLinearObjectAt(1)\n newLinearObjectList.defList.extend(getCurveLinearObjects(tanDirectionOnStartPt, prev, current, next))\n \n i = 1\n while i < tot - 1:\n tanDirectionOnStartPt = newLinearObjectList.getLinearObjectAt(-1).getTanDirectionOnEndPt()\n prev = current\n current = next \n next = self.getLinearObjectAt(i + 1)\n newLinearObjectList.defList.extend(getCurveLinearObjects(tanDirectionOnStartPt, prev, current, next))\n i = i + 1\n\n # ultimo oggetto lineare\n tanDirectionOnStartPt = newLinearObjectList.getLinearObjectAt(-1).getTanDirectionOnEndPt()\n prev = current\n current = next \n next = self.getLinearObjectAt(0) if isClosed else None\n newLinearObjectList.defList.extend(getCurveLinearObjects(tanDirectionOnStartPt, prev, current, next))\n \n self.set(newLinearObjectList) \n\n\n #============================================================================\n # fillet\n #============================================================================\n def fillet(self, radius):\n \"\"\"\n la funzione raccorda ogni segmento al successivo con un raggio di curvatura noto,\n la nuova polilinea avrà i vertici cambiati.\n \"\"\"\n if radius <= 0:\n return\n newLinearObjectList = QadLinearObjectList()\n\n part = self.getLinearObjectAt(0)\n i = 1\n tot = self.qty()\n while i <= tot - 1:\n nextPart = self.getLinearObjectAt(i)\n if part.isSegment() and nextPart.isSegment():\n # Ritorna una lista di 3 elementi (None in caso di errore): \n # - una linea che sostituisce <line1>, se = None <line1> va rimossa\n # - un arco, se = None non c'é arco di raccordo tra le due linee\n # - una linea che sostituisce <line2>, se = None <line2> va rimossa\n res = offsetBridgeTheGapBetweenLines(part, nextPart, radius, 1)\n if res is None:\n return\n if res[0] is not None:\n part = res[0]\n newLinearObjectList.append(part)\n if res[1] is not None:\n part = res[1]\n newLinearObjectList.append(part)\n if res[2] is not None:\n part = res[2]\n else:\n # offSetSide = \"left\" or \"right\"\n res = fillet2Parts_offset(part, nextPart, offSetSide, radius)\n i = i + 1\n\n if self.isClosed():\n nextPart = newLinearObjectList.getLinearObjectAt(0)\n if part.isSegment() and nextPart.isSegment():\n # Ritorna una lista di 3 elementi (None in caso di errore): \n # - una linea che sostituisce <line1>, se = None <line1> va rimossa\n # - un arco, se = None non c'é arco di raccordo tra le due linee\n # - una linea che sostituisce <line2>, se = None <line2> va rimossa\n res = offsetBridgeTheGapBetweenLines(part, nextPart, radius, 1)\n if res is None:\n return\n if res[0] is not None:\n part = res[0]\n newLinearObjectList.append(part)\n if res[1] is not None:\n part = res[1]\n newLinearObjectList.append(part)\n if res[2] is not None:\n part = res[2]\n self.remove(0) \n else:\n newLinearObjectList.append(part) \n \n self.set(newLinearObjectList) \n \n\n #============================================================================\n # getCircle\n #============================================================================\n def getCircle(self):\n \"\"\"\n la funzione ritorna l'oggetto cerchio.\n \"\"\"\n points = self.asPolyline() # vettore di punti\n circle = QadCircle()\n return circle if circle.fromPolyline(points, 0) is not None else None\n\n\n #============================================================================\n # getDistanceFromStart\n #============================================================================\n def getDistanceFromStart(self, pt):\n \"\"\"\n la funzione restituisce la distanza di <pt> (che deve essere sull'oggetto) dal punto iniziale.\n Da usarsi solo se le parti rappresentano una polilinea.\n \"\"\"\n tot = 0 \n for linearObject in self.defList:\n if linearObject.containsPt(pt) == True:\n return tot + linearObject.getDistanceFromStart(pt)\n else:\n tot = tot + linearObject.length()\n \n return -1\n\n\n #============================================================================\n # getPointFromStart\n #============================================================================\n def getPointFromStart(self, distance):\n \"\"\"\n la funzione restituisce un punto della polilinea alla distanza <distance> (che deve essere sull'oggetto) dal punto iniziale.\n Da usarsi solo se le parti rappresentano una polilinea.\n \"\"\"\n if distance < 0:\n return None\n d = distance\n for linearObject in self.defList:\n l = linearObject.length()\n if d > l:\n d = d - l\n else:\n return linearObject.getPointFromStart(d)\n\n return None\n\n\n #============================================================================\n # getLinearObjectNdxFromStart\n #============================================================================\n def getLinearObjectNdxFromStart(self, distance):\n \"\"\"\n la funzione restituisce il numero della parte lineare (0-index) in cui termina la distanza dal punto iniziale della polilinea.\n Da usarsi solo se le parti rappresentano una polilinea.\n \"\"\"\n if distance < 0:\n return None\n d = distance\n n = 0\n for linearObject in self.defList:\n l = linearObject.length()\n if d > l:\n return n\n else:\n n = n +1\n\n return None\n\n\n #============================================================================\n # lengthen_delta\n #============================================================================\n def lengthen_delta(self, move_startPt, delta):\n \"\"\"\n la funzione sposta il punto iniziale (se move_startPt = True) o finale (se move_startPt = False)\n di una distanza delta allungando (se delta > 0) o accorciando (se delta < 0) la polilinea\n \"\"\"\n length = self.length()\n # lunghezza polilinea + delta non può essere <= 0\n if length + delta <= 0: \n return False\n \n if move_startPt == False:\n # dal punto finale\n if delta >= 0: # allungo la polilinea\n # ultima parte\n return self.getLinearObjectAt(-1).lengthen_delta(False, delta)\n else: # accorcio la polilinea\n # cerco la parte in cui finirebbe la polilinea accorciata\n nPart = 0\n d = length + delta\n for linearObject in self.defList:\n l = linearObject.length()\n if d > l:\n d = d - l\n nPart = nPart + 1\n else:\n if linearObject.lengthen_delta(False, -(l - d)) == False:\n return False\n # se non è l'ultima parte\n if nPart+1 < len(self.defList):\n # cancello le parti successive a nPart\n del self.defList[nPart+1 :]\n break\n else: # dal punto iniziale\n self.reverse()\n res = self.lengthen_delta(False, delta)\n self.reverse()\n return res \n\n\n #============================================================================\n # lengthen_deltaAngle\n #============================================================================\n def lengthen_deltaAngle(self, move_startPt, delta):\n \"\"\"\n la funzione sposta il punto iniziale del primo arco (se move_startPt = True) o \n punto finale dell'ultimo arco (se move_startPt = False)\n di un certo numero di gradi delta allungando (se delta > 0) o accorciando (se delta < 0) la polilinea\n \"\"\"\n if move_startPt == False:\n # dal punto finale\n return self.getLinearObjectAt(-1).lengthen_deltaAngle(False, delta)\n else:\n # dal punto iniziale\n return self.getLinearObjectAt(0).lengthen_deltaAngle(True, delta)\n\n\n #============================================================================\n # asQgsFeatureList\n #============================================================================\n def asQgsFeatureList(self, polylineMode):\n \"\"\"\n la funzione restituisce una lista di feature.\n Se polylineMode = True allora la lista degli oggetti lineari sarà considerata un'unica polilinea\n \"\"\"\n fList = []\n if polylineMode == False:\n for linearObject in self.defList:\n f = QgsFeature()\n f.setGeometry(QgsGeometry.fromPolyline(linearObject.asPolyline()))\n fList.append(f)\n else:\n f = QgsFeature()\n f.setGeometry(QgsGeometry.fromPolyline(self.asPolyline()))\n fList.append(f)\n \n return fList\n\n\n #============================================================================\n # appendToTempQgsVectorLayer\n #============================================================================\n def appendToTempQgsVectorLayer(self, vectorLayer, polylineMode, updateExtents = True):\n \"\"\"\n la funzione inserisce gli oggetti lineari in lista in un QgsVectorLayer temporaneo già creato.\n Se polylineMode = True allora la lista degli oggetti lineari sarà considerata un'unica polilinea\n Ritorna la lista dei corrispettivi id di feature oppure None in caso di errore\n \"\"\"\n fList = self.asQgsFeatureList(polylineMode)\n \n idList = []\n result = True\n if vectorLayer.startEditing() == False:\n return None\n \n vectorLayer.beginEditCommand(\"Feature added\")\n \n for f in fList:\n if vectorLayer.addFeature(f):\n idList.append(f.id())\n else:\n result = False\n break\n\n if result == True:\n vectorLayer.endEditCommand();\n if updateExtents:\n vectorLayer.updateExtents()\n return idList\n else:\n vectorLayer.destroyEditCommand()\n return None\n\n\n #===============================================================================\n # getIntersectionPtsWithLinearObject\n #===============================================================================\n def getIntersectionPtsWithLinearObject(self, part, orderByStartPtOfPart = False):\n \"\"\"\n la funzione restituisce diverse liste:\n - la prima é una lista di punti di intersezione tra la parte <part> e\n la lista di parti ordinata per distanza dal punto iniziale di <part> se\n <orderByStartPtOfPart> = True altrimenti ordinata per distanza dal punto iniziale\n della lista di parti.\n - la seconda é una lista che contiene, rispettivamente per ogni punto di intersezione,\n il numero della parte (0-based) della lista di parti in cui si trova quel punto.\n - la terza é una lista che contiene, rispettivamente per ogni punto di intersezione,\n la distanza dal punto iniziale di <part> o dal punto iniziale della lista di parti\n (vedi <orderByStartPtOfPart>)\n <part>: un segmento o arco \n \"\"\" \n intPtSortedList = [] # lista di ((punto, distanza dall'inizio della parte) ...)\n partNumber = -1\n if orderByStartPtOfPart == False:\n distFromStartPrevParts = 0\n \n # per ogni parte della lista\n for part2 in self.defList:\n partNumber = partNumber + 1\n partialIntPtList = part.getIntersectionPtsWithLinearObject(part2)\n for partialIntPt in partialIntPtList:\n # escludo i punti che sono già in intPtSortedList\n found = False\n for intPt in intPtSortedList:\n if ptNear(intPt[0], partialIntPt):\n found = True\n break\n \n if found == False:\n if orderByStartPtOfPart:\n # inserisco il punto ordinato per distanza dall'inizio di part\n distFromStart = part.getDistanceFromStart(partialIntPt)\n else:\n distFromStart = distFromStartPrevParts + part2.getDistanceFromStart(partialIntPt)\n \n insertAt = 0\n for intPt in intPtSortedList:\n if intPt[1] < distFromStart:\n insertAt = insertAt + 1\n else:\n break \n intPtSortedList.insert(insertAt, [partialIntPt, distFromStart, partNumber])\n \n if orderByStartPtOfPart == False:\n distFromStartPrevParts = distFromStartPrevParts + part2.length()\n \n resultIntPt = []\n resultPartNumber = []\n resultDistanceFromStart = []\n for intPt in intPtSortedList:\n resultIntPt.append(intPt[0])\n resultPartNumber.append(intPt[2])\n resultDistanceFromStart.append(intPt[1])\n \n return resultIntPt, resultPartNumber, resultDistanceFromStart\n\n\n #===============================================================================\n # getIntersectionPtsWithLinearObjectlist\n #===============================================================================\n def getIntersectionPtsWithLinearObjectList(self, partList):\n \"\"\"\n la funzione restituisce diverse liste:\n - la prima é una lista di punti di intersezione tra le 2 liste di parti\n ordinata per distanza dal punto iniziale della lista.\n - la seconda é una lista che contiene, rispettivamente per ogni punto di intersezione,\n il numero della parte (0-based) della lista di parti in cui si trova quel punto.\n - la terza é una lista che contiene, rispettivamente per ogni punto di intersezione,\n la distanza dal punto iniziale della lista.\n <partList>: lista di parti \n \"\"\"\n resultIntPt = []\n resultPartNumber = []\n resultDistanceFromStart = []\n \n # per ogni parte della lista\n for part in self.defList:\n # lista di punti di intersezione ordinata per distanza dal punto iniziale di <part>\n partialResult = partList.getIntersectionPtsWithLinearObject(part, True)\n resultIntPt.extend(partialResult[0])\n resultPartNumber.extend(partialResult[2])\n resultDistanceFromStart.extend(partialResult[1])\n \n return resultIntPt, resultPartNumber, resultDistanceFromStart\n\n\n #============================================================================\n # join\n #============================================================================\n def join(self, linearObjectListToJoinTo, toleranceDist = TOLERANCE, mode = 1):\n \"\"\"\n la funzione unisce la polilinea con un'altra polilinea secondo la modalità <mode>.\n In caso di successo ritorna True altrimenti False.\n <linearObjectListToJoinTo> = polilinea con cui unirsi\n <toleranceDist> = distanza di tolleranza perché 2 punti siano considerati coincidenti \n <mode> = Imposta il metodo di unione (usato se toleranceDist > 0):\n 1 -> Estendi; Consente di unire polilinee selezionate estendendo o tagliando \n i segmenti nei punti finali più vicini.\n 2 -> Aggiungi; Consente di unire polilinee selezionate aggiungendo un segmento \n retto tra i punti finali più vicini.\n 3 -> Entrambi;Consente di unire polilinee selezionate estendendo o tagliando, se possibile.\n In caso contrario, consente di unire polilinee selezionate aggiungendo \n un segmento retto tra i punti finali più vicini. \n \"\"\"\n myToleranceDist = TOLERANCE if toleranceDist == 0 else toleranceDist\n # cerco il punto più vicino al punto iniziale della polilinea\n ptToJoin = self.getStartPt()\n isStartPt = True\n minDist = sys.float_info.max\n # considero il punto iniziale della polilinea a cui unirsi\n if linearObjectListToJoinTo.getStartPt() is None: # test\n fermati = True\n dist = getDistance(ptToJoin, linearObjectListToJoinTo.getStartPt())\n if dist < minDist:\n isStartPtToJoinTo = True\n minDist = dist\n # considero il punto finale della polilinea a cui unirsi\n dist = getDistance(ptToJoin, linearObjectListToJoinTo.getEndPt())\n if dist < minDist:\n isStartPtToJoinTo = False\n minDist = dist\n\n # cerco il punto più vicino al punto finale della polilinea\n ptToJoin = self.getEndPt()\n # considero il punto iniziale della polilinea a cui unirsi\n dist = getDistance(ptToJoin, linearObjectListToJoinTo.getStartPt())\n if dist < minDist:\n isStartPt = False\n isStartPtToJoinTo = True\n minDist = dist\n # considero il punto finale della polilinea a cui unirsi\n dist = getDistance(ptToJoin, linearObjectListToJoinTo.getEndPt())\n if dist < minDist:\n isStartPt = False\n isStartPtToJoinTo = False\n minDist = dist\n\n if minDist <= myToleranceDist: # trovato un punto\n # se il punto iniziale della polilinea da unire é uguale a quello iniziale della polilinea a cui unirsi\n if isStartPt == True and isStartPtToJoinTo == True: \n part1 = qad_utils.QadLinearObject(self.getLinearObjectAt(0))\n part1.reverse()\n part2 = qad_utils.QadLinearObject(linearObjectListToJoinTo.getLinearObjectAt(0))\n part2.reverse()\n \n res = joinEndPtsLinearParts(part1, part2, mode)\n if res is not None:\n # elimino la prima parte\n self.remove(0)\n res.reverse()\n self.insertList(0, res)\n \n # aggiungo le parti di <linearObjectListToJoinTo> tranne la prima\n i = 1\n tot = linearObjectListToJoinTo.qty()\n while i < tot:\n self.insert(0, linearObjectListToJoinTo.getLinearObjectAt(i).reverse())\n i = i + 1\n return True\n \n # se il punto iniziale della polilinea da unire é uguale a quello finale della polilinea a cui unirsi\n elif isStartPt == True and isStartPtToJoinTo == False:\n part1 = qad_utils.QadLinearObject(self.getLinearObjectAt(0))\n part1.reverse()\n part2 = linearObjectListToJoinTo.getLinearObjectAt(-1)\n \n res = joinEndPtsLinearParts(part1, part2, mode)\n if res is not None:\n # elimino la prima parte\n self.remove(0)\n res.reverse()\n self.insertList(0, res)\n \n # aggiungo le parti di <linearObjectListToJoinTo> tranne l'ultima\n i = linearObjectListToJoinTo.qty() - 2\n while i >= 0:\n self.insert(0, linearObjectListToJoinTo.getLinearObjectAt(i))\n i = i - 1\n return True\n\n # se il punto finale della polilinea da unire é uguale a quello iniziale della polilinea a cui unirsi\n elif isStartPt == False and isStartPtToJoinTo == True:\n part1 = self.getLinearObjectAt(-1)\n part2 = qad_utils.QadLinearObject(linearObjectListToJoinTo.getLinearObjectAt(0))\n part2.reverse()\n \n res = joinEndPtsLinearParts(part1, part2, mode)\n if res is not None: \n # elimino l'ultima parte\n self.remove(-1)\n self.appendList(res)\n\n # aggiungo le parti di <linearObjectListToJoinTo> tranne la prima\n i = 1\n tot = linearObjectListToJoinTo.qty()\n while i < tot:\n self.append(linearObjectListToJoinTo.getLinearObjectAt(i))\n i = i + 1\n return True\n \n # se il punto finale della polilinea da unire é uguale a quello finale della polilinea a cui unirsi \n elif isStartPt == False and isStartPtToJoinTo == False:\n part1 = self.getLinearObjectAt(-1)\n part2 = linearObjectListToJoinTo.getLinearObjectAt(-1)\n \n res = joinEndPtsLinearParts(part1, part2, mode)\n if res is not None: \n # elimino l'ultima parte\n self.remove(-1)\n self.appendList(res)\n\n # aggiungo le parti di <linearObjectListToJoinTo> tranne l'ultima\n i = linearObjectListToJoinTo.qty() - 2\n while i >= 0:\n self.append(linearObjectListToJoinTo.getLinearObjectAt(i).reverse())\n i = i - 1\n return True\n\n return False\n \n\n #============================================================================\n # selfJoin\n #============================================================================\n def selfJoin(self, epsg):\n \"\"\"\n la funzione restituisce una lista QadLinearObjectList che contiene le polilinee\n generate dall'unione degli oggetti lineari (lista di parti segmenti-archi).\n <epsg> = the authority identifier for this srs \n \"\"\"\n # creo un layer temporaneo in memoria\n vectorLayer = QgsVectorLayer(\"LineString?crs=%s&index=yes\" % epsg, \"QAD_SelfJoinLines\", \"memory\")\n provider = vectorLayer.dataProvider()\n \n # unisco le parti nella lista di self\n # inserisco nel layer i vari oggetti lineari\n idList = self.appendToTempQgsVectorLayer(vectorLayer, False)\n if idList is None:\n return []\n if provider.capabilities() & QgsVectorDataProvider.CreateSpatialIndex:\n provider.createSpatialIndex()\n \n vectorLayer.beginEditCommand(\"selfJoin\") \n \n for featureIdToJoin in idList:\n # featureIdToJoin, vectorLayer, tolerance2ApproxCurve, tomyToleranceDist \n joinFeatureInVectorLayer(featureIdToJoin, vectorLayer, QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))) \n \n vectorLayer.endEditCommand()\n vectorLayer.commitChanges()\n \n result = []\n feature = QgsFeature()\n \n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in vectorLayer.getFeatures(getFeatureRequest([], True, None, False)): \n linearObjectList = QadLinearObjectList()\n linearObjectList.fromPolyline(feature.geometry().asPolyline())\n result.append(linearObjectList)\n \n return result \n \n #===============================================================================\n # transform\n #===============================================================================\n def transform(self, coordTransform):\n \"\"\"\n la funzione restituisce una nuova lista di parti con le coordinate trasformate.\n \"\"\"\n result = QadLinearObjectList()\n for linearObject in self.defList:\n result.append(linearObject.transform(coordTransform))\n return result\n \n\n #===============================================================================\n # transformFromCRSToCRS\n #===============================================================================\n def transformFromCRSToCRS(self, sourceCRS, destCRS):\n \"\"\"\n la funzione trasforma le coordinate dei punti che compone l'oggetto lineare.\n \"\"\"\n return self.transform(QgsCoordinateTransform(sourceCRS, destCRS))\n \n \n #============================================================================\n # containsPt\n #============================================================================\n def containsPt(self, pt, startAt = 0):\n \"\"\"\n la funzione ritorna la posizione della parte che contiene il punto oppure -1.\n Il controllo inizia dalla parte <startAt> (0-based)\n \"\"\"\n tot = len(self.defList)\n if startAt < 0 or startAt >= tot:\n return -1\n i = startAt \n while i < tot:\n linearObject = self.defList[i]\n if linearObject.containsPt(pt):\n return i\n i = i + 1\n return -1\n\n\n #===============================================================================\n # closestPartWithContext\n #===============================================================================\n def closestPartWithContext(self, pt, epsilon = 1.e-15):\n \"\"\"\n la funzione ritorna una lista con \n (<minima distanza al quadrato>\n <punto più vicino>\n <indice della parte più vicina> \n <\"a sinistra di\" se il punto é alla sinista della parte (< 0 -> sinistra, > 0 -> destra)\n \"\"\"\n minDistPoint = QgsPoint()\n closestPartIndex = 0\n sqrDist = sys.float_info.max\n leftOf = None\n index = 0\n for linearObject in self.defList:\n result = linearObject.closestPtWithContext(pt)\n testdist = result[0]\n if testdist < sqrDist:\n closestPartIndex = index\n sqrDist = testdist\n minDistPoint = result[1]\n leftOf = result[2]\n \n index = index + 1 \n \n return (sqrDist, minDistPoint, closestPartIndex, leftOf)\n\n\n #===============================================================================\n # closestVertexWithContext\n #===============================================================================\n def closestVertexWithContext(self, pt, epsilon = 1.e-15):\n \"\"\"\n la funzione ritorna il vertice più vicino a pt\n \"\"\"\n # la funzione ritorna una lista con (<minima distanza al quadrato>,\n # <punto più vicino>\n # <indice della parte più vicina> \n # <\"a sinistra di\">)\n dummy = self.closestPartWithContext(pt, epsilon)\n partAt = dummy[2]\n linearObject = self.getLinearObjectAt(partAt) \n # punto iniziale della parte\n if qad_utils.getDistance(linearObject.getStartPt(), pt) < \\\n qad_utils.getDistance(linearObject.getEndPt(), pt): \n return partAt\n else: # punto finale della parte\n if partAt == self.qty() - 1: # se ultima parte \n return 0 if self.isClosed() else partAt + 1\n else:\n return partAt + 1\n \n\n #===============================================================================\n # breakOnPt\n #===============================================================================\n def breakOnPt(self, point):\n \"\"\"\n la funzione spezza in due la lista di parti nel punto <point>.\n Ritorna una lista di due parti: la prima parte (che può essere\n nulla se <point> coincide con il punto iniziale) e la seconda parte (che può essere\n nulla se <point> coincide con il punto finale)\n \"\"\"\n dummy = self.closestPartWithContext(point)\n nearestPt = dummy[1]\n partAt = dummy[2]\n if nearestPt is None or partAt is None:\n return [None, None]\n\n partToCut = self.getLinearObjectAt(partAt)\n cuttedParts = partToCut.breakOnPt(point)\n \n if ptNear(nearestPt, self.getStartPt()):\n partList1 = None\n partList2 = QadLinearObjectList(self)\n return [partList1, partList2]\n else:\n partList1 = QadLinearObjectList()\n for i in xrange(0, partAt, 1):\n partList1.append(QadLinearObject(self.getLinearObjectAt(i)))\n \n if cuttedParts[0] is not None:\n partList1.append(cuttedParts[0])\n \n if ptNear(nearestPt, self.getEndPt()):\n partList1 = QadLinearObjectList(self)\n partList2 = None\n return [partList1, partList2]\n else:\n partList2 = QadLinearObjectList()\n\n if cuttedParts[1] is not None:\n partList2.append(cuttedParts[1])\n \n for i in xrange(partAt + 1, self.qty(), 1):\n partList2.append(QadLinearObject(self.getLinearObjectAt(i)))\n \n return [partList1, partList2]\n\n\n #============================================================================\n # getIntPtNearestToStartPt\n #============================================================================\n def getIntPtNearestToStartPt(self, crs, entitySet, edgeMode):\n \"\"\"\n La funzione cerca il punto di intersezione tra la polilinea e un gruppo di entità\n che é più vicino al punto iniziale della polilinea.\n La funzione riceve:\n <crs> sistema di coordinate in cui é espressa la polilinea \n <entitySet> gruppo di entità\n La funzione restituisce:\n punto di intersezione, numero della parte\n \"\"\" \n newPt = None\n partNumber = -1\n distFromStart = 0\n trimmedLinearObject = QadLinearObject()\n gTransformed = QgsGeometry()\n \n # scorro i segmenti\n for i in xrange(0, self.qty(), 1):\n minDist = sys.float_info.max\n LinearObject = self.getLinearObjectAt(i) \n \n # per ciascun layer \n for layerEntitySet in entitySet.layerEntitySetList:\n layer = layerEntitySet.layer\n \n if layer.crs() != crs:\n coordTransform = QgsCoordinateTransform(layer.crs(), crs) \n trimmedLinearObject.set(LinearObject)\n \n # per ciascuna entità del layer\n for featureId in layerEntitySet.featureIds:\n f = getFeatureById(layer, featureId)\n if f is None:\n continue\n # Trasformo la geometria nel sistema di coordinate del <layer> \n gTransformed = f.geometry()\n if layer.crs() != crs:\n gTransformed.transform(coordTransform)\n \n intPt = getIntersectionPtTrimQgsGeometry(LinearObject, gTransformed, edgeMode)\n if intPt is not None:\n # cerco il punto di intersezione più vicino al punto iniziale\n trimmedLinearObject.setEndPt(intPt)\n if trimmedLinearObject.length() < minDist:\n minDist = trimmedLinearObject.length()\n newPt = intPt\n partNumber = i\n \n if newPt is not None:\n break\n \n distFromStart = distFromStart + LinearObject.length()\n \n if newPt is None:\n return None, -1\n else:\n return newPt, partNumber\n\n\n#===============================================================================\n# FINE - QadLinearObjectList class\n#===============================================================================\n \n \n#============================================================================\n# joinFeatureInVectorLayer\n#============================================================================\ndef joinFeatureInVectorLayer(featureIdToJoin, vectorLayer, tolerance2ApproxCurve, toleranceDist = TOLERANCE, \\\n mode = 2):\n \"\"\"\n la funzione effettua il join (unione) di una polilinea con un gruppo di altre polilinee.\n Non sono ammesse geometrie multiLineString.\n Il layer deve essere in modifica (startEditing) e in una transazione (beginEditCommand)\n La funzione riceve:\n <featureIdToJoin> = un ID della feature da unire \n <vectorLayer> = un QgsVectorLayer che deve contenere le feature da unire\n (si usano gli indici spaziali del vettore x essere più veloci).\n <toleranceDist> = distanza di tolleranza perché 2 punti siano considerati coincidenti \n <tolerance2ApproxCurve> = tolleranza di approssimazione per le curve (usato se toleranceDist > 0)\n <mode> = Imposta il metodo di unione (usato se toleranceDist > 0):\n 1 -> Estendi; Consente di unire polilinee selezionate estendendo o tagliando \n i segmenti nei punti finali più vicini.\n 2 -> Aggiungi; Consente di unire polilinee selezionate aggiungendo un segmento \n retto tra i punti finali più vicini.\n 3 -> Entrambi;Consente di unire polilinee selezionate estendendo o tagliando, se possibile.\n In caso contrario, consente di unire polilinee selezionate aggiungendo \n un segmento retto tra i punti finali più vicini. \n La funzione modifica il <vectorLayer> modificando la feature da unire e cancellando \n quelle unite a featureIdToJoin . Ritorna la lista di features cancellate.\n \"\"\" \n featureToJoin = getFeatureById(vectorLayer, featureIdToJoin)\n if featureToJoin is None:\n return []\n \n g = QgsGeometry(featureToJoin.geometry())\n linearObjectList = qad_utils.QadLinearObjectList()\n linearObjectList.fromPolyline(g.asPolyline())\n \n linearObjectListToJoinTo = qad_utils.QadLinearObjectList()\n \n deleteFeatures = []\n feature = QgsFeature()\n \n # Unisco usando il punto iniziale finché trovo feature da unire\n ptToJoin = linearObjectList.getStartPt()\n found = True\n while found == True:\n found = False\n if ptToJoin is None: # test\n fermati = True\n # cerco le features nel punto iniziale usando un micro rettangolo secondo <toleranceDist>\n selectRect = QgsRectangle(ptToJoin.x() - toleranceDist, ptToJoin.y() - toleranceDist, \\\n ptToJoin.x() + toleranceDist, ptToJoin.y() + toleranceDist)\n # cerco il punto più vicino al punto iniziale della polilinea\n minDist = sys.float_info.max\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in vectorLayer.getFeatures(getFeatureRequest([], True, selectRect, True)): \n if feature.id() != featureIdToJoin: # salto la feature da unire\n linearObjectListToJoinTo.fromPolyline(feature.geometry().asPolyline())\n \n if linearObjectList.join(linearObjectListToJoinTo, toleranceDist, mode) == True:\n found = True\n \n deleteFeatures.append(QgsFeature(feature))\n if vectorLayer.deleteFeature(feature.id()) == False:\n return []\n \n ptToJoin = linearObjectList.getStartPt()\n pts = linearObjectList.asPolyline(tolerance2ApproxCurve)\n featureToJoin.setGeometry(QgsGeometry.fromPolyline(pts))\n if vectorLayer.updateFeature(featureToJoin) == False:\n return []\n break\n \n # Unisco usando il punto finale finché trovo feature da unire\n ptToJoin = linearObjectList.getEndPt()\n found = True\n while found == True:\n found = False\n # cerco le features nel punto finale usando un micro rettangolo secondo <toleranceDist>\n selectRect = QgsRectangle(ptToJoin.x() - toleranceDist, ptToJoin.y() - toleranceDist, \\\n ptToJoin.x() + toleranceDist, ptToJoin.y() + toleranceDist)\n # fetchAttributes, fetchGeometry, rectangle, useIntersect \n for feature in vectorLayer.getFeatures(getFeatureRequest([], True, selectRect, True)): \n if feature.id() != featureIdToJoin: # salto la feature da unire\n linearObjectListToJoinTo.fromPolyline(feature.geometry().asPolyline())\n\n if linearObjectList.join(linearObjectListToJoinTo, toleranceDist, mode) == True:\n found = True\n \n deleteFeatures.append(QgsFeature(feature))\n if vectorLayer.deleteFeature(feature.id()) == False:\n return []\n \n ptToJoin = linearObjectList.getEndPt()\n pts = linearObjectList.asPolyline(tolerance2ApproxCurve)\n featureToJoin.setGeometry(QgsGeometry.fromPolyline(pts))\n if vectorLayer.updateFeature(featureToJoin) == False:\n return []\n break\n \n return deleteFeatures\n\n\n#===============================================================================\n# joinEndPtsLinearParts\n#===============================================================================\ndef joinEndPtsLinearParts(part1, part2, mode):\n \"\"\"\n la funzione effettua il join (unione) tra 2 parti lineari considerando il punto finale di part1\n e il punto iniziale di part2.\n La funzione riceve:\n <part1> = prima parte lineare \n <part2> = seconda parte parte lineare \n <mode> = Imposta il metodo di unione:\n 1 -> Estendi; Consente di unire polilinee selezionate estendendo o tagliando \n i segmenti nei punti finali più vicini.\n 2 -> Aggiungi; Consente di unire polilinee selezionate aggiungendo un segmento \n retto tra i punti finali più vicini.\n 3 -> Entrambi; Consente di unire polilinee selezionate estendendo o tagliando, se possibile.\n In caso contrario, consente di unire polilinee selezionate aggiungendo \n un segmento retto tra i punti finali più vicini. \n La funzione restituisce una QadLinearObjectList che comprende:\n part1 (eventualmente modificata nel punto finale) + \n eventuale segmento + \n part2 (eventualmente modificata nel punto finale)\n oppure restituisce None se non é possibile l'unione delle parti\n \"\"\"\n linearObjectList = qad_utils.QadLinearObjectList()\n endPt1 = part1.getEndPt()\n endPt2 = part2.getEndPt()\n \n if ptNear(endPt1, endPt2): # le 2 parti sono già unite\n linearObjectList.append(QadLinearObject(part1))\n linearObjectList.append(QadLinearObject(part2).reverse())\n return linearObjectList\n\n if mode == 1: # Estendi/Taglia\n IntPtList = part1.getIntersectionPtsWithLinearObject(part2)\n if len(IntPtList) > 0: # Taglia\n linearObjectList.append(QadLinearObject(part1))\n linearObjectList.getLinearObjectAt(-1).setEndPt(IntPtList[0])\n linearObjectList.append(QadLinearObject(part2).reverse())\n linearObjectList.getLinearObjectAt(-1).setStartPt(IntPtList[0])\n return linearObjectList\n else: # estendi\n IntPtList = part1.getIntersectionPtsOnExtensionWithLinearObject(part2)\n # considero solo i punti oltre l'inizio delle parti\n for i in xrange(len(IntPtList) - 1, -1, -1):\n if part1.getDistanceFromStart(IntPtList[i]) < 0 or \\\n part2.getDistanceFromStart(IntPtList[i]) < 0:\n del IntPtList[i] \n \n if len(IntPtList) > 0:\n IntPt = IntPtList[0] \n linearObjectList.append(QadLinearObject(part1))\n linearObjectList.getLinearObjectAt(-1).setEndPt(IntPtList[0])\n linearObjectList.append(QadLinearObject(part2.reverse()))\n linearObjectList.getLinearObjectAt(-1).setStartPt(IntPtList[0])\n return linearObjectList\n \n if mode == 2 or mode == 3: # Aggiungi\n linearObjectList.append(QadLinearObject(part1))\n linearObjectList.append([endPt1, endPt2])\n linearObjectList.append(QadLinearObject(part2).reverse())\n return linearObjectList\n\n return None\n\n\n#===============================================================================\n# getCurveLinearObjects\n#===============================================================================\ndef getCurveLinearObjects(tanDirectionOnStartPt, prev, current, next):\n \"\"\"\n Data la direzione della tangente nel punto iniziale della parte corrente e \n una successione di 3 parti lineari,\n la funzione ritorna una lista di parti lineari\n da sostituire alla parte <current> per curvare la polilinea\n \"\"\"\n if current.isArc():\n return [QadLinearObject(current)]\n\n # se non ci sono né la parte precedente né la parte successiva \n if prev is None and next is None:\n return QadLinearObject(current)\n\n arc = QadArc()\n if prev is None: # non c'é una parte precedente\n if arc.fromStartSecondEndPts(current.getStartPt(), current.getEndPt(), next.getEndPt()) == False:\n return [QadLinearObject(current)]\n if ptNear(current.getStartPt(), arc.getStartPt()): # arco non é inverso \n arc.setEndAngleByPt(current.getEndPt())\n return [QadLinearObject([arc, False])]\n else: # arco é inverso\n arc.setStartAngleByPt(current.getEndPt())\n return [QadLinearObject([arc, True])]\n else:\n t = prev.getTanDirectionOnEndPt() if tanDirectionOnStartPt is None else tanDirectionOnStartPt\n \n if next is None: # non c'é una parte successiva \n if arc.fromStartEndPtsTan(current.getStartPt(), current.getEndPt(), t) == False:\n return [QadLinearObject(current)]\n if ptNear(current.getStartPt(), arc.getStartPt()): # arco non é inverso \n return [QadLinearObject([arc, False])]\n else: # arco é inverso\n return [QadLinearObject([arc, True])]\n else: # c'é una parte precedente e successiva\n # calcolo il punto medio tra i 2 archi di raccordo\n# if arc.fromStartEndPtsTan(current.getStartPt(), current.getEndPt(), \\\n# prev.getTanDirectionOnEndPt()) == False:\n# return [QadLinearObject(current)]\n# tanDirectionOnEndPt = next.getTanDirectionOnStartPt() + math.pi\n# arc2 = QadArc()\n# if arc2.fromStartEndPtsTan(current.getEndPt(), current.getStartPt(), \\\n# tanDirectionOnEndPt) == False:\n# return [QadLinearObject(current)]\n\n if arc.fromStartSecondEndPts(prev.getStartPt(), current.getStartPt(), current.getEndPt()) == False:\n return [QadLinearObject(current)]\n if ptNear(prev.getStartPt(), arc.getStartPt()): # arco non é inverso \n arc.setStartAngleByPt(current.getStartPt())\n else: # arco é inverso\n arc.setEndAngleByPt(current.getStartPt())\n arc2 = QadArc()\n if arc2.fromStartSecondEndPts(current.getStartPt(), current.getEndPt(), next.getEndPt()) == False:\n return [QadLinearObject(current)]\n if ptNear(current.getStartPt(), arc2.getStartPt()): # arco non é inverso \n arc2.setEndAngleByPt(current.getEndPt())\n else: # arco é inverso\n arc2.setStartAngleByPt(current.getEndPt())\n\n midPt = getMiddlePoint(arc.getMiddlePt(), arc2.getMiddlePt())\n \n if arc.fromStartEndPtsTan(current.getStartPt(), midPt, t) == False:\n return [QadLinearObject(current)]\n if ptNear(current.getStartPt(), arc.getStartPt()): # arco non é inverso \n linearObject1 = QadLinearObject([arc, False])\n else: # arco é inverso\n linearObject1 = QadLinearObject([arc, True])\n \n if arc2.fromStartEndPtsTan(linearObject1.getEndPt(), current.getEndPt(), \\\n linearObject1.getTanDirectionOnEndPt()) == False:\n return [QadLinearObject(current)]\n if ptNear(current.getEndPt(), arc2.getEndPt()): # arco non é inverso \n linearObject2 = QadLinearObject([arc2, False])\n else: # arco é inverso\n linearObject2 = QadLinearObject([arc2, True])\n\n return [linearObject1, linearObject2]\n\n\n#============================================================================\n# TrimExtend\n#============================================================================\ndef getFilletLinearObjectList(poly1, partAt1, pointAt1, poly2, partAt2, pointAt2, filletMode, radius, epsg):\n \"\"\"\n Date due polilinee, la parte e il punto in cui bisogna fare il raccordo tra le due\n polilinee, la funzione ritorna una polilinea risultato del raccordo e due flag che\n danno indicazioni su ciò che deve essere fatto alle polilinee originali:\n (0=niente, 1=modificare, 2=cancellare)\n <filletMode> modalità di raccordo; 1=Taglia-estendi, 2=Non taglia-estendi\n <radius> raggio di raccordo\n \"\"\"\n circle1 = poly1.getCircle()\n circle2 = poly2.getCircle()\n \n if circle1 is None: # se poly1 non era un cerchio\n part = QadLinearObject(poly1.getLinearObjectAt(partAt1))\n if circle2 is None: # se poly2 non era un cerchio\n nextPart = QadLinearObject(poly2.getLinearObjectAt(partAt2)) \n if part.isSegment():\n if nextPart.isSegment(): # part e nextPart sono segmenti retti\n if radius == 0: \n res = bridgeTheGapBetweenLines(part, pointAt1, nextPart, pointAt2, radius, 0)\n else:\n res = bridgeTheGapBetweenLines(part, pointAt1, nextPart, pointAt2, radius, 1)\n else: # part é un segmento retto, nextPart é un arco\n res = bridgeTheGapBetweenArcLine(nextPart, pointAt2, part, pointAt1, radius, filletMode)\n if res is not None:\n dummy = res[0] # inverto il primo e il terzo elemento\n res[0] = res[2]\n res[2] = dummy\n else:\n if nextPart.isSegment(): # part é un arco, nextPart é un segmento retto\n res = bridgeTheGapBetweenArcLine(part, pointAt1, nextPart, pointAt2, radius, filletMode)\n else: # part é un arco, nextPart é un arco\n res = bridgeTheGapBetweenArcs(part, pointAt1, nextPart, pointAt2, radius, filletMode)\n else:\n if part.isSegment(): # part é un segmento retto, poly2 é un cerchio\n res = bridgeTheGapBetweenCircleLine(poly2, pointAt2, part, pointAt1, radius, filletMode)\n if res is not None:\n dummy = res[0] # inverto il primo e il terzo elemento\n res[0] = res[2]\n res[2] = dummy\n else: # part é un arco, poly2 é un cerchio\n res = bridgeTheGapBetweenArcCircle(part, pointAt1, poly2, pointAt2, radius, filletMode)\n else:\n if circle2 is None: # se poly2 non era un cerchio\n nextPart = QadLinearObject(poly2.getLinearObjectAt(partAt2)) \n if nextPart.isSegment(): # poly1 é un cerchio, nextPart é un segmento retto\n res = bridgeTheGapBetweenCircleLine(poly1, pointAt1, nextPart, pointAt2, radius, filletMode)\n else: # poly1 é un cerchio, nextPart é un arco\n res = bridgeTheGapBetweenArcCircle(nextPart, pointAt2, poly1, pointAt1, radius, filletMode)\n if res is not None:\n dummy = res[0] # inverto il primo e il terzo elemento\n res[0] = res[2]\n res[2] = dummy\n else: # poly1 e poly2 sono cerchi\n res = bridgeTheGapBetweenCircles(poly1, pointAt1, poly2, pointAt2, radius)\n\n if res is None: # raccordo non possibile\n return None\n \n filletLinearObjectList = QadLinearObjectList()\n whatToDoPoly1 = 0 # 0=niente, 1=modificare, 2=cancellare\n whatToDoPoly2 = 0 # 0=niente, 1=modificare, 2=cancellare\n \n if filletMode == 1 or radius == 0: # modalità di raccordo \"Taglia-estendi\"\n if circle1 is None: # se poly1 non era un cerchio\n if res[0] is not None:\n part.set(res[0]) # modifico part\n if circle2 is None: # se poly2 non era un cerchio\n if res[2] is not None:\n nextPart.set(res[2]) # modifico nextPart\n\n filletArc = res[1] # arco di raccordo\n\n if filletArc is None:\n if circle1 is None and circle2 is None:\n # se il punto iniziale di part tocca nextPart\n if ptNear(part.getStartPt(), nextPart.getStartPt()) or \\\n ptNear(part.getStartPt(), nextPart.getEndPt()):\n whatToDoPoly1 = 1 # 1=modificare\n # aggiungo part e le parti successive di part\n filletLinearObjectList.append(part)\n filletLinearObjectList.appendList(poly1, partAt1 + 1)\n # se il punto finale di part tocca nextPart\n elif ptNear(part.getEndPt(), nextPart.getStartPt()) or \\\n ptNear(part.getEndPt(), nextPart.getEndPt()):\n whatToDoPoly1 = 1 # 1=modificare\n # aggiungo part e le parti precedenti di part\n filletLinearObjectList.append(part)\n filletLinearObjectList.appendList(poly1, 0, partAt1)\n \n # se il punto iniziale di nextPart tocca part\n if ptNear(nextPart.getStartPt(), part.getStartPt()) or \\\n ptNear(nextPart.getStartPt(), part.getEndPt()):\n if whatToDoPoly1 == 1: # se la poly1 era da modificare (1=modificare)\n whatToDoPoly2 = 2 # 2=cancellare\n else:\n whatToDoPoly2 = 1 # 1=modificare\n # aggiungo nextPart e le parti successive di nextPart\n filletLinearObjectList.append(nextPart)\n filletLinearObjectList.appendList(poly2, partAt2 + 1)\n # se il punto finale di nextPart tocca part\n elif ptNear(nextPart.getEndPt(), part.getStartPt()) or \\\n ptNear(nextPart.getEndPt(), part.getEndPt()):\n if whatToDoPoly1 == 1: # se la poly1 era da modificare (1=modificare)\n whatToDoPoly2 = 2 # 2=cancellare\n else:\n whatToDoPoly2 = 1 # 1=modificare\n # aggiungo nextPart e le parti precedenti di nextPart\n filletLinearObjectList.append(nextPart)\n filletLinearObjectList.appendList(poly2, 0, partAt2) \n else: # esiste un arco di raccordo\n filletLinearObjectList.append(filletArc)\n if circle1 is None:\n # se l'arco di raccordo tocca il punto iniziale di part\n if ptNear(filletArc.getStartPt(), part.getStartPt()) or \\\n ptNear(filletArc.getEndPt(), part.getStartPt()):\n whatToDoPoly1 = 1 # 1=modificare\n # aggiungo part e le parti successive di part\n filletLinearObjectList.append(part)\n filletLinearObjectList.appendList(poly1, partAt1 + 1)\n # se l'arco di raccordo tocca il punto finale di part\n elif ptNear(filletArc.getStartPt(), part.getEndPt()) or \\\n ptNear(filletArc.getEndPt(), part.getEndPt()):\n whatToDoPoly1 = 1 # 1=modificare\n # aggiungo part e le parti precedenti di part\n filletLinearObjectList.append(part)\n filletLinearObjectList.appendList(poly1, 0, partAt1)\n \n if circle2 is None:\n # se l'arco di raccordo tocca il punto iniziale di nextPart\n if ptNear(filletArc.getStartPt(), nextPart.getStartPt()) or \\\n ptNear(filletArc.getEndPt(), nextPart.getStartPt()):\n if whatToDoPoly1 == 1: # se la poly1 era da modificare (1=modificare)\n whatToDoPoly2 = 2 # 2=cancellare\n else:\n whatToDoPoly2 = 1 # 1=modificare\n # aggiungo nextPart e le parti successive di nextPart\n filletLinearObjectList.append(nextPart)\n filletLinearObjectList.appendList(poly2, partAt2 + 1)\n # se l'arco di raccordo tocca il punto finale di nextPart\n elif ptNear(filletArc.getStartPt(), nextPart.getEndPt()) or \\\n ptNear(filletArc.getEndPt(), nextPart.getEndPt()):\n if whatToDoPoly1 == 1: # se la poly1 era da modificare (1=modificare)\n whatToDoPoly2 = 2 # 2=cancellare\n else:\n whatToDoPoly2 = 1 # 1=modificare\n # aggiungo nextPart e le parti precedenti di nextPart\n filletLinearObjectList.append(nextPart)\n filletLinearObjectList.appendList(poly2, 0, partAt2)\n \n res = filletLinearObjectList.selfJoin(epsg)\n if len(res) != 1:\n return None\n \n return res[0], whatToDoPoly1, whatToDoPoly2\n\n\n#============================================================================\n# QadRawConfigParser class suppporting unicode\n#============================================================================\nclass QadRawConfigParser(ConfigParser.RawConfigParser):\n\n def __init__(self, defaults=None, dict_type=ConfigParser._default_dict,\n allow_no_value=False):\n ConfigParser.RawConfigParser.__init__(self, defaults, dict_type, allow_no_value)\n \n def get(self, section, option, default = None):\n try:\n return ConfigParser.RawConfigParser.get(self, section, option)\n except:\n return default\n\n def getint(self, section, option, default = None):\n try:\n return ConfigParser.RawConfigParser.getint(self, section, option)\n except:\n return default\n\n def getfloat(self, section, option, default = None):\n try:\n return ConfigParser.RawConfigParser.getfloat(self, section, option)\n except:\n return default\n\n def getboolean(self, section, option, default = None):\n try:\n return ConfigParser.RawConfigParser.getboolean(self, section, option)\n except:\n return default\n\n def write(self, fp):\n \"\"\"Fixed for Unicode output\"\"\"\n if self._defaults:\n fp.write(\"[%s]\\n\" % DEFAULTSECT)\n for (key, value) in self._defaults.items():\n fp.write(\"%s = %s\\n\" % (key, unicode(value).replace('\\n', '\\n\\t')))\n fp.write(\"\\n\")\n for section in self._sections:\n fp.write(\"[%s]\\n\" % section)\n for (key, value) in self._sections[section].items():\n if key != \"__name__\":\n fp.write(\"%s = %s\\n\" % (key, unicode(value).replace('\\n','\\n\\t')))\n fp.write(\"\\n\")\n \n\n#===============================================================================\n# Timer class for profiling\n#===============================================================================\nclass Timer(object):\n # da usare:\n # with qad_utils.Timer() as t:\n # ...\n # elasped = t.secs\n def __init__(self, verbose=False):\n self.verbose = verbose\n\n def __enter__(self):\n self.start = time.time()\n return self\n\n def __exit__(self, *args):\n self.end = time.time()\n self.secs = self.end - self.start\n self.msecs = self.secs * 1000 # millisecs\n if self.verbose:\n print 'elapsed time: %f ms' % self.msecs\n"
},
{
"alpha_fraction": 0.6877278089523315,
"alphanum_fraction": 0.7144593000411987,
"avg_line_length": 60.935482025146484,
"blob_id": "9a71db0559a715332b2543bdea053067b4ce0300",
"content_id": "748818acd85736fc60bd24a2c2a741d05091fca0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5761,
"license_type": "no_license",
"max_line_length": 420,
"num_lines": 93,
"path": "/qad_dimstyle_diff_ui.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qad_dimstyle_diff.ui'\n#\n# Created: Tue Sep 08 15:55:22 2015\n# by: PyQt4 UI code generator 4.10.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_DimStyle_Diff_Dialog(object):\n def setupUi(self, DimStyle_Diff_Dialog):\n DimStyle_Diff_Dialog.setObjectName(_fromUtf8(\"DimStyle_Diff_Dialog\"))\n DimStyle_Diff_Dialog.resize(443, 526)\n self.label = QtGui.QLabel(DimStyle_Diff_Dialog)\n self.label.setGeometry(QtCore.QRect(10, 10, 71, 21))\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.label_2 = QtGui.QLabel(DimStyle_Diff_Dialog)\n self.label_2.setGeometry(QtCore.QRect(10, 40, 71, 21))\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.dimStyle1 = QtGui.QComboBox(DimStyle_Diff_Dialog)\n self.dimStyle1.setGeometry(QtCore.QRect(80, 10, 211, 22))\n self.dimStyle1.setObjectName(_fromUtf8(\"dimStyle1\"))\n self.dimStyle2 = QtGui.QComboBox(DimStyle_Diff_Dialog)\n self.dimStyle2.setGeometry(QtCore.QRect(80, 40, 211, 22))\n self.dimStyle2.setObjectName(_fromUtf8(\"dimStyle2\"))\n self.line = QtGui.QFrame(DimStyle_Diff_Dialog)\n self.line.setGeometry(QtCore.QRect(10, 70, 421, 16))\n self.line.setFrameShape(QtGui.QFrame.HLine)\n self.line.setFrameShadow(QtGui.QFrame.Sunken)\n self.line.setObjectName(_fromUtf8(\"line\"))\n self.msg = QtGui.QLabel(DimStyle_Diff_Dialog)\n self.msg.setGeometry(QtCore.QRect(10, 80, 321, 21))\n self.msg.setObjectName(_fromUtf8(\"msg\"))\n self.layoutWidget = QtGui.QWidget(DimStyle_Diff_Dialog)\n self.layoutWidget.setGeometry(QtCore.QRect(277, 490, 158, 25))\n self.layoutWidget.setObjectName(_fromUtf8(\"layoutWidget\"))\n self.horizontalLayout = QtGui.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout.setMargin(0)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.closeButton = QtGui.QPushButton(self.layoutWidget)\n self.closeButton.setObjectName(_fromUtf8(\"closeButton\"))\n self.horizontalLayout.addWidget(self.closeButton)\n self.helpButton = QtGui.QPushButton(self.layoutWidget)\n self.helpButton.setObjectName(_fromUtf8(\"helpButton\"))\n self.horizontalLayout.addWidget(self.helpButton)\n self.tableWidget = QtGui.QTableWidget(DimStyle_Diff_Dialog)\n self.tableWidget.setGeometry(QtCore.QRect(10, 110, 421, 371))\n self.tableWidget.setObjectName(_fromUtf8(\"tableWidget\"))\n self.tableWidget.setColumnCount(0)\n self.tableWidget.setRowCount(0)\n self.copyButton = QtGui.QPushButton(DimStyle_Diff_Dialog)\n self.copyButton.setGeometry(QtCore.QRect(404, 80, 31, 23))\n self.copyButton.setText(_fromUtf8(\"\"))\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(_fromUtf8(\":/plugins/qad/icons/copy.png\")), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.copyButton.setIcon(icon)\n self.copyButton.setObjectName(_fromUtf8(\"copyButton\"))\n\n self.retranslateUi(DimStyle_Diff_Dialog)\n QtCore.QObject.connect(self.helpButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Diff_Dialog.ButtonHELP_Pressed)\n QtCore.QObject.connect(self.dimStyle1, QtCore.SIGNAL(_fromUtf8(\"currentIndexChanged(int)\")), DimStyle_Diff_Dialog.DimStyleName1Changed)\n QtCore.QObject.connect(self.dimStyle2, QtCore.SIGNAL(_fromUtf8(\"currentIndexChanged(int)\")), DimStyle_Diff_Dialog.DimStyleName2Changed)\n QtCore.QObject.connect(self.copyButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Diff_Dialog.copyToClipboard)\n QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL(_fromUtf8(\"clicked()\")), DimStyle_Diff_Dialog.accept)\n QtCore.QMetaObject.connectSlotsByName(DimStyle_Diff_Dialog)\n\n def retranslateUi(self, DimStyle_Diff_Dialog):\n DimStyle_Diff_Dialog.setWindowTitle(_translate(\"DimStyle_Diff_Dialog\", \"QAD - Compare dimension styles\", None))\n self.label.setText(_translate(\"DimStyle_Diff_Dialog\", \"Compare:\", None))\n self.label_2.setText(_translate(\"DimStyle_Diff_Dialog\", \"With:\", None))\n self.dimStyle1.setToolTip(_translate(\"DimStyle_Diff_Dialog\", \"Specify the first dimension style.\", None))\n self.dimStyle2.setToolTip(_translate(\"DimStyle_Diff_Dialog\", \"Specify the second dimension style. If you set the second style as the first, all dimension style properties will displayed.\", None))\n self.msg.setText(_translate(\"DimStyle_Diff_Dialog\", \"TextLabel\", None))\n self.closeButton.setText(_translate(\"DimStyle_Diff_Dialog\", \"Close\", None))\n self.helpButton.setText(_translate(\"DimStyle_Diff_Dialog\", \"?\", None))\n self.tableWidget.setToolTip(_translate(\"DimStyle_Diff_Dialog\", \"<html><head/><body><p>Display the result of comparing dimension styles.If you compare two different styles, the settings that are different between the two dimension styles, their current settings, and brief descriptions are listed. If you set the second style as the first, all dimension style properties will displayed.</p></body></html>\", None))\n self.copyButton.setToolTip(_translate(\"DimStyle_Diff_Dialog\", \"Copy the result of comparing into the clipboard.\", None))\n\n"
},
{
"alpha_fraction": 0.583325982093811,
"alphanum_fraction": 0.5863350629806519,
"avg_line_length": 42.45769119262695,
"blob_id": "3cc36c306e2b7ec568638700a915463d73a97a39",
"content_id": "759613a7028f9bf7ba5895730fe6059c29ab9186",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11307,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 260,
"path": "/qad_lengthen_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando lengthen\n \n -------------------\n begin : 2015-10-06\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_rubberband import QadRubberBand\nfrom qad_dim import QadDimStyles\n\n\n#===============================================================================\n# Qad_lengthen_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_lengthen_maptool_ModeEnum():\n # si richiede la selezione dell'oggetto da misurare\n ASK_FOR_OBJ_TO_MISURE = 1\n # si richiede il delta\n ASK_FOR_DELTA = 2\n # non si richiede niente\n NONE = 3\n # si richiede la selezione dell'oggetto da allungare\n ASK_FOR_OBJ_TO_LENGTHEN = 4\n # si richiede la percentuale \n ASK_FOR_PERCENT = 5\n # si richiede il totale\n ASK_FOR_TOTAL = 6\n # si richiede il nuovo punto dell'estremità in modalità dinamica\n ASK_FOR_DYNAMIC_POINT = 7\n\n#===============================================================================\n# Qad_lengthen_maptool class\n#===============================================================================\nclass Qad_lengthen_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n\n self.OpMode = None # \"DElta\" o \"Percent\" o \"Total\" o \"DYnamic\"\n self.OpType = None # \"length\" o \"Angle\"\n self.value = None\n self.tmpLinearObjectList = None\n\n self.__rubberBand = QadRubberBand(self.canvas)\n\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__rubberBand.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__rubberBand.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__rubberBand.reset()\n self.mode = None\n\n def setInfo(self, entity, point):\n # setta: self.layer, self.tmpLinearObjectList e self.move_startPt\n\n if self.tmpLinearObjectList is not None:\n del self.tmpLinearObjectList\n self.tmpLinearObjectList = None\n \n if entity.isInitialized() == False:\n return False\n \n self.layer = entity.layer\n transformedPt = self.canvas.mapRenderer().mapToLayerCoordinates(self.layer, point)\n geom = entity.getGeometry()\n \n # ritorna una tupla (<The squared cartesian distance>,\n # <minDistPoint>\n # <afterVertex>\n # <leftOf>)\n dummy = qad_utils.closestSegmentWithContext(transformedPt, geom)\n if dummy[2] is None:\n return False\n # ritorna la sotto-geometria al vertice <atVertex> e la sua posizione nella geometria (0-based)\n subGeom, atSubGeom = qad_utils.getSubGeomAtVertex(geom, dummy[2]) \n self.tmpLinearObjectList = qad_utils.QadLinearObjectList() \n self.tmpLinearObjectList.fromPolyline(subGeom.asPolyline())\n \n if qad_utils.getDistance(self.tmpLinearObjectList.getStartPt(), transformedPt) <= \\\n qad_utils.getDistance(self.tmpLinearObjectList.getEndPt(), transformedPt):\n # si allunga/accorcia dal punto iniziale \n self.move_startPt = True\n else:\n # si allunga dal punto finale\n self.move_startPt = False\n return True\n\n\n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__rubberBand.reset()\n res = False\n \n # si richiede la selezione dell'oggetto da allungare\n if self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_OBJ_TO_LENGTHEN:\n if self.tmpEntity.isInitialized():\n if self.setInfo(self.tmpEntity, self.tmpPoint) == False:\n return\n\n if self.OpMode == \"DElta\":\n newTmpLinearObjectList = qad_utils.QadLinearObjectList(self.tmpLinearObjectList)\n if self.OpType == \"length\":\n res = newTmpLinearObjectList.lengthen_delta(self.move_startPt, self.value)\n elif self.OpType == \"Angle\":\n res = newTmpLinearObjectList.lengthen_deltaAngle(self.move_startPt, self.value)\n elif self.OpMode == \"Percent\":\n newTmpLinearObjectList = qad_utils.QadLinearObjectList(self.tmpLinearObjectList)\n value = newTmpLinearObjectList.length() * self.value / 100\n value = value - newTmpLinearObjectList.length()\n res = newTmpLinearObjectList.lengthen_delta(self.move_startPt, value)\n elif self.OpMode == \"Total\":\n newTmpLinearObjectList = qad_utils.QadLinearObjectList(self.tmpLinearObjectList)\n if self.OpType == \"length\":\n value = self.value - self.tmpLinearObjectList.length()\n res = newTmpLinearObjectList.lengthen_delta(self.move_startPt, value)\n elif self.OpType == \"Angle\": \n if newTmpLinearObjectList.qty() == 1:\n linearObject = newTmpLinearObjectList.getLinearObjectAt(0)\n if linearObject.isArc() == True: # se è un arco\n value = self.value - linearObject.getArc().totalAngle()\n res = newTmpLinearObjectList.lengthen_deltaAngle(self.move_startPt, value)\n \n # si richiede un punto per la nuova estremità\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_DYNAMIC_POINT:\n newTmpLinearObjectList = qad_utils.QadLinearObjectList(self.tmpLinearObjectList)\n transformedPt = self.canvas.mapRenderer().mapToLayerCoordinates(self.layer, self.tmpPoint)\n \n if self.move_startPt:\n linearObject = newTmpLinearObjectList.getLinearObjectAt(0)\n else:\n linearObject = newTmpLinearObjectList.getLinearObjectAt(-1)\n \n if linearObject.isSegment():\n newPt = qad_utils.getPerpendicularPointOnInfinityLine(linearObject.getStartPt(), linearObject.getEndPt(), transformedPt)\n else: # arco\n newPt = qad_utils.getPolarPointByPtAngle(linearObject.getArc().center, \\\n qad_utils.getAngleBy2Pts(linearObject.getArc().center, transformedPt), \\\n linearObject.getArc().radius) \n\n if newTmpLinearObjectList.qty() > 1 and linearObject.isSegment():\n ang = linearObject.getTanDirectionOnStartPt()\n\n if self.move_startPt:\n linearObject.setStartPt(newPt)\n else:\n linearObject.setEndPt(newPt)\n\n if newTmpLinearObjectList.qty() > 1 and linearObject.isSegment() and \\\n qad_utils.TanDirectionNear(ang, linearObject.getTanDirectionOnStartPt()) == False:\n res = False\n else:\n res = True\n \n if res == False: # allungamento impossibile\n return\n pts = newTmpLinearObjectList.asPolyline()\n geom = QgsGeometry.fromPolyline(pts)\n self.__rubberBand.addGeometry(geom, self.layer)\n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__rubberBand.show() \n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__rubberBand.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n\n # si richiede la selezione dell'oggetto da misurare\n if self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_OBJ_TO_MISURE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION)\n\n # solo layer di tipo lineari che non appartengano a quote o di tipo poligono \n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and \\\n layer.geometryType() == QGis.Line or layer.geometryType() == QGis.Polygon:\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.onlyEditableLayers = False\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n # si richiede il delta\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_DELTA:\n self.OpMode = \"DElta\"\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n # non si richiede niente\n elif self.mode == Qad_lengthen_maptool_ModeEnum.NONE:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n # si richiede la selezione dell'oggetto da allungare\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_OBJ_TO_LENGTHEN:\n self.setSelectionMode(QadGetPointSelectionModeEnum.ENTITY_SELECTION_DYNAMIC)\n\n # solo layer lineari editabili che non appartengano a quote\n layerList = []\n for layer in self.plugIn.canvas.layers():\n if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Line and \\\n layer.isEditable():\n if len(QadDimStyles.getDimListByLayer(layer)) == 0:\n layerList.append(layer)\n \n self.layersToCheck = layerList\n self.onlyEditableLayers = True\n self.setSnapType(QadSnapTypeEnum.DISABLE)\n # si richiede la percentuale\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_PERCENT:\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION) \n self.OpMode = \"Percent\"\n # si richiede il totale\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_TOTAL:\n self.OpMode = \"Total\"\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n # si richiede il nuovo punto dell'estremità in modalità dinamica\n elif self.mode == Qad_lengthen_maptool_ModeEnum.ASK_FOR_DYNAMIC_POINT:\n self.OpMode = \"DYnamic\"\n self.setSelectionMode(QadGetPointSelectionModeEnum.POINT_SELECTION)\n"
},
{
"alpha_fraction": 0.590499222278595,
"alphanum_fraction": 0.593880832195282,
"avg_line_length": 45.00185012817383,
"blob_id": "29bd74137ae9dc01af5c232aa3d98f7b38330928",
"content_id": "76b7c23d8b2649c19f7fd5076cd00f5e4bf145b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 24866,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 540,
"path": "/qad_stretch_fun.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n funzioni per stirare oggetti grafici\n \n -------------------\n begin : 2013-11-11\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\n\n\nimport qad_utils\nimport qad_arc\nimport qad_circle\nfrom qad_snapper import *\n\n\n#===============================================================================\n# isPtContainedForStretch\n#===============================================================================\ndef isPtContainedForStretch(point, containerGeom, tolerance=None):\n \"\"\"\n Funzione di ausilio per le funzioni di stretch (stretchPoint e stretchQgsLineStringGeometry).\n Se containerGeom è un oggetto QgsGeometry allora ritorna True se il punto è contenuto a livello spaziale\n dalla geometria containerGeom.\n Se containerGeom è una lista di punti allora ritorna True se il punto è fra quelli della lista.\n \"\"\"\n if tolerance is None:\n tolerance = qad_utils.TOLERANCE\n if type(containerGeom) == QgsGeometry: # geometria \n return containerGeom.contains(point)\n elif type(containerGeom) == list: # lista di punti\n for containerPt in containerGeom:\n if qad_utils.ptNear(containerPt, point, tolerance): # se i punti sono sufficientemente vicini\n return True\n return False \n\n\n#===============================================================================\n# stretchPoint\n#===============================================================================\ndef stretchPoint(point, containerGeom, offSetX, offSetY):\n \"\"\"\n Stira il punto se è contenuto in containerGeom\n point = punto da stirare\n containerGeom = può essere una QgsGeometry rappresentante un poligono contenente i punti di geom da stirare\n oppure una lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n if isPtContainedForStretch(point, containerGeom): # se il punto è contenuto in containerGeom\n return qad_utils.movePoint(point, offSetX, offSetY)\n\n return None\n\n\n#===============================================================================\n# stretchQgsGeometry\n#===============================================================================\ndef stretchQgsGeometry(geom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira una geometria\n geom = geometria da tirare\n containerGeom = può essere una QgsGeometry rappresentante un poligono contenente i punti di geom da stirare\n oppure una lista dei punti di geom da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n tolerance2ApproxCurve = tolleranza per rigenerare le curve\n \"\"\"\n wkbType = geom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = stretchPoint(geom.asPoint(), containerGeom, offSetX, offSetY)\n if pt is not None:\n return QgsGeometry.fromPoint(pt)\n \n if wkbType == QGis.WKBMultiPoint:\n stretchedGeom = QgsGeometry(geom)\n points = stretchedGeom.asMultiPoint() # vettore di punti\n atSubGeom = 0\n for pt in points:\n subGeom = QgsGeometry.fromPoint(pt)\n stretchedSubGeom = stretchQgsGeometry(subGeom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom])\n atSubGeom = atSubGeom + 1\n return stretchedGeom\n\n if wkbType == QGis.WKBLineString:\n return stretchQgsLineStringGeometry(geom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve)\n \n if wkbType == QGis.WKBMultiLineString:\n stretchedGeom = QgsGeometry(geom)\n lines = stretchedGeom.asMultiPolyline() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = QgsGeometry.fromPolyline(line)\n stretchedSubGeom = stretchQgsGeometry(subGeom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n if wkbType == QGis.WKBPolygon:\n stretchedGeom = QgsGeometry(geom)\n lines = stretchedGeom.asPolygon() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = QgsGeometry.fromPolyline(line)\n stretchedSubGeom = stretchQgsGeometry(subGeom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n if wkbType == QGis.WKBMultiPolygon:\n stretchedGeom = QgsGeometry(geom)\n polygons = geom.asMultiPolygon() # vettore di poligoni\n atSubGeom = 0\n for polygon in polygons:\n subGeom = QgsGeometry.fromPolygon(polygon)\n stretchedSubGeom = stretchQgsGeometry(subGeom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n return None\n\n\n#===============================================================================\n# stretchQgsLineStringGeometry\n#===============================================================================\ndef stretchQgsLineStringGeometry(geom, containerGeom, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira i punti di una linestring che sono contenuti in containerGeom\n point = punto da tirare\n containerGeom = può essere una QgsGeometry rappresentante un poligono contenente i punti di geom da stirare\n oppure una lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n obj = qad_utils.whatGeomIs(0, geom)\n if (type(obj) != list and type(obj) != tuple):\n objType = obj.whatIs()\n if objType == \"CIRCLE\": # se é cerchio\n if isPtContainedForStretch(obj.center, containerGeom): # se il punto è contenuto in containerGeom\n obj.center.setX(obj.center.x() + offSetX)\n obj.center.setY(obj.center.y() + offSetY)\n return QgsGeometry.fromPolyline(obj.asPolyline(tolerance2ApproxCurve)) \n\n stretchedGeom = QgsGeometry(geom)\n snapper = QadSnapper()\n points = snapper.getEndPoints(stretchedGeom)\n del snapper\n\n linearObjectListToStretch = qad_utils.QadLinearObjectList()\n linearObjectListToStretch.fromPolyline(geom.asPolyline())\n \n for point in points:\n if isPtContainedForStretch(point, containerGeom): # se il punto è contenuto in containerGeom\n atPart = linearObjectListToStretch.containsPt(point)\n while atPart >= 0:\n linearObject = linearObjectListToStretch.getLinearObjectAt(atPart)\n pt = linearObject.getStartPt() \n if qad_utils.ptNear(pt, point): # cambio punto iniziale\n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n if linearObject.isSegment():\n linearObject.setStartPt(pt)\n else:\n oldArc = linearObject.getArc()\n middlePt = oldArc.getMiddlePt()\n distFromMiddleChord = qad_utils.getDistance(middlePt, qad_utils.getPerpendicularPointOnInfinityLine(oldArc.getStartPt(), oldArc.getEndPt(), middlePt))\n \n newArc = QadArc()\n if linearObject.isInverseArc(): \n middlePt = qad_utils.getMiddlePoint(pt, oldArc.getStartPt())\n middlePt = qad_utils.getPolarPointByPtAngle(middlePt, \\\n qad_utils.getAngleBy2Pts(pt, oldArc.getStartPt()) + math.pi / 2, \\\n distFromMiddleChord) \n if newArc.fromStartSecondEndPts(oldArc.getStartPt(), middlePt, pt) == False:\n return None\n else:\n middlePt = qad_utils.getMiddlePoint(pt, oldArc.getEndPt())\n middlePt = qad_utils.getPolarPointByPtAngle(middlePt, \\\n qad_utils.getAngleBy2Pts(pt, oldArc.getEndPt()) - math.pi / 2, \\\n distFromMiddleChord) \n if newArc.fromStartSecondEndPts(pt, middlePt, oldArc.getEndPt()) == False:\n return None\n linearObject.setArc(newArc, linearObject.isInverseArc()) \n else:\n pt = linearObject.getEndPt()\n if qad_utils.ptNear(pt, point): # cambio punto finale\n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n if linearObject.isSegment():\n linearObject.setEndPt(pt)\n else:\n oldArc = linearObject.getArc()\n middlePt = oldArc.getMiddlePt()\n distFromMiddleChord = qad_utils.getDistance(middlePt, qad_utils.getPerpendicularPointOnInfinityLine(oldArc.getStartPt(), oldArc.getEndPt(), middlePt))\n \n newArc = QadArc()\n if linearObject.isInverseArc():\n middlePt = qad_utils.getMiddlePoint(pt, oldArc.getEndPt())\n middlePt = qad_utils.getPolarPointByPtAngle(middlePt, \\\n qad_utils.getAngleBy2Pts(pt, oldArc.getEndPt()) - math.pi / 2, \\\n distFromMiddleChord) \n if newArc.fromStartSecondEndPts(pt, middlePt, oldArc.getEndPt()) == False:\n return None\n else:\n middlePt = qad_utils.getMiddlePoint(pt, oldArc.getStartPt())\n middlePt = qad_utils.getPolarPointByPtAngle(middlePt, \\\n qad_utils.getAngleBy2Pts(pt, oldArc.getStartPt()) + math.pi / 2, \\\n distFromMiddleChord) \n if newArc.fromStartSecondEndPts(oldArc.getStartPt(), middlePt, pt) == False:\n return None\n linearObject.setArc(newArc, linearObject.isInverseArc()) \n \n atPart = linearObjectListToStretch.containsPt(point, atPart + 1)\n \n pts = linearObjectListToStretch.asPolyline(tolerance2ApproxCurve)\n stretchedGeom = QgsGeometry.fromPolyline(pts) \n \n return stretchedGeom \n\n\n####################################################################\n# Funzioni di stretch per grip point\n####################################################################\n\n\n#===============================================================================\n# gripStretchQgsGeometry\n#===============================================================================\ndef gripStretchQgsGeometry(geom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira una geometria in coordinate piane mediante grip point\n geom = geometria da stirare\n ptListToStretch = lista dei punti di geom da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n tolerance2ApproxCurve = tolleranza per rigenerare le curve\n \"\"\"\n wkbType = geom.wkbType()\n if wkbType == QGis.WKBPoint or wkbType == QGis.WKBPoint25D:\n pt = stretchPoint(geom.asPoint(), ptListToStretch, offSetX, offSetY)\n if pt is not None:\n return QgsGeometry.fromPoint(pt)\n \n if wkbType == QGis.WKBMultiPoint:\n stretchedGeom = QgsGeometry(geom)\n points = stretchedGeom.asMultiPoint() # vettore di punti\n atSubGeom = 0\n for pt in points:\n subGeom = QgsGeometry.fromPoint(pt)\n stretchedSubGeom = gripStretchQgsGeometry(subGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n\n if wkbType == QGis.WKBLineString:\n return gripStretchQgsLineStringGeometry(geom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n \n if wkbType == QGis.WKBMultiLineString:\n stretchedGeom = QgsGeometry(geom)\n lines = stretchedGeom.asMultiPolyline() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = QgsGeometry.fromPolyline(line)\n stretchedSubGeom = gripStretchQgsGeometry(subGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n if wkbType == QGis.WKBPolygon:\n stretchedGeom = QgsGeometry(geom)\n lines = stretchedGeom.asPolygon() # lista di linee\n atSubGeom = 0\n for line in lines: \n subGeom = QgsGeometry.fromPolyline(line)\n stretchedSubGeom = gripStretchQgsGeometry(subGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n if wkbType == QGis.WKBMultiPolygon:\n stretchedGeom = QgsGeometry(geom)\n polygons = geom.asMultiPolygon() # vettore di poligoni\n atSubGeom = 0\n for polygon in polygons:\n subGeom = QgsGeometry.fromPolygon(polygon)\n stretchedSubGeom = gripStretchQgsGeometry(subGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n stretchedGeom = qad_utils.setSubGeom(stretchedGeom, stretchedSubGeom, [atSubGeom]) \n atSubGeom = atSubGeom + 1\n return stretchedGeom\n \n return None\n\n\n#===============================================================================\n# gripStretchQadGeometry\n#===============================================================================\ndef gripStretchQadGeometry(geom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira una entità qad in coordinate piane mediante grip point\n geom = entità qad da stirare\n ptListToStretch = lista dei punti di geom da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n tolerance2ApproxCurve = tolleranza per rigenerare le curve\n \"\"\"\n if type(geom) == list: # entità composta da più geometrie\n res = []\n for subGeom in geom:\n res.append(gripStretchQadGeometry(subGeom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve))\n return res\n else:\n if type(geom) == QgsPoint:\n return stretchPoint(geom, ptListToStretch, offSetX, offSetY)\n elif geom.whatIs() == \"ARC\":\n return gripStretchArc(geom, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve) \n elif geom.whatIs() == \"CIRCLE\":\n return gripStretchCircle(geom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n elif geom.whatIs() == \"LINEAROBJS\":\n return gripStretchQgsLinearObjectList(geom, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n\n return None\n\n\n#===============================================================================\n# gripStretchCircle\n#===============================================================================\ndef gripStretchCircle(circle, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira i punti di grip di un cerchio che sono contenuti in ptListToStretch\n circle = cerchio da stirare\n basePt = punto base\n ptListToStretch = lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n newCenter = QgsPoint(circle.center)\n newRadius = circle.radius\n \n for ptToStretch in ptListToStretch:\n if qad_utils.ptNear(ptToStretch, circle.center): # se i punti sono sufficientemente vicini\n newCenter.set(circle.center.x() + offSetX, circle.center.y() + offSetY)\n elif circle.isPtOnCircle(ptToStretch):\n newPt = QgsPoint(basePt.x() + offSetX, basePt.y() + offSetY)\n newRadius = qad_utils.getDistance(circle.center, newPt)\n\n newCircle = qad_circle.QadCircle()\n if newCircle.set(newCenter, newRadius) == False:\n return None\n \n return newCircle\n\n\n#===============================================================================\n# gripStretchArc\n#===============================================================================\ndef gripStretchArc(arc, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve, inverseArc = None):\n \"\"\"\n Stira i punti di grip di un arco che sono contenuti in ptListToStretch\n arc = arco da stirare\n ptListToStretch = lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n startPt = arc.getStartPt()\n endPt = arc.getEndPt()\n middlePt = arc.getMiddlePt()\n newStartPt = QgsPoint(startPt)\n newEndPt = QgsPoint(endPt)\n newMiddlePt = QgsPoint(middlePt)\n newCenter = None\n startPtChanged = endPtChanged = middlePtPtChanged = False\n for ptToStretch in ptListToStretch:\n if qad_utils.ptNear(ptToStretch, arc.center): # se i punti sono sufficientemente vicini\n newCenter = QgsPoint(arc.center.x() + offSetX, arc.center.y() + offSetY)\n else:\n if qad_utils.ptNear(startPt, ptToStretch):\n newStartPt.set(startPt.x() + offSetX, startPt.y() + offSetY)\n startPtChanged = True\n elif qad_utils.ptNear(endPt, ptToStretch):\n newEndPt.set(endPt.x() + offSetX, endPt.y() + offSetY)\n endPtChanged = True\n elif qad_utils.ptNear(middlePt, ptToStretch):\n newMiddlePt.set(middlePt.x() + offSetX, middlePt.y() + offSetY)\n middlePtPtChanged = True\n \n newArc = qad_arc.QadArc()\n if newArc.fromStartSecondEndPts(newStartPt, newMiddlePt, newEndPt) == False:\n return None\n \n # se il centro era nei punti di grip\n if newCenter is not None:\n # se i tre punti dell'arco erano nei punti di grip oppure\n # allora non cambio il centro\n if (startPtChanged and endPtChanged and middlePtPtChanged):\n pass\n else:\n newArc.center.set(newCenter.x(), newCenter.y())\n \n if inverseArc is not None: # se l'arco faceva parte di una linestring\n # verifico il verso del nuovo arco\n if qad_utils.ptNear(newStartPt, newArc.getStartPt()):\n # stesso verso del vecchio arco\n return newArc, inverseArc\n else:\n return newArc, not inverseArc\n \n return newArc\n\n\n#===============================================================================\n# gripStretchQgsLineStringGeometry\n#===============================================================================\ndef gripStretchQgsLineStringGeometry(geom, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira i punti di grip di una linestring che sono contenuti in ptListToStretch\n geom = geometria da stirare\n basePt = punto base\n ptListToStretch = lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n obj = qad_utils.whatGeomIs(0, geom)\n if (type(obj) != list and type(obj) != tuple):\n objType = obj.whatIs()\n if objType == \"CIRCLE\": # se é cerchio\n newCircle = gripStretchCircle(obj, basePt, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n if newCircle is not None:\n return QgsGeometry.fromPolyline(newCircle.asPolyline(tolerance2ApproxCurve))\n elif objType == \"ARC\": # se é arco\n newArc = gripStretchArc(obj, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve)\n if newArc is not None:\n return QgsGeometry.fromPolyline(newArc.asPolyline(tolerance2ApproxCurve))\n return None\n \n linearObjectListToStretch = qad_utils.QadLinearObjectList()\n linearObjectListToStretch.fromPolyline(geom.asPolyline())\n \n atPart = 0\n while atPart < linearObjectListToStretch.qty():\n linearObject = linearObjectListToStretch.getLinearObjectAt(atPart) \n if linearObject.isSegment():\n pt = linearObject.getStartPt()\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n # cambio punto iniziale \n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n linearObject.setStartPt(pt)\n \n pt = linearObject.getEndPt()\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n # cambio punto finale\n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n linearObject.setEndPt(pt)\n else: # se è arco\n newArc, newInverseFlag = gripStretchArc(linearObject.getArc(), ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve, linearObject.isInverseArc())\n if newArc is None:\n return None\n linearObject.setArc(newArc, newInverseFlag)\n\n atPart = atPart + 1\n \n pt = linearObjectListToStretch.getCentroid(tolerance2ApproxCurve) # verifico se polilinea ha un centroide\n if pt is not None:\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n linearObjectListToStretch.move(offSetX, offSetY)\n \n pts = linearObjectListToStretch.asPolyline(tolerance2ApproxCurve)\n stretchedGeom = QgsGeometry.fromPolyline(pts) \n \n return stretchedGeom \n\n\n#===============================================================================\n# gripStretchQgsLinearObjectList\n#===============================================================================\ndef gripStretchQgsLinearObjectList(linearObjectList, ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve):\n \"\"\"\n Stira i punti di grip di una linestring che sono contenuti in ptListToStretch\n linearObjectListToStretch = geometria da stirare\n ptListToStretch = lista dei punti da stirare\n offSetX = spostamento X\n offSetY = spostamento Y\n \"\"\"\n linearObjectListToStretch = qad_utils.QadLinearObjectList(linearObjectList)\n \n atPart = 0\n while atPart < linearObjectListToStretch.qty():\n linearObject = linearObjectListToStretch.getLinearObjectAt(atPart) \n if linearObject.isSegment():\n pt = linearObject.getStartPt()\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n # cambio punto iniziale \n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n linearObject.setStartPt(pt)\n \n pt = linearObject.getEndPt()\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n # cambio punto finale\n pt.setX(pt.x() + offSetX)\n pt.setY(pt.y() + offSetY)\n linearObject.setEndPt(pt)\n else: # se è arco\n newArc, newInverseFlag = gripStretchArc(linearObject.getArc(), ptListToStretch, offSetX, offSetY, tolerance2ApproxCurve, linearObject.isInverseArc())\n if newArc is None:\n return None\n linearObject.setArc(newArc, newInverseFlag)\n\n atPart = atPart + 1\n \n pt = linearObjectListToStretch.getCentroid(tolerance2ApproxCurve) # verifico se polilinea ha un centroide\n if pt is not None:\n if isPtContainedForStretch(pt, ptListToStretch): # se il punto è contenuto in ptListToStretch\n linearObjectListToStretch.move(offSetX, offSetY)\n\n return linearObjectListToStretch"
},
{
"alpha_fraction": 0.5372474789619446,
"alphanum_fraction": 0.5599899888038635,
"avg_line_length": 42.35610580444336,
"blob_id": "4a3306c60821ac4e4628c8bde5cb16b460f1198c",
"content_id": "b071196e5d8dd13505f5abbdeb407f03aa8f189a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 83845,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 1932,
"path": "/qad_circle.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per la gestione dei cerchi\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\nimport sys\n\nimport qad_utils\nfrom qad_variables import *\nfrom qad_arc import *\n\n\n#===============================================================================\n# QadArc arc class\n#===============================================================================\nclass QadCircle():\n \n def __init__(self, circle = None):\n if circle is not None:\n self.set(circle.center, circle.radius)\n else: \n self.center = None\n self.radius = None\n\n def whatIs(self):\n return \"CIRCLE\"\n\n def set(self, center, radius):\n if radius <=0:\n return False\n self.center = QgsPoint(center)\n self.radius = radius\n return True\n\n def transform(self, ct):\n \"\"\"Transform this geometry as described by CoordinateTranasform ct.\"\"\"\n self.center = coordTransform.transform(self.center) \n\n def transformFromCRSToCRS(self, sourceCRS, destCRS):\n \"\"\"Transform this geometry as described by CRS.\"\"\"\n if (sourceCRS is not None) and (destCRS is not None) and sourceCRS != destCRS: \n coordTransform = QgsCoordinateTransform(sourceCRS, destCRS) # trasformo le coord\n self.center = coordTransform.transform(self.center)\n \n def __eq__(self, circle):\n \"\"\"self == other\"\"\"\n if self.center != circle.center or self.radius != circle.radius:\n return False\n else:\n return True \n \n def __ne__(self, circle):\n \"\"\"self != other\"\"\"\n if self.center != circle.center or self.radius != circle.radius:\n return True \n else:\n return False \n \n def length(self):\n return 2 * math.pi * self.radius\n\n def lengthBetween2Points(self, pt1, pt2, leftOfPt1):\n \"\"\"\n Calcola la distanza tra 2 punti sulla circonferenza. L'arco considerato può essere\n quello a sinistra o a destra di <pt1> (vedi <leftOfPt1>)\n se <leftOfPt1> é boolean allora se = True viene considerato l'arco a sin di pt1\n se <leftOfPt1> é float allora significa che si tratta della direzione della tangente su pt1\n e se la direzione è a sin viene considerato l'arco a sin di pt1\n \"\"\"\n if qad_utils.ptNear(pt1, pt2): # se i punti sono così vicini da essere considerati uguali\n return 0\n \n if type(leftOfPt1) == float: # direzione della tangente su pt1 \n startAngle = qad_utils.getAngleBy2Pts(self.center, pt1) \n if qad_utils.doubleNear(qad_utils.normalizeAngle(startAngle + math.pi / 2), \n qad_utils.normalizeAngle(leftOfPt1)):\n _leftOfPt1 = True\n else:\n _leftOfPt1 = False\n else: # booolean\n _leftOfPt1 = leftOfPt1\n \n if _leftOfPt1: # arco a sinistra di pt1\n startAngle = qad_utils.getAngleBy2Pts(self.center, pt1) \n endAngle = qad_utils.getAngleBy2Pts(self.center, pt2)\n else: # arco a destra di pt1\n startAngle = qad_utils.getAngleBy2Pts(self.center, pt2)\n endAngle = qad_utils.getAngleBy2Pts(self.center, pt1) \n\n if startAngle < endAngle:\n totalAngle = endAngle - startAngle\n else:\n totalAngle = (2 * math.pi - startAngle) + endAngle\n \n return self.radius * totalAngle\n\n def area(self):\n return math.pi * self.radius * self.radius\n\n def isPtOnCircle(self, point):\n dist = qad_utils.getDistance(self.center, point)\n return qad_utils.doubleNear(self.radius, dist)\n\n def getQuadrantPoints(self):\n # ritorna i punti quadranti: pt in alto, pt in basso, a destra, a sinistra del centro\n pt1 = QgsPoint(self.center.x(), self.center.y() + self.radius)\n pt2 = QgsPoint(self.center.x(), self.center.y()- self.radius)\n pt3 = QgsPoint(self.center.x() + self.radius, self.center.y())\n pt4 = QgsPoint(self.center.x() - self.radius, self.center.y())\n return [pt1, pt2, pt3, pt4]\n\n \n def getTanPoints(self, point):\n dist = qad_utils.getDistance(self.center, point)\n if dist < self.radius:\n return []\n if dist == self.radius:\n return [point]\n \n angleOffSet = math.asin(self.radius / dist)\n angleOffSet = (math.pi / 2) - angleOffSet\n angle = qad_utils.getAngleBy2Pts(self.center, point)\n \n pt1 = qad_utils.getPolarPointByPtAngle(self.center, angle + angleOffSet, self.radius)\n pt2 = qad_utils.getPolarPointByPtAngle(self.center, angle - angleOffSet, self.radius) \n return [pt1, pt2]\n \n\n def getPerpendicularPoints(self, point):\n angle = qad_utils.getAngleBy2Pts(self.center, point) \n pt1 = qad_utils.getPolarPointByPtAngle(self.center, angle, self.radius) \n pt2 = qad_utils.getPolarPointByPtAngle(self.center, angle + math.pi, self.radius)\n return [pt1, pt2] \n\n\n def getIntersectionPointsWithCircle(self, circle):\n result = []\n # se i punti sono così vicini da essere considerati uguali \n if qad_utils.ptNear(self.center, circle.center): # stesso centro\n return result\n distFromCenters = qad_utils.getDistance(self.center, circle.center)\n distFromCirc = distFromCenters - self.radius - circle.radius\n\n # se è così vicino allo zero da considerarlo = 0\n if qad_utils.doubleNear(distFromCirc, 0):\n angle = qad_utils.getAngleBy2Pts(self.center, circle.center)\n result.append(qad_utils.getPolarPointByPtAngle(self.center, angle, self.radius))\n return result\n \n if distFromCirc > 0: # i cerchi sono troppo distanti\n return result\n\n x2_self = self.center.x() * self.center.x() # X del centro del cerchio <self> al quadrato\n x2_circle = circle.center.x() * circle.center.x() # Y del centro del cerchio <circle> al quadrato\n radius2_self = self.radius * self.radius # raggio del cerchio <self> al quadrato\n radius2_circle = circle.radius * circle.radius # raggio del cerchio <circle> al quadrato\n \n if qad_utils.doubleNear(self.center.y(), circle.center.y()):\n x1 = x2_circle - x2_self + radius2_self - radius2_circle\n x1 = x1 / (2 * (circle.center.x() - self.center.x()))\n x2 = x1 \n D = radius2_self - ((x1 - self.center.x()) * (x1 - self.center.x()))\n # se D è così vicino a zero \n if qad_utils.doubleNear(D, 0.0):\n D = 0\n elif D < 0: # non si può fare la radice quadrata di un numero negativo\n return result\n E = math.sqrt(D)\n \n y1 = self.center.y() + E\n y2 = self.center.y() - E\n else:\n y2_self = self.center.y() * self.center.y() # Y del centro del cerchio <self> al quadrato\n y2_circle = circle.center.y() * circle.center.y() # Y del centro del cerchio <circle> al quadrato\n \n a = (self.center.x() - circle.center.x()) / (circle.center.y() - self.center.y())\n b = x2_circle - x2_self + y2_circle - y2_self + radius2_self - radius2_circle \n b = b / (2 * (circle.center.y() - self.center.y()))\n \n A = 1 + (a * a)\n B = (2 * a * b) - (2 * self.center.x()) - (2 * a * self.center.y())\n C = (b * b) - (2 * self.center.y() * b) + x2_self + y2_self - radius2_self\n D = (B * B) - (4 * A * C)\n # se D è così vicino a zero \n if qad_utils.doubleNear(D, 0.0):\n D = 0\n elif D < 0: # non si può fare la radice quadrata di un numero negativo\n return result\n E = math.sqrt(D)\n \n x1 = (-B + E) / (2 * A)\n y1 = a * x1 + b\n \n x2 = (-B - E) / (2 * A) \n y2 = a * x2 + b\n \n result.append(QgsPoint(x1, y1))\n if x1 != x2 or y1 != y2: # i punti non sono coincidenti\n result.append(QgsPoint(x2, y2))\n \n return result\n\n\n def getIntersectionPointsWithInfinityLine(self, p1, p2):\n result = []\n if p1 == p2:\n return result\n\n x2_self = self.center.x() * self.center.x() # X del centro del cerchio <self> al quadrato\n y2_self = self.center.y() * self.center.y() # Y del centro del cerchio <self> al quadrato\n radius2_self = self.radius * self.radius # raggio del cerchio <self> al quadrato\n \n diffX = p2.x() - p1.x()\n if diffX == 0: # se la retta passante per p1 e p2 é verticale\n B = -2 * self.center.y()\n C = x2_self + y2_self + (p1.x() * p1.x()) - (2* p1.x() * self.center.x()) - radius2_self\n D = (B * B) - (4 * C) \n # se D è così vicino a zero \n if qad_utils.doubleNear(D, 0.0):\n D = 0\n elif D < 0: # non si può fare la radice quadrata di un numero negativo\n return result\n E = math.sqrt(D)\n \n y1 = (-B + E) / 2 \n x1 = p1.x()\n \n y2 = (-B - E) / 2 \n x2 = p1.x()\n else:\n m = (p2.y() - p1.y()) / diffX\n q = p1.y() - (m * p1.x())\n A = 1 + (m * m)\n B = (2 * m * q) - (2 * self.center.x()) - (2 * m * self.center.y())\n C = x2_self + (q * q) + y2_self - (2 * q * self.center.y()) - radius2_self\n \n D = (B * B) - 4 * A * C\n # se D è così vicino a zero \n if qad_utils.doubleNear(D, 0.0):\n D = 0\n elif D < 0: # non si può fare la radice quadrata di un numero negativo\n return result\n E = math.sqrt(D)\n \n x1 = (-B + E) / (2 * A)\n y1 = p1.y() + m * x1 - m * p1.x()\n \n x2 = (-B - E) / (2 * A)\n y2 = p1.y() + m * x2 - m * p1.x()\n \n result.append(QgsPoint(x1, y1))\n if x1 != x2 or y1 != y2: # i punti non sono coincidenti\n result.append(QgsPoint(x2, y2))\n \n return result\n\n\n #============================================================================\n # getIntersectionPointsWithSegment\n #============================================================================\n def getIntersectionPointsWithSegment(self, p1, p2):\n result = []\n intPtList = self.getIntersectionPointsWithInfinityLine(p1, p2)\n for intPt in intPtList:\n if qad_utils.isPtOnSegment(p1, p2, intPt):\n result.append(intPt)\n return result\n\n\n #============================================================================\n # getTangentsWithCircle\n #============================================================================\n def getTangentsWithCircle(self, circle):\n \"\"\"\n la funzione ritorna una lista di linee che sono le tangenti ai due cerchi\n \"\"\"\n tangents = []\n \n x1 = self.center[0]\n y1 = self.center[1]\n r1 = self.radius\n x2 = circle.center[0]\n y2 = circle.center[1]\n r2 = circle.radius\n\n d_sq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n if (d_sq <= (r1-r2)*(r1-r2)):\n return tangents\n \n d = math.sqrt(d_sq);\n vx = (x2 - x1) / d;\n vy = (y2 - y1) / d;\n \n # Let A, B be the centers, and C, D be points at which the tangent\n # touches first and second circle, and n be the normal vector to it.\n #\n # We have the system:\n # n * n = 1 (n is a unit vector) \n # C = A + r1 * n\n # D = B +/- r2 * n\n # n * CD = 0 (common orthogonality)\n #\n # n * CD = n * (AB +/- r2*n - r1*n) = AB*n - (r1 -/+ r2) = 0, <=>\n # AB * n = (r1 -/+ r2), <=>\n # v * n = (r1 -/+ r2) / d, where v = AB/|AB| = AB/d\n # This is a linear equation in unknown vector n.\n sign1 = +1\n while sign1 >= -1:\n c = (r1 - sign1 * r2) / d;\n \n # Now we're just intersecting a line with a circle: v*n=c, n*n=1\n \n if (c*c > 1.0):\n sign1 = sign1 - 2\n continue\n \n h = math.sqrt(max(0.0, 1.0 - c*c));\n\n sign2 = +1\n while sign2 >= -1:\n nx = vx * c - sign2 * h * vy;\n ny = vy * c + sign2 * h * vx;\n\n tangent = []\n tangent.append(QgsPoint(x1 + r1 * nx, y1 + r1 * ny))\n tangent.append(QgsPoint(x2 + sign1 * r2 * nx, y2 + sign1 * r2 * ny))\n tangents.append(tangent)\n sign2 = sign2 - 2\n \n sign1 = sign1 - 2\n \n return tangents \n\n\n #============================================================================\n # asPolyline\n #============================================================================\n def asPolyline(self, tolerance2ApproxCurve = None, atLeastNSegment = None):\n \"\"\"\n ritorna una lista di punti che definisce il cerchio\n \"\"\"\n \n if tolerance2ApproxCurve is None:\n tolerance = QadVariables.get(QadMsg.translate(\"Environment variables\", \"TOLERANCE2APPROXCURVE\"))\n else:\n tolerance = tolerance2ApproxCurve\n\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n # Calcolo la lunghezza del segmento con pitagora\n dummy = self.radius - tolerance\n if dummy <= 0: # se la tolleranza è troppo bassa rispetto al raggio\n SegmentLen = self.radius\n else:\n dummy = (self.radius * self.radius) - (dummy * dummy)\n SegmentLen = math.sqrt(dummy) # radice quadrata\n SegmentLen = SegmentLen * 2\n\n if SegmentLen == 0: # se la tolleranza è troppo bassa la lunghezza del segmento diventa zero \n return None\n\n # calcolo quanti segmenti ci vogliono (non meno di _atLeastNSegment)\n SegmentTot = math.ceil(self.length() / SegmentLen)\n if SegmentTot < _atLeastNSegment:\n SegmentTot = _atLeastNSegment\n \n points = []\n # primo punto\n firsPt = qad_utils.getPolarPointByPtAngle(self.center, 0, self.radius)\n points.append(firsPt)\n\n i = 1\n angle = 0\n offSetAngle = 2 * math.pi / SegmentTot\n while i < SegmentTot:\n angle = angle + offSetAngle\n pt = qad_utils.getPolarPointByPtAngle(self.center, angle, self.radius)\n points.append(pt) \n i = i + 1\n\n # ultimo punto (come il primo)\n points.append(firsPt)\n return points\n\n\n #============================================================================\n # fromPolyline\n #============================================================================\n def fromPolyline(self, points, startVertex, atLeastNSegment = None):\n \"\"\"\n setta le caratteristiche del primo cerchio incontrato nella lista di punti\n partendo dalla posizione startVertex (0-indexed)\n ritorna la posizione nella lista del punto iniziale e finale se é stato trovato un cerchio\n altrimenti None.\n N.B. in punti NON devono essere in coordinate geografiche\n \"\"\"\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n totPoints = len(points)\n # perchésia un cerchio ci vogliono almeno _atLeastNSegment segmenti\n if (totPoints - 1) - startVertex < _atLeastNSegment or _atLeastNSegment < 2:\n return None\n\n # per problemi di approssimazione dei calcoli\n epsilon = 1.e-4 # percentuale del raggio per ottenere max diff. di una distanza con il raggio\n\n InfinityLinePerpOnMiddle1 = None\n InfinityLinePerpOnMiddle2 = None\n \n nSegment = 0\n i = startVertex\n while i < totPoints - 1:\n if InfinityLinePerpOnMiddle1 is None:\n InfinityLinePerpOnMiddle1 = qad_utils.getInfinityLinePerpOnMiddle(points[i], points[i + 1])\n nStartVertex = i\n nSegment = 1\n i = i + 1\n continue\n elif InfinityLinePerpOnMiddle2 is None: \n InfinityLinePerpOnMiddle2 = qad_utils.getInfinityLinePerpOnMiddle(points[i], points[i + 1])\n if InfinityLinePerpOnMiddle2 is None: \n InfinityLinePerpOnMiddle1 = None\n nSegment = 0\n else:\n # calcolo il presunto centro con 2 segmenti\n center = qad_utils.getIntersectionPointOn2InfinityLines(InfinityLinePerpOnMiddle1[0], \\\n InfinityLinePerpOnMiddle1[1], \\\n InfinityLinePerpOnMiddle2[0], \\\n InfinityLinePerpOnMiddle2[1])\n if center is None: # linee parallele\n InfinityLinePerpOnMiddle1 = InfinityLinePerpOnMiddle2\n InfinityLinePerpOnMiddle2 = None\n nStartVertex = i\n nSegment = 1\n else:\n nSegment = nSegment + 1\n radius = qad_utils.getDistance(center, points[i + 1]) # calcolo il presunto raggio\n maxDifference = radius * epsilon\n \n # calcolo il verso dell'arco e l'angolo dell'arco\n # se un punto intermedio dell'arco è a sinistra del\n # segmento che unisce i due punti allora il verso è antiorario\n startClockWise = True if qad_utils.leftOfLine(points[i], points[i - 1], points[i + 1]) < 0 else False\n angle = qad_utils.getAngleBy3Pts(points[i - 1], center, points[i + 1], startClockWise) \n else: # e sono già stati valutati almeno 2 segmenti\n # calcolo la distanza del punto dal presunto centro\n dist = qad_utils.getDistance(center, points[i + 1])\n # calcolo il verso dell'arco e l'angolo \n clockWise = True if qad_utils.leftOfLine(points[i], points[i - 1], points[i + 1]) < 0 else False \n angle = angle + qad_utils.getAngleBy3Pts(points[i], center, points[i + 1], startClockWise)\n \n # se la distanza è così vicina a quella del raggio\n # il verso dell'arco deve essere quello iniziale\n # l'angolo dell'arco non può essere > 360 gradi\n if qad_utils.doubleNear(radius, dist, maxDifference) and \\\n startClockWise == clockWise and \\\n (angle < 2 * math.pi or qad_utils.doubleNear(angle, 2 * math.pi)): \n nSegment = nSegment + 1 # anche questo segmento fa parte del cerchio\n else: # questo segmento non fa parte del cerchio\n nStartVertex = i\n nSegment = 1 \n InfinityLinePerpOnMiddle1 = qad_utils.getInfinityLinePerpOnMiddle(points[i], points[i + 1])\n InfinityLinePerpOnMiddle2 = None\n \n i = i + 1\n\n # se sono stati trovati un numero sufficiente di segmenti successivi\n if nSegment >= _atLeastNSegment:\n nEndVertex = nStartVertex + nSegment\n # se il punto iniziale e quello finale coincidono é un cerchio\n if points[nStartVertex] == points[nEndVertex]:\n self.center = center\n self.radius = radius \n return nStartVertex, nEndVertex\n\n return None\n\n\n #============================================================================\n # fromCenterPtArea\n #============================================================================\n def fromCenterArea(self, centerPt, area):\n \"\"\"\n setta le caratteristiche del cerchio attraverso:\n il punto centrale\n area\n \"\"\"\n if centerPt is None or area <= 0:\n return False\n self.center = centerPt\n self.radius = math.sqrt(area / math.pi)\n return True\n\n\n #============================================================================\n # from3Pts\n #============================================================================\n def from3Pts(self, firstPt, secondPt, thirdPt):\n \"\"\"\n setta le caratteristiche del cerchio attraverso:\n punto iniziale\n secondo punto (intermedio)\n punto finale\n \"\"\"\n InfinityLinePerpOnMiddle1 = qad_utils.getInfinityLinePerpOnMiddle(firstPt, secondPt)\n InfinityLinePerpOnMiddle2 = qad_utils.getInfinityLinePerpOnMiddle(secondPt, thirdPt)\n if InfinityLinePerpOnMiddle1 is None or InfinityLinePerpOnMiddle2 is None:\n return False\n self.center = qad_utils.getIntersectionPointOn2InfinityLines(InfinityLinePerpOnMiddle1[0], \\\n InfinityLinePerpOnMiddle1[1], \\\n InfinityLinePerpOnMiddle2[0], \\\n InfinityLinePerpOnMiddle2[1])\n if self.center is None: # linee parallele\n return False\n self.radius = qad_utils.getDistance(self.center, firstPt)\n return True\n\n\n #============================================================================\n # from3TanPts\n #============================================================================\n def from3TanPts(self, geom1, pt1, geom2, pt2, geom3, pt3):\n \"\"\"\n setta le caratteristiche del cerchio attraverso\n tre oggetti di tangenza per le estremità del diametro:\n geometria 1 di tangenza (linea, arco o cerchio)\n punto di selezione geometria 1\n geometria 2 di tangenza (linea, arco o cerchio)\n punto di selezione geometria 2\n \"\"\"\n obj1 = qad_utils.whatGeomIs(pt1, geom1)\n obj2 = qad_utils.whatGeomIs(pt2, geom2)\n obj3 = qad_utils.whatGeomIs(pt3, geom3)\n \n if (obj1 is None) or (obj2 is None) or (obj3 is None):\n return False\n\n if (type(obj1) == list or type(obj1) == tuple):\n obj1Type = \"LINE\"\n else:\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj1 = circle\n obj1Type = \"CIRCLE\" \n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj2.center, obj2.radius)\n obj2 = circle\n obj2Type = \"CIRCLE\" \n\n if (type(obj3) == list or type(obj3) == tuple):\n obj3Type = \"LINE\"\n else:\n obj3Type = obj3.whatIs()\n if obj3Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj3.center, obj3.radius)\n obj3 = circle\n obj3Type = \"CIRCLE\" \n \n if obj1Type == \"LINE\":\n if obj2Type == \"LINE\":\n if obj3Type == \"LINE\":\n return self.fromLineLineLineTanPts(obj1, pt1, obj2, pt2, obj3, pt3)\n elif obj3Type == \"CIRCLE\":\n return self.fromLineLineCircleTanPts(obj1, pt1, obj2, pt2, obj3, pt3)\n elif obj2Type == \"CIRCLE\":\n if obj3Type == \"LINE\":\n return self.fromLineLineCircleTanPts(obj1, pt1, obj3, pt3, obj2, pt2)\n elif obj3Type == \"CIRCLE\":\n return self.fromLineCircleCircleTanPts(obj1, pt1, obj2, pt2, obj3, pt3)\n elif obj1Type == \"CIRCLE\":\n if obj2Type == \"LINE\":\n if obj3Type == \"LINE\":\n return self.fromLineLineCircleTanPts(obj2, pt2, obj3, pt3, obj1, pt1)\n elif obj3Type == \"CIRCLE\":\n return self.fromLineCircleCircleTanPts(obj2, pt2, obj1, pt1, obj3, pt3)\n elif obj2Type == \"CIRCLE\":\n if obj3Type == \"LINE\":\n return self.fromLineCircleCircleTanPts(obj3, pt3, obj1, pt1, obj2, pt2)\n elif obj3Type == \"CIRCLE\":\n return self.fromCircleCircleCircleTanPts(obj1, pt1, obj2, pt2, obj3, pt3)\n \n return False\n \n\n #============================================================================\n # fromLineLineLineTanPts\n #============================================================================\n def fromLineLineLineTanPts(self, line1, pt1, line2, pt2, line3, pt3):\n \"\"\"\n setta le caratteristiche del cerchio attraverso tre linee:\n linea1 di tangenza (lista di 2 punti)\n punto di selezione linea1\n linea2 di tangenza (lista di 2 punti)\n punto di selezione linea2\n linea3 di tangenza (lista di 2 punti)\n punto di selezione linea3\n \"\"\"\n circleList = []\n \n # Punti di intersezione delle rette (line1, line2, line3)\n ptInt1 = qad_utils.getIntersectionPointOn2InfinityLines(line1[0], line1[1], \\\n line2[0], line2[1]) \n ptInt2 = qad_utils.getIntersectionPointOn2InfinityLines(line2[0], line2[1], \\\n line3[0], line3[1]) \n ptInt3 = qad_utils.getIntersectionPointOn2InfinityLines(line3[0], line3[1], \\\n line1[0], line1[1])\n # tre rette parallele\n if (ptInt1 is None) and (ptInt2 is None):\n return circleList\n \n if (ptInt1 is None): # la linea1 e linea2 sono parallele\n circleList.extend(self.from2ParLinesLineTanPts(line1, line2, line3)) \n elif (ptInt2 is None): # la linea2 e linea3 sono parallele\n circleList.extend(self.from2ParLinesLineTanPts(line2, line3, line1)) \n elif (ptInt3 is None): # la linea3 e linea1 sono parallele\n circleList.extend(self.from2ParLinesLineTanPts(line3, line1, line2)) \n else:\n # Bisettrici degli angoli interni del triangolo avente come vertici i punti di intersezione delle rette\n Bisector123 = qad_utils.getBisectorInfinityLine(ptInt1, ptInt2, ptInt3)\n Bisector231 = qad_utils.getBisectorInfinityLine(ptInt2, ptInt3, ptInt1)\n Bisector312 = qad_utils.getBisectorInfinityLine(ptInt3, ptInt1, ptInt2)\n # Punto di intersezione delle bisettrici = centro delle circonferenza inscritta al triangolo\n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector123[0], Bisector123[1], \\\n Bisector231[0], Bisector231[1])\n # Perpendicolari alle rette line1 passanti per il centro della circonferenza inscritta\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n # Bisettrici degli angoli esterni del triangolo\n angle = qad_utils.getAngleBy2Pts(Bisector123[0], Bisector123[1]) + math.pi / 2\n Bisector123 = [ptInt2, qad_utils.getPolarPointByPtAngle(ptInt2, angle, 10)]\n \n angle = qad_utils.getAngleBy2Pts(Bisector231[0], Bisector231[1]) + math.pi / 2\n Bisector231 = [ptInt3, qad_utils.getPolarPointByPtAngle(ptInt3, angle, 10)]\n\n angle = qad_utils.getAngleBy2Pts(Bisector312[0], Bisector312[1]) + math.pi / 2\n Bisector312 = [ptInt1, qad_utils.getPolarPointByPtAngle(ptInt1, angle, 10)]\n # Punti di intersezione delle bisettrici = centro delle circonferenze ex-inscritte\n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector123[0], Bisector123[1], \\\n Bisector231[0], Bisector231[1])\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(ptInt2, ptInt3, center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector231[0], Bisector231[1], \\\n Bisector312[0], Bisector312[1])\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(ptInt3, ptInt1, center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector312[0], Bisector312[1], \\\n Bisector123[0], Bisector123[1])\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(ptInt1, ptInt2, center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n if len(circleList) == 0:\n return False\n \n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line2[0], line2[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n\n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line3[0], line3[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt3))\n\n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n\n\n #===========================================================================\n # from2ParLinesLineTanPts\n #===========================================================================\n def from2ParLinesLineTanPts(self, parLine1, parLine2, line3):\n \"\"\"\n setta le caratteristiche del cerchio attraverso 2 linee parallele e una terza linea non parallela:\n linea1 di tangenza (lista di 2 punti) parallela a linea2\n linea2 di tangenza (lista di 2 punti) parallela a linea1\n linea3 di tangenza (lista di 2 punti)\n \"\"\"\n circleList = []\n \n ptInt2 = qad_utils.getIntersectionPointOn2InfinityLines(parLine2[0], parLine2[1], \\\n line3[0], line3[1]) \n ptInt3 = qad_utils.getIntersectionPointOn2InfinityLines(line3[0], line3[1], \\\n parLine1[0], parLine1[1])\n\n if parLine1[0] == ptInt3:\n pt = parLine1[1]\n else:\n pt = parLine1[0] \n Bisector123 = qad_utils.getBisectorInfinityLine(pt, ptInt2, ptInt3)\n \n if parLine2[0] == ptInt2:\n pt = parLine2[1]\n else:\n pt = parLine2[0]\n Bisector312 = qad_utils.getBisectorInfinityLine(pt, ptInt3, ptInt2)\n \n # Punto di intersezione delle bisettrici = centro delle circonferenza\n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector123[0], Bisector123[1], \\\n Bisector312[0], Bisector312[1])\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(parLine1[0], parLine1[1], center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n # Bisettrici degli angoli esterni\n Bisector123 = Bisector123 + math.pi / 2\n Bisector312 = Bisector312 + math.pi / 2 \n # Punto di intersezione delle bisettrici = centro delle circonferenza\n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector123[0], Bisector123[1], \\\n Bisector312[0], Bisector312[1])\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(parLine1[0], parLine1[1], center)\n radius = qad_utils.getDistance(center, ptPer)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n\n return circleList\n \n \n #============================================================================\n # fromLineLineCircleTanPts\n #============================================================================\n def fromLineLineCircleTanPts(self, line1, pt1, line2, pt2, circle, pt3):\n \"\"\"\n setta le caratteristiche del cerchio attraverso tre linee:\n linea1 di tangenza (lista di 2 punti)\n punto di selezione linea1\n linea2 di tangenza (lista di 2 punti)\n punto di selezione linea2\n cerchio di tangenza (oggetto QadCircle)\n punto di selezione cerchio\n \"\"\"\n circleList = []\n \n circleList.extend(qad_utils.solveCircleTangentTo2LinesAndCircle(line1, line2, circle, -1, -1)) \n circleList.extend(qad_utils.solveCircleTangentTo2LinesAndCircle(line1, line2, circle, -1, 1))\n circleList.extend(qad_utils.solveCircleTangentTo2LinesAndCircle(line1, line2, circle, 1, -1))\n circleList.extend(qad_utils.solveCircleTangentTo2LinesAndCircle(line1, line2, circle, 1, 1))\n\n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line2[0], line2[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n \n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle.center)\n if qad_utils.getDistance(circleTan.center, circle.center) < circle.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt3))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n \n\n #============================================================================\n # fromLineCircleCircleTanPts\n #============================================================================\n def fromLineCircleCircleTanPts(self, line, pt, circle1, pt1, circle2, pt2):\n \"\"\"\n setta le caratteristiche del cerchio attraverso tre linee:\n linea di tangenza (lista di 2 punti)\n punto di selezione linea\n cerchio1 di tangenza (oggetto QadCircle)\n punto di selezione cerchio1\n cerchio2 di tangenza (oggetto QadCircle)\n punto di selezione cerchio2\n \"\"\"\n circleList = []\n \n circleList.extend(qad_utils.solveCircleTangentToLineAnd2Circles(line, circle1, circle2, -1, -1)) \n circleList.extend(qad_utils.solveCircleTangentToLineAnd2Circles(line, circle1, circle2, -1, 1))\n circleList.extend(qad_utils.solveCircleTangentToLineAnd2Circles(line, circle1, circle2, 1, -1))\n circleList.extend(qad_utils.solveCircleTangentToLineAnd2Circles(line, circle1, circle2, 1, 1))\n\n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line[0], line[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt))\n\n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle1.center)\n if qad_utils.getDistance(circleTan.center, circle1.center) < circle1.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n \n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle2.center)\n if qad_utils.getDistance(circleTan.center, circle2.center) < circle2.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n \n\n #============================================================================\n # fromCircleCircleCircleTanPts\n #============================================================================\n def fromCircleCircleCircleTanPts(self, circle1, pt1, circle2, pt2, circle3, pt3):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso tre linee:\n cerchio1 di tangenza (oggetto QadCircle)\n punto di selezione cerchio1\n cerchio2 di tangenza (oggetto QadCircle)\n punto di selezione cerchio2\n cerchio3 di tangenza (oggetto QadCircle)\n punto di selezione cerchio3\n \"\"\"\n circleList = []\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, -1, -1, -1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, -1, -1, 1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, -1, 1, -1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, -1, 1, 1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, 1, -1, -1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, 1, -1, 1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, 1, 1, -1)\n if circle is not None:\n circleList.append(circle)\n circle = qad_utils.solveApollonius(circle1, circle2, circle3, 1, 1, 1)\n if circle is not None:\n circleList.append(circle)\n\n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle1.center)\n if qad_utils.getDistance(circleTan.center, circle1.center) < circle1.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle2.center)\n if qad_utils.getDistance(circleTan.center, circle2.center) < circle2.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n\n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle3.center)\n if qad_utils.getDistance(circleTan.center, circle3.center) < circle3.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt3))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n\n\n #============================================================================\n # from2IntPts1TanPt\n #============================================================================\n def from2IntPts1TanPt(self, pt1, pt2, geom, pt):\n \"\"\"\n setta le caratteristiche del cerchio attraverso\n 2 punti di intersezione ed un oggetto di tangenza:\n punto1 di intersezione\n punto2 di intersezione\n geometria di tangenza (linea, arco o cerchio)\n punto di selezione geometria\n \"\"\"\n obj = qad_utils.whatGeomIs(pt, geom)\n \n if obj is None:\n return False\n\n if (type(obj) == list or type(obj) == tuple):\n objType = \"LINE\"\n else:\n objType = obj.whatIs()\n if objType == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj.center, obj.radius)\n obj = circle\n objType = \"CIRCLE\" \n \n if objType == \"LINE\":\n return self.from2IntPtsLineTanPts(pt1, pt2, obj, pt)\n elif objType == \"CIRCLE\":\n return self.from2IntPtsCircleTanPts(pt1, pt2, obj, pt)\n \n return False\n\n \n #===========================================================================\n # from2IntPtsLineTanPts\n #===========================================================================\n def from2IntPtsLineTanPts(self, pt1, pt2, line, pt, AllCircles = False):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso 2 punti di intersezione e una linea tangente:\n punto1 di intersezione\n punto2 di intersezione\n linea di tangenza (lista di 2 punti)\n punto di selezione linea\n il parametro AllCircles se = True fa restituire tutti i cerchi e non sono quello più vicino a pt1 e pt2\n \"\"\"\n circleList = []\n \n pt1Line = line[0]\n pt2Line = line[1]\n\n A = (pt1[0] * pt1[0]) + (pt1[1] * pt1[1])\n B = (pt2[0] * pt2[0]) + (pt2[1] * pt2[1])\n\n E = - pt1[0] + pt2[0]\n F = pt1[1] - pt2[1]\n if F == 0:\n if AllCircles == True:\n return circleList\n else:\n return False\n\n G = (-A + B) / F \n H = E / F\n \n if pt1Line[0] - pt2Line[0] == 0:\n # la linea é verticale\n e = pt1Line[0] \n I = H * H\n if I == 0:\n if AllCircles == True:\n return circleList\n else:\n return False\n J = (2 * G * H) - (4 * e) + (4 * pt2[0]) + (4 * H * pt2[1])\n K = (G * G) - (4 * e * e) + (4 * B) + (4 * G * pt2[1])\n else:\n # equazione della retta line -> y = dx + e\n d = (pt2Line[1] - pt1Line[1]) / (pt2Line[0] - pt1Line[0])\n e = - d * pt1Line[0] + pt1Line[1] \n C = 4 * (1 + d * d)\n D = 2 * d * e\n d2 = d * d\n I = 1 + (H * H * d2) + 2 * H * d\n if I == 0:\n if AllCircles == True:\n return circleList\n else:\n return False\n J = (2 * d2 * G * H) + (2 * D) + (2 * D * H * d) + (2 * G * d) - (e * C * H) + (pt2[0] * C) + H * pt2[1] * C\n K = (G * G * d2) + (2 * D * G * d) + (D * D) - (C * e * e) - (C * G * e) + (B * C) + (G * pt2[1] * C)\n \n L = (J * J) - (4 * I * K)\n if L < 0:\n if AllCircles == True:\n return circleList\n else:\n return False\n \n a1 = (-J + math.sqrt(L)) / (2 * I)\n b1 = (a1 * H) + G\n c1 = - B - (a1 * pt2[0]) - (b1 * pt2[1])\n center = QgsPoint()\n center.setX(- (a1 / 2))\n center.setY(- (b1 / 2))\n radius = math.sqrt((a1 * a1 / 4) + (b1 * b1 / 4) - c1)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n a2 = (-J - math.sqrt(L)) / (2 * I) \n b2 = (a2 * H) + G\n c2 = - B - (a2 * pt2[0]) - (b2 * pt2[1])\n center.setX(- (a2 / 2))\n center.setY(- (b2 / 2))\n radius = math.sqrt((a2 * a2 / 4) + (b2 * b2 / 4) - c2)\n circle = QadCircle()\n circle.set(center, radius)\n circleList.append(circle)\n \n if AllCircles == True:\n return circleList\n \n if len(circleList) == 0:\n return False\n\n minDist = sys.float_info.max\n for circle in circleList: \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line[0], line[1], circle.center)\n dist = qad_utils.getDistance(ptInt, pt)\n \n if dist < minDist: # mediamente più vicino\n minDist = dist\n self.center = circle.center\n self.radius = circle.radius\n \n return True\n\n \n #===========================================================================\n # from2IntPtsCircleTanPts\n #===========================================================================\n def from2IntPtsCircleTanPts(self, pt1, pt2, circle, pt):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso 2 punti di intersezione e una cerchio tangente:\n punto1 di intersezione\n punto2 di intersezione\n cerchio di tangenza (oggetto QadCircle)\n punto di selezione cerchio\n \"\"\"\n # http://www.batmath.it/matematica/a_apollonio/ppc.htm\n circleList = []\n \n if pt1 == pt2:\n return False\n \n dist1 = qad_utils.getDistance(pt1, circle.center) # distanza del punto 1 dal centro\n dist2 = qad_utils.getDistance(pt2, circle.center) # distanza del punto 2 dal centro\n\n # entrambi i punti devono essere esterni o interni a circle\n if (dist1 > circle.radius and dist2 < circle.radius) or \\\n (dist1 < circle.radius and dist2 > circle.radius):\n return False \n \n if dist1 == dist2: # l'asse di pt1 e pt2 passa per il centro di circle\n if dist1 == circle.radius: # entrambi i punti sono sulla circonferenza di circle\n return False \n axis = qad_utils.getInfinityLinePerpOnMiddle(pt1, pt2) # asse di pt1 e pt2\n intPts = circle.getIntersectionPointsWithInfinityLine(axis) # punti di intersezione tra l'asse e circle\n for intPt in intPts:\n circleTan = QadCircle()\n if circleTan.from3Pts(pt1, pt2, intPt) == True:\n circleList.append(circleTan) \n elif dist1 > circle.radius and dist2 > circle.radius : # entrambi i punti sono esterni a circle\n # mi ricavo una qualunque circonferenza passante per p1 e p2 ed intersecante circle\n circleInt = QadCircle()\n if circleInt.from3Pts(pt1, pt2, circle.center) == False:\n return False \n intPts = circle.getIntersectionPointsWithCircle(circleInt)\n intPt = qad_utils.getIntersectionPointOn2InfinityLines(pt1, pt2, intPts[0], intPts[1])\n tanPts = circle.getTanPoints(intPt)\n for tanPt in tanPts:\n circleTan = QadCircle()\n if circleTan.from3Pts(pt1, pt2, tanPt) == True:\n circleList.append(circleTan) \n elif dist1 < circle.radius and dist2 < circle.radius : # entrambi i punti sono interni a circle\n # mi ricavo una qualunque circonferenza passante per p1 e p2 ed intersecante circle\n ptMiddle = qad_utils.getMiddlePoint(pt1, pt2)\n angle = qad_utils.getAngleBy2Pts(pt1, pt2) + math.pi / 2\n pt3 = qad_utils.getPolarPointByPtAngle(ptMiddle, angle, 2 * circle.radius)\n circleInt = QadCircle()\n if circleInt.from3Pts(pt1, pt2, pt3) == False:\n return False \n intPts = circle.getIntersectionPointsWithCircle(circleInt)\n intPt = qad_utils.getIntersectionPointOn2InfinityLines(pt1, pt2, intPts[0], intPts[1])\n tanPts = circle.getTanPoints(intPt)\n for tanPt in tanPts:\n circleTan = QadCircle()\n if circleTan.from3Pts(pt1, pt2, tanPt) == True:\n circleList.append(circleTan)\n elif dist1 == radius: # il punto1 sulla circonferenza di circle\n # una sola circonferenza avente come centro l'intersezione tra l'asse pt1 e pt2 e la retta\n # passante per il centro di circle e pt1\n axis = qad_utils.getInfinityLinePerpOnMiddle(pt1, pt2) # asse di pt1 e pt2 \n intPt = qad_utils.getIntersectionPointOn2InfinityLines(axis[0], axis[1], circle.center, pt1)\n circleTan = QadCircle()\n circleTan.set(intPt, qad_utils.getDistance(pt1, intPt))\n circleList.append(circleTan)\n elif dist2 == radius: # il punto3 é sulla circonferenza di circle\n # una sola circonferenza avente come centro l'intersezione tra l'asse pt1 e pt2 e la retta\n # passante per il centro di circle e pt2\n axis = qad_utils.getInfinityLinePerpOnMiddle(pt1, pt2) # asse di pt1 e pt2 \n intPt = qad_utils.getIntersectionPointOn2InfinityLines(axis[0], axis[1], circle.center, pt2)\n circleTan = QadCircle()\n circleTan.set(intPt, qad_utils.getDistance(pt2, intPt))\n circleList.append(circleTan) \n \n if len(circleList) == 0:\n return False\n\n minDist = sys.float_info.max\n for circleTan in circleList: \n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle.center)\n if qad_utils.getDistance(circleTan.center, circle.center) < circle.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n dist = qad_utils.getDistance(ptInt, pt)\n \n if dist < minDist: # mediamente più vicino\n minDist = dist\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n \n\n #============================================================================\n # from1IntPt2TanPts\n #============================================================================\n def from1IntPt2TanPts(self, pt, geom1, pt1, geom2, pt2):\n \"\"\"\n setta le caratteristiche del cerchio attraverso\n 1 punti di intersezione e 2 oggetti di tangenza:\n punto di intersezione\n geometria1 di tangenza (linea, arco o cerchio)\n punto di selezione geometria1\n geometria2 di tangenza (linea, arco o cerchio)\n punto di selezione geometria2 \n \"\"\"\n obj1 = qad_utils.whatGeomIs(pt1, geom1)\n obj2 = qad_utils.whatGeomIs(pt2, geom2)\n \n if (obj1 is None) or (obj2 is None):\n return False\n\n if (type(obj1) == list or type(obj1) == tuple):\n obj1Type = \"LINE\"\n else:\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj1 = circle\n obj1Type = \"CIRCLE\" \n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj2 = circle\n obj2Type = \"CIRCLE\" \n \n if obj1Type == \"LINE\":\n if obj2Type == \"LINE\":\n return self.from1IntPtLineLineTanPts(pt, obj1, pt1, obj2, pt2)\n elif obj2Type == \"CIRCLE\":\n return self.from1IntPtLineCircleTanPts(pt, obj1, pt1, obj2, pt2)\n elif obj1Type == \"CIRCLE\":\n if obj2Type == \"LINE\":\n return self.from1IntPtLineCircleTanPts(pt, obj2, pt2, obj1, pt1)\n elif obj2Type == \"CIRCLE\":\n return self.from1IntPtCircleCircleTanPts(pt, obj1, pt1, obj2, pt2)\n \n return False\n\n \n #===========================================================================\n # from1IntPtLineLineTanPts\n #===========================================================================\n def from1IntPtLineLineTanPts(self, pt, line1, pt1, line2, pt2, AllCircles = False):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso 1 punti di intersezione e due linee tangenti:\n punto di intersezione \n linea1 di tangenza (lista di 2 punti)\n punto di selezione linea1\n linea2 di tangenza (lista di 2 punti)\n punto di selezione linea2\n il parametro AllCircles se = True fa restituire tutti i cerchi e non sono quello più vicino a pt1 e pt2\n \"\"\"\n # http://www.batmath.it/matematica/a_apollonio/prr.htm\n circleList = []\n \n # verifico se le rette sono parallele\n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(line1[0], line1[1], \\\n line2[0], line2[1])\n if ptInt is None: # le rette sono parallele\n # Se le rette sono parallele il problema ha soluzioni solo se il punto \n # é non esterno alla striscia individuata dalle due rette e basta considerare \n # il simmetrico di A rispetto alla bisettrice della striscia.\n ptPerp = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], line2[0])\n angle = qad_utils.getAngleBy2Pts(line2[0], ptPerp)\n dist = qad_utils.getDistance(line2[0], ptPerp)\n pt1ParLine = qad_utils.getPolarPointByPtAngle(line2[0], angle, dist / 2)\n angle = angle + math.pi / 2\n pt2ParLine = qad_utils.getPolarPointByPtAngle(pt1ParLine, angle, dist)\n\n ptPerp = qad_utils.getPerpendicularPointOnInfinityLine(pt1ParLine, pt2ParLine, pt)\n dist = qad_utils.getDistance(pt, ptPerp)\n \n # trovo il punto simmetrico\n angle = qad_utils.getAngleBy2Pts(pt, ptPerp)\n ptSymmetric = qad_utils.getPolarPointByPtAngle(pt, angle, dist * 2)\n return self.from2IntPtsLineTanPts(pt, ptSymmetric, line1, pt1, AllCircles)\n else: # le rette non sono parallele\n if ptInt == pt:\n return False\n # se il punto é sulla linea1 o sulla linea2\n ptPerp1 = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], pt)\n ptPerp2 = qad_utils.getPerpendicularPointOnInfinityLine(line2[0], line2[1], pt)\n if ptPerp1 == pt or ptPerp2 == pt:\n # Se le rette sono incidenti ed il punto appartiene ad una delle due la costruzione\n # é quasi immediata: basta tracciare le bisettrici dei due angoli individuati dalle rette \n # e la perpendicolare per pt alla retta cui appartiene pt stesso. Si avranno due circonferenze. \n \n if ptPerp1 == pt: # se il punto é sulla linea1\n angle = qad_utils.getAngleBy2Pts(line2[0], line2[1])\n ptLine = qad_utils.getPolarPointByPtAngle(ptInt, angle, 10)\n Bisector1 = qad_utils.getBisectorInfinityLine(pt, ptInt, ptLine)\n ptLine = qad_utils.getPolarPointByPtAngle(ptInt, angle + math.pi, 10)\n Bisector2 = qad_utils.getBisectorInfinityLine(pt, ptInt, ptLine)\n angle = qad_utils.getAngleBy2Pts(line1[0], line1[1])\n ptPerp = qad_utils.getPolarPointByPtAngle(pt, angle + math.pi / 2, 10) \n else: # se il punto é sulla linea2\n angle = qad_utils.getAngleBy2Pts(line1[0], line1[1])\n ptLine = qad_utils.getPolarPointByPtAngle(ptInt, angle, 10)\n Bisector1 = qad_utils.getBisectorInfinityLine(pt, ptInt, ptLine)\n ptLine = qad_utils.getPolarPointByPtAngle(ptInt, angle + math.pi, 10)\n Bisector2 = qad_utils.getBisectorInfinityLine(pt, ptInt, ptLine)\n angle = qad_utils.getAngleBy2Pts(line2[0], line2[1])\n ptPerp = qad_utils.getPolarPointByPtAngle(pt, angle + math.pi / 2, 10)\n \n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector1[0], Bisector1[1], \\\n pt, ptPerp)\n radius = qad_utils.getDistance(pt, center)\n circleTan = QadCircle()\n circleTan.set(center, radius)\n circleList.append(circleTan) \n\n center = qad_utils.getIntersectionPointOn2InfinityLines(Bisector2[0], Bisector2[1], \\\n pt, ptPerp)\n radius = qad_utils.getDistance(pt, center)\n circleTan = QadCircle()\n circleTan.set(center, radius)\n circleList.append(circleTan) \n else: \n # Bisettrice dell'angolo interno del triangolo avente come vertice i punti di intersezione delle rette\n Bisector = qad_utils.getBisectorInfinityLine(ptPerp1, ptInt, ptPerp2)\n \n ptPerp = qad_utils.getPerpendicularPointOnInfinityLine(Bisector[0], Bisector[1], pt)\n dist = qad_utils.getDistance(pt, ptPerp)\n \n # trovo il punto simmetrico\n angle = qad_utils.getAngleBy2Pts(pt, ptPerp)\n ptSymmetric = qad_utils.getPolarPointByPtAngle(pt, angle, dist * 2)\n return self.from2IntPtsLineTanPts(pt, ptSymmetric, line1, pt1, AllCircles)\n\n if AllCircles == True:\n return circleList\n \n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line2[0], line2[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n \n \n #============7===============================================================\n # from1IntPtLineCircleTanPts\n #===========================================================================\n def from1IntPtLineCircleTanPts(self, pt, line1, pt1, circle2, pt2, AllCircles = False):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso 1 punto di intersezione, 1 linea e 1 cerchio tangenti:\n punto di intersezione \n linea di tangenza (lista di 2 punti)\n punto di selezione linea\n cerchio di tangenza (oggetto QadCircle)\n punto di selezione cerchio\n il parametro AllCircles se = True fa restituire tutti i cerchi e non sono quello più vicino a pt1 e pt2\n \"\"\"\n # http://www.batmath.it/matematica/a_apollonio/prc.htm\n circleList = []\n \n # Sono dati un cerchio circle2, un punto pt ed una retta line1 nell'ipotesi che pt\n # non stia nè sulla retta line1 nè sul circolo.\n # Si vogliono trovare le circonferenze passanti per il punto e tangenti alla retta e al cerchio dato.\n # Il problema si può risolvere facilmente utilizzando un'inversione di centro pt e raggio qualunque.\n # Trovate le circonferenze inverse della retta data e del circolo dato, se ne trovano le tangenti comuni.\n # Le inverse di queste tangenti comuni sono le circonferenze cercate. \n\n if qad_utils.getYOnInfinityLine(line1[0], line1[1], pt.x()) == pt.y() or \\\n qad_utils.getDistance(pt, circle2.center) == circle2.radius:\n if AllCircles == True:\n return circleList\n else:\n return False\n \n c = QadCircle()\n c.set(pt, 10)\n \n circularInvLine = qad_utils.getCircularInversionOfLine(c, line1)\n circularInvCircle = qad_utils.getCircularInversionOfCircle(c, circle2)\n tangents = circularInvCircle.getTangentsWithCircle(circularInvLine)\n for tangent in tangents:\n circleList.append(qad_utils.getCircularInversionOfLine(c, tangent))\n \n if AllCircles == True:\n return circleList\n\n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n ptInt = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], circleTan.center)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle2.center)\n if qad_utils.getDistance(circleTan.center, circle2.center) < circle2.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n if AllCircles == True:\n return circleList\n else:\n return True\n\n\n #===========================================================================\n # from1IntPtCircleCircleTanPts\n #===========================================================================\n def from1IntPtCircleCircleTanPts(self, pt, circle1, pt1, circle2, pt2):\n \"\"\"\n setta le caratteristiche dei cerchi attraverso 1 punto di intersezione, 2 cerchi tangenti:\n punto di intersezione \n cerchio1 di tangenza (oggetto QadCircle)\n punto di selezione cerchio1\n cerchio2 di tangenza (oggetto QadCircle)\n punto di selezione cerchio2\n \"\"\"\n # http://www.batmath.it/matematica/a_apollonio/prc.htm\n circleList = []\n\n # Sono dati un punto pt e due circonferenze circle1 e circle2;\n # si devono determinare le circonferenze passanti per pt e tangenti alle due circonferenze.\n # Proponiamo una costruzione che utilizza l'inversione, in quanto ci pare la più elegante.\n # In realtà si potrebbe anche fare una costruzione utilizzando i centri di omotetia dei due cerchi dati\n # ma, nella sostanza, é solo un modo per mascherare l'uso dell'inversione.\n # Si considera un circolo di inversione di centro pt e raggio qualunque.\n # Si determinano i circoli inversi dei due circoli dati e le loro tangenti comuni.\n # Le circonferenze inverse di queste tangenti comuni sono quelle che soddisfano il problema. \n\n c = QadCircle()\n c.set(pt, 10)\n \n circularInvCircle1 = qad_utils.getCircularInversionOfCircle(c, circle1)\n circularInvCircle2 = qad_utils.getCircularInversionOfCircle(c, circle2)\n tangents = circularInvCircle1.getTangentsWithCircle(circularInvCircle2)\n for tangent in tangents:\n circleList.append(qad_utils.getCircularInversionOfLine(c, tangent))\n\n if len(circleList) == 0:\n return False\n\n AvgList = []\n Avg = sys.float_info.max\n for circleTan in circleList:\n del AvgList[:] # svuoto la lista\n \n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle1.center)\n if qad_utils.getDistance(circleTan.center, circle1.center) < circle1.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt1))\n\n angle = qad_utils.getAngleBy2Pts(circleTan.center, circle2.center)\n if qad_utils.getDistance(circleTan.center, circle2.center) < circle2.radius: # cerchio interno\n angle = angle + math.pi / 2\n ptInt = qad_utils.getPolarPointByPtAngle(circleTan.center, angle, circleTan.radius)\n AvgList.append(qad_utils.getDistance(ptInt, pt2))\n \n currAvg = qad_utils.numericListAvg(AvgList) \n if currAvg < Avg: # mediamente più vicino\n Avg = currAvg\n self.center = circleTan.center\n self.radius = circleTan.radius\n \n return True\n\n \n #============================================================================\n # fromDiamEnds\n #============================================================================\n def fromDiamEnds(self, startPt, endPt):\n \"\"\"\n setta le caratteristiche del cerchio attraverso i punti estremità del diametro:\n punto iniziale\n punto finale\n \"\"\"\n self.radius = qad_utils.getDistance(startPt, endPt) / 2\n if self.radius == 0:\n return False\n self.center = qad_utils.getMiddlePoint(startPt, endPt)\n return True\n \n\n #============================================================================\n # fromDiamEndsPtTanPt\n #============================================================================\n def fromDiamEndsPtTanPt(self, startPt, geom, pt):\n \"\"\"\n setta le caratteristiche del cerchio attraverso un punto di estremità del diametro e\n un oggetto di tangenza per l'altra estremità :\n punto iniziale\n geometria 1 di tangenza (linea, arco o cerchio)\n punto di selezione geometria 1\n \"\"\"\n obj = qad_utils.whatGeomIs(pt, geom)\n \n if (type(obj) == list or type(obj) == tuple):\n objType = \"LINE\"\n else:\n objType = obj.whatIs()\n if objType == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj.center, obj.radius)\n obj = circle\n objType = \"CIRCLE\"\n \n if objType == \"LINE\":\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(obj[0], obj[1], startPt)\n return self.fromDiamEnds(startPt, ptPer)\n elif objType == \"CIRCLE\": \n ptIntList = obj.getIntersectionPointsWithInfinityLine(startPt, obj.center) \n # scelgo il punto più vicino al punto pt\n ptTan = qad_utils.getNearestPoints(pt, ptIntList)[0]\n return self.fromDiamEnds(startPt, ptTan)\n \n\n #============================================================================\n # fromDiamEnds2TanPts\n #============================================================================\n def fromDiamEnds2TanPts(self, geom1, pt1, geom2, pt2):\n \"\"\"\n setta le caratteristiche del cerchio attraverso\n due oggetto di tangenza per le estremità del diametro:\n geometria1 di tangenza (linea, arco o cerchio)\n punto di selezione geometria1\n geometria2 di tangenza (linea, arco o cerchio)\n punto di selezione geometria2\n \"\"\"\n obj1 = qad_utils.whatGeomIs(pt1, geom1)\n obj2 = qad_utils.whatGeomIs(pt2, geom2)\n \n if (obj1 is None) or (obj2 is None):\n return False\n\n if (type(obj1) == list or type(obj1) == tuple):\n obj1Type = \"LINE\"\n else:\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj1 = circle\n obj1Type = \"CIRCLE\" \n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj2Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj2 = circle\n obj2Type = \"CIRCLE\" \n \n if obj1Type == \"LINE\":\n if obj2Type == \"LINE\":\n return False # Il diametro non può essere tangente a due linee\n elif obj2Type == \"CIRCLE\":\n return self.fromLineCircleTanPts(obj1, pt1, obj2, pt2)\n elif obj1Type == \"CIRCLE\":\n if obj2Type == \"LINE\":\n return self.fromLineCircleTanPts(obj2, pt2, obj1, pt1)\n elif obj2Type == \"CIRCLE\":\n return self.fromCircleCircleTanPts(obj1, pt1, obj2, pt2)\n \n return False\n \n\n #============================================================================\n # fromLineCircleTanPts\n #============================================================================\n def fromLineCircleTanPts(self, line, ptLine, circle, ptCircle):\n \"\"\"\n setta le caratteristiche del cerchio attraverso una linea, un cerchio di tangenza:\n linea di tangenza (lista di 2 punti)\n punto di selezione linea\n cerchio di tangenza (oggetto QadCircle)\n punto di selezione cerchio\n \"\"\"\n\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(line[0], line[1], circle.center)\n \n ptIntList = obj.getIntersectionPointsWithInfinityLine(ptPer, circle.center) \n # scelgo il punto più vicino al punto pt\n ptTan = qad_utils.getNearestPoints(pt, ptIntList)[0]\n return self.fromDiamEnds(ptPer, ptTan)\n \n\n #============================================================================\n # fromCircleCircleTanPts\n #============================================================================\n def fromCircleCircleTanPts(self, circle1, pt1, circle2, pt2):\n \"\"\"\n setta le caratteristiche del cerchio attraverso due cerchi di tangenza:\n cerchio1 di tangenza (oggetto QadCircle)\n punto di selezione cerchio1\n cerchio2 di tangenza (oggetto QadCircle)\n punto di selezione cerchio2\n \"\"\"\n\n ptIntList = circle1.getIntersectionPointsWithInfinityLine(circle1.center, circle2.center) \n # scelgo il punto più vicino al punto pt1\n ptTan1 = qad_utils.getNearestPoints(pt1, ptIntList)[0]\n \n ptIntList = circle2.getIntersectionPointsWithInfinityLine(circle1.center, circle2.center) \n # scelgo il punto più vicino al punto pt2\n ptTan2 = qad_utils.getNearestPoints(pt2, ptIntList)[0]\n \n return self.fromDiamEnds(ptTan1, ptTan2)\n \n \n #============================================================================\n # from2TanPtsRadius\n #============================================================================\n def from2TanPtsRadius(self, geom1, pt1, geom2, pt2, radius):\n \"\"\"\n setta le caratteristiche del cerchio attraverso 2 oggetti di tangenza e un raggio:\n geometria1 di tangenza (linea, arco o cerchio)\n punto di selezione geometria1\n oggetto2 di tangenza (linea, arco o cerchio)\n punto di selezione geometria2\n raggio\n \"\"\"\n obj1 = qad_utils.whatGeomIs(pt1, geom1)\n obj2 = qad_utils.whatGeomIs(pt2, geom2)\n \n if (obj1 is None) or (obj2 is None):\n return False\n\n if (type(obj1) == list or type(obj1) == tuple):\n obj1Type = \"LINE\"\n else:\n obj1Type = obj1.whatIs()\n if obj1Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj1.center, obj1.radius)\n obj1 = circle\n obj1Type = \"CIRCLE\" \n\n if (type(obj2) == list or type(obj2) == tuple):\n obj2Type = \"LINE\"\n else:\n obj2Type = obj2.whatIs()\n if obj1Type == \"ARC\": # se è arco lo trasformo in cerchio\n circle = QadCircle()\n circle.set(obj2.center, obj2.radius)\n obj2 = circle\n obj2Type = \"CIRCLE\" \n \n if obj1Type == \"LINE\":\n if obj2Type == \"LINE\":\n return self.fromLineLineTanPtsRadius(obj1, pt1, obj2, pt2, radius)\n elif obj2Type == \"CIRCLE\":\n return self.fromLineCircleTanPtsRadius(obj1, pt1, obj2, pt2, radius)\n elif obj1Type == \"CIRCLE\":\n if obj2Type == \"LINE\":\n return self.fromLineCircleTanPtsRadius(obj2, pt2, obj1, pt1, radius)\n elif obj2Type == \"CIRCLE\":\n return self.fromCircleCircleTanPtsRadius(obj1, pt1, obj2, pt2, radius)\n \n return False\n\n\n #============================================================================\n # fromLineLineTanPtsRadius\n #============================================================================\n def fromLineLineTanPtsRadius(self, line1, pt1, line2, pt2, radius):\n \"\"\"\n setta le caratteristiche del cerchio attraverso due linee di tangenza e un raggio:\n linea1 di tangenza (lista di 2 punti)\n punto di selezione linea1\n linea2 di tangenza (lista di 2 punti)\n punto di selezione linea2\n raggio\n \"\"\"\n \n # calcolo il punto medio tra i due punti di selezione\n ptMiddle = qad_utils.getMiddlePoint(pt1, pt2)\n\n # verifico se le rette sono parallele\n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(line1[0], line1[1], \\\n line2[0], line2[1])\n if ptInt is None: # le rette sono parallele\n ptPer = qad_utils.getPerpendicularPointOnInfinityLine(line1[0], line1[1], ptMiddle)\n if qad_utils.doubleNear(radius, qad_utils.getDistance(ptPer, ptMiddle)): \n self.center = ptMiddle\n self.radius = radius\n return True\n else:\n return False\n \n # angolo linea1\n angle = qad_utils.getAngleBy2Pts(line1[0], line1[1])\n # retta parallela da un lato della linea1 distante radius\n angle = angle + math.pi / 2\n pt1Par1Line1 = qad_utils.getPolarPointByPtAngle(line1[0], angle, radius)\n pt2Par1Line1 = qad_utils.getPolarPointByPtAngle(line1[1], angle, radius)\n # retta parallela dall'altro lato della linea1 distante radius\n angle = angle - math.pi\n pt1Par2Line1 = qad_utils.getPolarPointByPtAngle(line1[0], angle, radius)\n pt2Par2Line1 = qad_utils.getPolarPointByPtAngle(line1[1], angle, radius)\n\n # angolo linea2\n angle = qad_utils.getAngleBy2Pts(line2[0], line2[1])\n # retta parallela da un lato della linea2 distante radius\n angle = angle + math.pi / 2\n pt1Par1Line2 = qad_utils.getPolarPointByPtAngle(line2[0], angle, radius)\n pt2Par1Line2 = qad_utils.getPolarPointByPtAngle(line2[1], angle, radius)\n # retta parallela dall'altro lato della linea2 distante radius\n angle = angle - math.pi\n pt1Par2Line2 = qad_utils.getPolarPointByPtAngle(line2[0], angle, radius)\n pt2Par2Line2 = qad_utils.getPolarPointByPtAngle(line2[1], angle, radius)\n\n # calcolo le intersezioni\n ptIntList = []\n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(pt1Par1Line1, pt2Par1Line1, \\\n pt1Par1Line2, pt2Par1Line2)\n ptIntList.append(ptInt)\n \n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(pt1Par1Line1, pt2Par1Line1, \\\n pt1Par2Line2, pt2Par2Line2)\n ptIntList.append(ptInt)\n\n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(pt1Par2Line1, pt2Par2Line1, \\\n pt1Par1Line2, pt2Par1Line2)\n ptIntList.append(ptInt)\n\n ptInt = qad_utils.getIntersectionPointOn2InfinityLines(pt1Par2Line1, pt2Par2Line1, \\\n pt1Par2Line2, pt2Par2Line2)\n ptIntList.append(ptInt)\n\n # scelgo il punto più vicino al punto medio\n self.center = qad_utils.getNearestPoints(ptMiddle, ptIntList)[0]\n self.radius = radius\n return True\n \n\n #============================================================================\n # fromLineCircleTanPtsRadius\n #============================================================================\n def fromLineCircleTanPtsRadius(self, line, ptLine, circle, ptCircle, radius):\n \"\"\"\n setta le caratteristiche del cerchio attraverso una linea, un cerchio di tangenza e un raggio:\n linea di tangenza (lista di 2 punti)\n punto di selezione linea\n cerchio di tangenza (oggetto QadCircle)\n punto di selezione cerchio\n raggio\n \"\"\"\n\n # calcolo il punto medio tra i due punti di selezione\n ptMiddle = qad_utils.getMiddlePoint(ptLine, ptCircle)\n\n # angolo linea1\n angle = qad_utils.getAngleBy2Pts(line[0], line[1])\n # retta parallela da un lato della linea1 distante radius\n angle = angle + math.pi / 2\n pt1Par1Line = qad_utils.getPolarPointByPtAngle(line[0], angle, radius)\n pt2Par1Line = qad_utils.getPolarPointByPtAngle(line[1], angle, radius)\n # retta parallela dall'altro lato della linea1 distante radius\n angle = angle - math.pi\n pt1Par2Line = qad_utils.getPolarPointByPtAngle(line[0], angle, radius)\n pt2Par2Line = qad_utils.getPolarPointByPtAngle(line[1], angle, radius)\n \n # creo un cerchio con un raggio + grande\n circleTan = QadCircle()\n circleTan.set(circle.center, circle.radius + radius)\n ptIntList = circleTan.getIntersectionPointsWithInfinityLine(pt1Par1Line, pt2Par1Line)\n ptIntList2 = circleTan.getIntersectionPointsWithInfinityLine(pt1Par2Line, pt2Par2Line)\n ptIntList.extend(ptIntList2)\n\n if len(ptIntList) == 0: # nessuna intersezione\n return False\n \n # scelgo il punto più vicino al punto medio\n self.center = qad_utils.getNearestPoints(ptMiddle, ptIntList)[0]\n self.radius = radius\n return True\n\n\n #============================================================================\n # fromCircleCircleTanPtsRadius\n #============================================================================\n def fromCircleCircleTanPtsRadius(self, circle1, pt1, circle2, pt2, radius):\n \"\"\"\n setta le caratteristiche del cerchio attraverso due cerchi di tangenza e un raggio:\n cerchio1 di tangenza (oggetto QadCircle)\n punto di selezione cerchio1\n cerchio2 di tangenza (oggetto QadCircle)\n punto di selezione cerchio2\n raggio\n \"\"\"\n\n # calcolo il punto medio tra i due punti di selezione\n ptMiddle = qad_utils.getMiddlePoint(pt1, pt2)\n \n # creo due cerchi con un raggio + grande\n circle1Tan = QadCircle()\n circle1Tan.set(circle1.center, circle1.radius + radius)\n circle2Tan = QadCircle()\n circle2Tan.set(circle2.center, circle2.radius + radius)\n ptIntList = circle1Tan.getIntersectionPointsWithCircle(circle2Tan)\n\n if len(ptIntList) == 0: # nessuna intersezione\n return False\n \n # scelgo il punto più vicino al punto medio\n self.center = qad_utils.getNearestPoints(ptMiddle, ptIntList)[0]\n self.radius = radius\n return True\n\n\n#===============================================================================\n# QadCircleList lista di cerchi class\n#===============================================================================\nclass QadCircleList():\n def __init__(self):\n self.circleList = [] # lista dei cerchi\n self.startEndVerticesList = [] # lista degli estremi (posizioni dei vertici iniziali e finali)\n\n def clear(self):\n del self.circleList[:] # svuoto la lista\n del self.startEndVerticesList[:] # svuoto la lista\n\n\n #============================================================================\n # fromPoints\n #============================================================================\n def fromPoints(self, points, atLeastNSegment = None):\n \"\"\"\n setta la lista deg cerchi e degli estremi leggendo una sequenza di punti\n ritorna il numero dei cerchi trovati\n \"\"\"\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n self.clear()\n startVertex = 0\n circle = QadCircle()\n startEndVertices = circle.fromPolyline(points, startVertex, _atLeastNSegment)\n while startEndVertices is not None:\n _circle = QadCircle(circle) # ne faccio una copia\n self.circleList.append(_circle)\n self.startEndVerticesList.append(startEndVertices)\n startVertex = startEndVertices[1] # l'ultimo punto del cerchio\n startEndVertices = circle.fromPolyline(points, startVertex, _atLeastNSegment) \n\n return len(self.circleList)\n\n\n #============================================================================\n # fromGeom\n #============================================================================\n def fromGeom(self, geom, atLeastNSegment = None):\n \"\"\"\n setta la lista dei cerchi e degli estremi leggendo una geometria\n ritorna il numero di cerchi trovati\n \"\"\"\n if atLeastNSegment is None:\n _atLeastNSegment = QadVariables.get(QadMsg.translate(\"Environment variables\", \"CIRCLEMINSEGMENTQTY\"), 12)\n else:\n _atLeastNSegment = atLeastNSegment\n \n self.clear()\n circle = QadCircle()\n incremental = 0 \n # riduco in polilinee\n geoms = qad_utils.asPointOrPolyline(geom)\n for g in geoms:\n points = g.asPolyline() # vettore di punti\n startVertex = 0\n startEndVertices = circle.fromPolyline(points, startVertex, _atLeastNSegment)\n while startEndVertices is not None:\n _circle = QadCircle(circle) # ne faccio una copia\n self.circleList.append(_circle)\n self.startEndVerticesList.append([startEndVertices[0] + incremental, startEndVertices[1] + incremental])\n startVertex = startEndVertices[1] # l'ultimo punto del cerchio\n startEndVertices = circle.fromPolyline(points, startVertex, _atLeastNSegment)\n \n incremental = len(points) - 1\n\n return len(self.circleList)\n\n #============================================================================\n # fromGeom\n #============================================================================\n def circleAt(self, iVertex):\n \"\"\"\n cerca se esiste un cerchio al vertice <iVertex>\n restituisce una lista con <cerchio>, <lista con punto iniziale e finale>\n oppure None se cerchio non trovato\n \"\"\"\n i = 0\n for startEndVertices in self.startEndVerticesList:\n if iVertex >= startEndVertices[0] and iVertex <= startEndVertices[1]:\n return self.circleList[i], startEndVertices\n i = i + 1\n \n return None\n"
},
{
"alpha_fraction": 0.6376456022262573,
"alphanum_fraction": 0.6404046416282654,
"avg_line_length": 50.625328063964844,
"blob_id": "55daa21fcb5ec66b1e1a32635ce848234da4ece1",
"content_id": "ed66479bf1dd4151ca4462e39f3bf29c6a8879dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 19576,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 379,
"path": "/qad_arc_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool di richiesta di un punto in ambito del comando arco\n \n -------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_arc import *\nfrom qad_rubberband import QadRubberBand\nfrom qad_highlight import QadHighlight\n\n\n#===============================================================================\n# Qad_arc_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_arc_maptool_ModeEnum():\n # noto niente si richiede il primo punto\n NONE_KNOWN_ASK_FOR_START_PT = 1 \n # noto il punto iniziale dell'arco si richiede il secondo punto\n START_PT_KNOWN_ASK_FOR_SECOND_PT = 2 \n # noti il punto iniziale e il secondo punto dell'arco si richiede il punto finale\n START_SECOND_PT_KNOWN_ASK_FOR_END_PT = 3 \n # noto il punto iniziale dell'arco si richiede il centro\n START_PT_KNOWN_ASK_FOR_CENTER_PT = 4 \n # noti il punto iniziale e il centro dell'arco si richiede il punto finale\n START_CENTER_PT_KNOWN_ASK_FOR_END_PT = 5 \n # noti il punto iniziale e il centro dell'arco si richiede l'angolo inscritto\n START_CENTER_PT_KNOWN_ASK_FOR_ANGLE = 6 \n # noti il punto iniziale e il centro dell'arco si richiede la lunghezza della corda\n START_CENTER_PT_KNOWN_ASK_FOR_CHORD = 7\n # noto il punto iniziale dell'arco si richiede il punto finale\n START_PT_KNOWN_ASK_FOR_END_PT = 8 \n # noti il punto iniziale e finale dell'arco si richiede il centro\n START_END_PT_KNOWN_ASK_FOR_CENTER = 9\n # noti il punto iniziale e finale dell'arco si richiede l'angolo inscritto\n START_END_PT_KNOWN_ASK_FOR_ANGLE = 10\n # noti il punto iniziale e finale dell'arco si richiede la direzione della tangente al punto iniziale\n START_END_PT_KNOWN_ASK_FOR_TAN = 11\n # noti il punto iniziale e finale dell'arco si richiede il raggio\n START_END_PT_KNOWN_ASK_FOR_RADIUS = 12 \n # noto niente si richiede il centro\n NONE_KNOWN_ASK_FOR_CENTER_PT = 13\n # noto il centro dell'arco si richiede il punto iniziale\n CENTER_PT_KNOWN_ASK_FOR_START_PT = 14 \n # noti il punto iniziale e la tangente al punto iniziale si richiede il punto finale\n START_PT_TAN_KNOWN_ASK_FOR_END_PT = 15\n # noto il punto iniziale dell'arco si richiede l'angolo inscritto\n START_PT_KNOWN_ASK_FOR_ANGLE = 16 \n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il punto finale\n START_PT_ANGLE_KNOWN_ASK_FOR_END_PT = 17 \n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il centro\n START_PT_ANGLE_KNOWN_ASK_FOR_CENTER_PT = 18\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il raggio\n START_PT_ANGLE_KNOWN_ASK_FOR_RADIUS = 19\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il secondo punto per misurare il raggio\n START_PT_ANGLE_KNOWN_ASK_FOR_SECONDPTRADIUS = 20\n # noti il punto iniziale, l'angolo inscritto e il raggio dell'arco si richiede la direzione della corda\n START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION = 21\n # noti il punto iniziale e il raggio dell'arco si richiede il punto finale\n START_PT_RADIUS_KNOWN_ASK_FOR_END_PT = 22 \n\n\n#===============================================================================\n# Qad_arc_maptool class\n#===============================================================================\nclass Qad_arc_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.arcStartPt = None\n self.arcSecondPt = None\n self.arcEndPt = None\n self.arcCenterPt = None\n self.arcTanOnStartPt = None\n self.arcAngle = None\n self.arcStartPtForRadius = None\n self.arcRadius = None\n self.__rubberBand = QadRubberBand(self.canvas)\n\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__rubberBand.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__rubberBand.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__rubberBand.reset()\n self.mode = None\n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__rubberBand.reset()\n \n result = False\n arc = QadArc() \n \n # noti il primo e il secondo punto dell'arco si richiede il terzo punto\n if self.mode == Qad_arc_maptool_ModeEnum.START_SECOND_PT_KNOWN_ASK_FOR_END_PT:\n result = arc.fromStartSecondEndPts(self.arcStartPt, self.arcSecondPt, self.tmpPoint)\n # noti il primo punto e il centro dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_END_PT:\n result = arc.fromStartCenterEndPts(self.arcStartPt, self.arcCenterPt, self.tmpPoint)\n # noti il primo punto e il centro dell'arco si richiede l'angolo inscritto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_ANGLE:\n angle = qad_utils.getAngleBy2Pts(self.arcCenterPt, self.tmpPoint)\n result = arc.fromStartCenterPtsAngle(self.arcStartPt, self.arcCenterPt, angle)\n # noti il primo punto e il centro dell'arco si richiede la lunghezza della corda\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_CHORD: \n chord = qad_utils.getDistance(self.arcStartPt, self.tmpPoint)\n result = arc.fromStartCenterPtsChord(self.arcStartPt, self.arcCenterPt, chord)\n # noti il punto iniziale e finale dell'arco si richiede il centro\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_CENTER: \n result = arc.fromStartCenterEndPts(self.arcStartPt, self.tmpPoint, self.arcEndPt)\n # noti il punto iniziale e finale dell'arco si richiede l'angolo inscritto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_ANGLE: \n angle = qad_utils.getAngleBy2Pts(self.arcStartPt, self.tmpPoint)\n result = arc.fromStartEndPtsAngle(self.arcStartPt, self.arcEndPt, angle)\n # noti il punto iniziale e finale dell'arco si richiede la direzione della tangente\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_TAN: \n tan = qad_utils.getAngleBy2Pts(self.arcStartPt, self.tmpPoint)\n result = arc.fromStartEndPtsTan(self.arcStartPt, self.arcEndPt, tan)\n # noti il punto iniziale e finale dell'arco si richiede il raggio\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_RADIUS: \n radius = qad_utils.getDistance(self.arcEndPt, self.tmpPoint)\n result = arc.fromStartEndPtsRadius(self.arcStartPt, self.arcEndPt, radius)\n # noti il punto iniziale e la tangente al punto iniziale si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_TAN_KNOWN_ASK_FOR_END_PT: \n result = arc.fromStartEndPtsTan(self.arcStartPt, self.tmpPoint, self.arcTanOnStartPt) \n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_END_PT: \n result = arc.fromStartEndPtsAngle(self.arcStartPt, self.tmpPoint, self.arcAngle)\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il centro\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_CENTER_PT: \n result = arc.fromStartCenterPtsAngle(self.arcStartPt, self.tmpPoint, self.arcAngle)\n # noti il punto iniziale, l'angolo inscritto e il raggio dell'arco si richiede la direzione della corda\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION: \n chordDirection = qad_utils.getAngleBy2Pts(self.arcStartPt, self.tmpPoint)\n result = arc.fromStartPtAngleRadiusChordDirection(self.arcStartPt, self.arcAngle, \\\n self.arcRadius, chordDirection)\n # noti il punto iniziale e il raggio dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_RADIUS_KNOWN_ASK_FOR_END_PT: \n result = arc.fromStartEndPtsRadius(self.arcStartPt, self.tmpPoint, self.arcRadius)\n \n if result == True:\n points = arc.asPolyline()\n \n if points is not None:\n self.__rubberBand.setLine(points)\n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__rubberBand.show()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__rubberBand.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n # noto niente si richiede il primo punto\n if self.mode == Qad_arc_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_START_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il primo punto dell'arco si richiede il secondo punto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_SECOND_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il primo e il secondo punto dell'arco si richiede il terzo punto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_SECOND_PT_KNOWN_ASK_FOR_END_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il primo punto dell'arco si richiede il centro \n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_CENTER_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il primo punto e il centro dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_END_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcCenterPt)\n # noti il primo punto e il centro dell'arco si richiede l'angolo inscritto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_ANGLE: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcCenterPt)\n # noti il primo punto e il centro dell'arco si richiede la lunghezza della corda\n elif self.mode == Qad_arc_maptool_ModeEnum.START_CENTER_PT_KNOWN_ASK_FOR_CHORD: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noto il punto iniziale dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_END_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e finale dell'arco si richiede il centro\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_CENTER: \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noti il punto iniziale e finale dell'arco si richiede l'angolo inscritto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_ANGLE: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e finale dell'arco si richiede la direzione della tangente\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_TAN: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e finale dell'arco si richiede il raggio\n elif self.mode == Qad_arc_maptool_ModeEnum.START_END_PT_KNOWN_ASK_FOR_RADIUS: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE) \n self.setStartPoint(self.arcEndPt)\n # noto niente si richiede il centro\n elif self.mode == Qad_arc_maptool_ModeEnum.NONE_KNOWN_ASK_FOR_CENTER_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il centro dell'arco si richiede il punto iniziale\n elif self.mode == Qad_arc_maptool_ModeEnum.CENTER_PT_KNOWN_ASK_FOR_START_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE) \n self.setStartPoint(self.arcCenterPt)\n # noti il punto iniziale e la tangente al punto iniziale si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_TAN_KNOWN_ASK_FOR_END_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE) \n self.setStartPoint(self.arcStartPt)\n # noto il punto iniziale dell'arco si richiede l'angolo inscritto\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_KNOWN_ASK_FOR_ANGLE:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_END_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il centro\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_CENTER_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il raggio\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_RADIUS: \n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noti il punto iniziale e l'angolo inscritto dell'arco si richiede il secondo punto per misurare il raggio\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_KNOWN_ASK_FOR_SECONDPTRADIUS: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPtForRadius)\n # noti il punto iniziale, l'angolo inscritto e il raggio dell'arco si richiede la direzione della corda\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_ANGLE_RADIUS_KNOWN_ASK_FOR_CHORDDIRECTION: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n # noti il punto iniziale e il raggio dell'arco si richiede il punto finale\n elif self.mode == Qad_arc_maptool_ModeEnum.START_PT_RADIUS_KNOWN_ASK_FOR_END_PT: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.arcStartPt)\n \n\n\n#===============================================================================\n# Qad_scale_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_gripChangeArcRadius_maptool_ModeEnum():\n # si richiede il punto base\n ASK_FOR_BASE_PT = 1 \n # noto il punto base si richiede il secondo punto per il raggio\n BASE_PT_KNOWN_ASK_FOR_RADIUS_PT = 2\n\n\n#===============================================================================\n# Qad_gripChangeArcRadius_maptool class\n#===============================================================================\nclass Qad_gripChangeArcRadius_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n \n self.basePt = None\n self.entity = None\n self.arc = None \n self.coordTransform = None\n self.__highlight = QadHighlight(self.canvas)\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__highlight.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__highlight.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__highlight.reset()\n self.mode = None\n\n def setEntity(self, entity):\n self.entity = QadEntity(entity)\n self.arc = self.entity.getQadGeom() # arco in map coordinate\n self.basePt = self.arc.center\n self.coordTransform = QgsCoordinateTransform(self.canvas.mapRenderer().destinationCrs(), entity.layer.crs())\n\n\n #============================================================================\n # stretch\n #============================================================================\n def changeRadius(self, radius):\n self.__highlight.reset()\n # radius = nuovo raggio dell'arco\n # tolerance2ApproxCurve = tolleranza per ricreare le curve\n self.arc.radius = radius\n points = self.arc.asPolyline()\n if points is None:\n return False\n \n g = QgsGeometry.fromPolyline(points)\n # trasformo la geometria nel crs del layer\n g.transform(self.coordTransform) \n self.__highlight.addGeometry(g, self.entity.layer)\n \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n\n # noto il punto base si richiede il secondo punto per il raggio\n if self.mode == Qad_gripChangeArcRadius_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_RADIUS_PT:\n radius = qad_utils.getDistance(self.basePt, self.tmpPoint)\n self.changeRadius(radius) \n \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__highlight.show()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__highlight.hide()\n except:\n pass\n \n \n def setMode(self, mode):\n self.mode = mode\n # noto niente si richiede il punto base\n if self.mode == Qad_gripChangeArcRadius_maptool_ModeEnum.ASK_FOR_BASE_PT:\n self.clear()\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n self.__highlight.reset()\n # noto il punto base si richiede il secondo punto per il raggio\n elif self.mode == Qad_gripChangeArcRadius_maptool_ModeEnum.BASE_PT_KNOWN_ASK_FOR_RADIUS_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.basePt)\n "
},
{
"alpha_fraction": 0.6699540019035339,
"alphanum_fraction": 0.6982248425483704,
"avg_line_length": 35.19047546386719,
"blob_id": "4611981e23b5125cc9e6686713bf568cc4444a1e",
"content_id": "980ed1d217bfc2124a68eb217e0aa10fb5515ee1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1521,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 42,
"path": "/qad_ui.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qad.ui'\n#\n# Created: Tue Sep 08 15:55:17 2015\n# by: PyQt4 UI code generator 4.10.2\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_QAD(object):\n def setupUi(self, QAD):\n QAD.setObjectName(_fromUtf8(\"QAD\"))\n QAD.resize(400, 300)\n self.buttonBox = QtGui.QDialogButtonBox(QAD)\n self.buttonBox.setGeometry(QtCore.QRect(30, 240, 341, 32))\n self.buttonBox.setOrientation(QtCore.Qt.Horizontal)\n self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)\n self.buttonBox.setObjectName(_fromUtf8(\"buttonBox\"))\n\n self.retranslateUi(QAD)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8(\"accepted()\")), QAD.accept)\n QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8(\"rejected()\")), QAD.reject)\n QtCore.QMetaObject.connectSlotsByName(QAD)\n\n def retranslateUi(self, QAD):\n QAD.setWindowTitle(_translate(\"QAD\", \"QAD\", None))\n\n"
},
{
"alpha_fraction": 0.5809829831123352,
"alphanum_fraction": 0.5888527035713196,
"avg_line_length": 51.215328216552734,
"blob_id": "2995a0cee4dbf1df85f169adeaecff36265d706b",
"content_id": "2b27794426fbfbf9a0ddf475ee53538b8d714558",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 203870,
"license_type": "no_license",
"max_line_length": 179,
"num_lines": 3901,
"path": "/qad_dim.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per la gestione delle quote\n \n -------------------\n begin : 2014-02-20\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport codecs\nimport ConfigParser\nimport math\nimport sys\n\n\nimport qad_utils\nimport qad_stretch_fun\nimport qad_layer\nimport qad_label\nfrom qad_entity import *\nfrom qad_variables import *\n\n\n\"\"\"\nLa classe quotatura é composta da tre layer: testo, linea, simbolo con lo stesso sistema di coordinate.\n\nIl layer testo deve avere tutte le caratteristiche del layer testo di QAD ed in più:\n- il posizionamento dell'etichetta con modalita \"Intorno al punto\" con distanza = 0 \n (che vuol dire punto di inserimento in basso a sx)\n- la dimensione del testo in unità mappa (la dimensione varia a seconda dello zoom).\n- dimStyleFieldName = \"dim_style\"; nome del campo che contiene il nome dello stile di quota (opzionale)\n- dimTypeFieldName = \"dim_type\"; nome del campo che contiene il tipo dello stile di quota (opzionale)\n- l'opzione \"Mostra etichette capovolte\" deve essere su \"sempre\" nel tab \"Etichette\"->\"Visualizzazione\"\n- rotFieldName = \"rot\"; nome del campo che contiene la rotazione del testo\n- la rotazione deve essere letta dal campo indicato da rotFieldName\n- idFieldName = \"id\"; nome del campo che contiene il codice della quota (opzionale)\n- la rotazione deve essere derivata dal campo rotFieldName\n- il font del carattere può essere derivata da un campo\n- la dimensione del carattere può essere derivata da un campo\n- il colore del testo può essere derivato da un campo (opzionale)\n\n\nIl layer simbolo deve avere tutte le caratteristiche del layer simbolo di QAD ed in più:\n- il simbolo freccia con rotazione 0 deve essere orizzontale con la freccia rivolta verso destra\n ed il suo punto di inserimento deve essere sulla punta della freccia\n- la dimensione del simbolo in unità mappa (la dimensione varia a seconda dello zoom),\n impostare la dimensione del simbolo in modo che la larghezza della freccia sia 1 unità di mappa.\n- componentFieldName = \"type\"; nome del campo che contiene il tipo di componente della quota (vedi QadDimComponentEnum) (opzionale)\n- symbolFieldName = \"block\"; nome del campo che contiene il nome del simbolo (opzionale)\n- idParentFieldName = \"id_parent\"; nome del campo che contiene il codice del testo della quota (opzionale)\n- scaleFieldName = \"scale\"; nome del campo che contiene il fattore di scala del simbolo (opzionale)\n se usato usare lo stile \"singolo simbolo\" (unico che consente di impostare la scala come diametro scala)\n la scala deve essere impostata su attraverso Stile->avanzato->campo di dimensione della scala-><nome del campo scala>\n la modalità di scala deve essere impostata su attraverso Stile->avanzato->campo di dimensione della scala->diametro scala\n- rotFieldName = \"rot\"; nome del campo che contiene la rotazione del simbolo \n la rotazione deve essere letta dal campo indicato da rotFieldName (360-rotFieldName)\n\nIl layer linea deve avere tutte le caratteristiche del layer linea ed in più:\n- componentFieldName = \"type\"; nome del campo che contiene il tipo di componente della quota (vedi QadDimComponentEnum) (opzionale)\n- lineTypeFieldName = \"line_type\"; nome del campo che contiene il tipolinea (opzionale)\n- colorFieldName = \"color\"; nome del campo che contiene il colore 'r,g,b,alpha'; alpha é opzionale (0=trasparente, 255=opaco) (opzionale)\n- idParentFieldName = \"id_parent\"; nome del campo che contiene il codice del testo della quota (opzionale)\n\n\"\"\"\n\n\n#===============================================================================\n# QadDimTypeEnum class. \n#===============================================================================\nclass QadDimTypeEnum():\n ALIGNED = \"AL\" # quota lineare allineata ai punti di origine delle linee di estensione\n ANGULAR = \"AN\" # quota angolare, misura l'angolo tra i 3 punti o tra gli oggetti selezionati\n BASE_LINE = \"BL\" # quota lineare, angolare o coordinata a partire dalla linea di base della quota precedente o di una quota selezionata\n DIAMETER = \"DI\" # quota per il diametro di un cerchio o di un arco\n LEADER = \"LD\" # crea una linea che consente di collegare un'annotazione ad una lavorazione\n LINEAR = \"LI\" # quota lineare con una linea di quota orizzontale o verticale\n RADIUS = \"RA\" # quota radiale, misura il raggio di un cerchio o di un arco selezionato e visualizza il testo di quota con un simbolo di raggio davanti\n ARC_LENTGH = \"AR\" # quota per la lunghezza di un cerchio o di un arco\n\n\n#===============================================================================\n# QadDimComponentEnum class.\n#===============================================================================\nclass QadDimComponentEnum():\n DIM_LINE1 = \"D1\" # linea di quota (\"Dimension line 1\")\n DIM_LINE2 = \"D2\" # linea di quota (\"Dimension line 2\")\n EXT_LINE1 = \"E1\" # prima linea di estensione (\"Extension line 1\")\n EXT_LINE2 = \"E2\" # seconda linea di estensione (\"Extension line 2\")\n LEADER_LINE = \"L\" # linea porta quota usata quando il testo é fuori dalla quota (\"Leader\")\n BLOCK1 = \"B1\" # primo blocco della freccia (\"Block 1\")\n BLOCK2 = \"B2\" # secondo blocco della freccia (\"Block 2\")\n LEADER_BLOCK = \"LB\" # blocco della freccia nel caso leader (\"Leader Block\")\n ARC_BLOCK = \"AB\" # simbolo dell'arco (\"Arc Block\")\n DIM_PT1 = \"D1\" # primo punto da quotare (\"Dimension point 1\")\n DIM_PT2 = \"D2\" # secondo punto da quotare (\"Dimension point 2\")\n TEXT_PT = \"T\" # punto del testo di quota (\"Text\")\n\n\n#===============================================================================\n# QadDimStyleAlignmentEnum class.\n#===============================================================================\nclass QadDimStyleAlignmentEnum():\n HORIZONTAL = 0 # orizzontale\n VERTICAL = 1 # verticale\n ALIGNED = 2 # allineata\n FORCED_ROTATION = 3 # rotazione forzata\n\n\n#===============================================================================\n# QadDimStyleTxtVerticalPosEnum class.\n#===============================================================================\nclass QadDimStyleTxtVerticalPosEnum():\n CENTERED_LINE = 0 # testo centrato alla linea di quota\n ABOVE_LINE = 1 # testo sopra alla linea di quota ma nel caso la linea di quota non sia orizzontale \n # e il testo sia dentro le linee di estensione e forzato orizzontale allora il testo diventa centrato\n EXTERN_LINE = 2 # testo posizionato nella parte opposta ai punti di quotatura \n BELOW_LINE = 4 # testo sotto alla linea di quota ma nel caso la linea di quota non sia orizzontale \n # e il testo sia dentro le linee di estensione e forzato orizzontale allora il testo diventa centrato\n\n\n#===============================================================================\n# QadDimStyleTxtHorizontalPosEnum class.\n#===============================================================================\nclass QadDimStyleTxtHorizontalPosEnum():\n CENTERED_LINE = 0 # testo centrato alla linea di quota\n FIRST_EXT_LINE = 1 # testo vicino alla prima linea di estensione\n SECOND_EXT_LINE = 2 # testo vicino alla seconda linea di estensione\n FIRST_EXT_LINE_UP = 3 # testo sopra e allineato alla prima linea di estensione\n SECOND_EXT_LINE_UP = 4 # testo sopra e allineato alla seconda linea di estensione\n\n\n#===============================================================================\n# QadDimStyleTxtRotEnum class.\n#===============================================================================\nclass QadDimStyleTxtRotModeEnum():\n HORIZONTAL = 0 # testo orizzontale\n ALIGNED_LINE = 1 # testo allineato con la linea di quota\n ISO = 2 # testo allineato con la linea di quota se tra le linee di estensione,\n # altrimenti testo orizzontale\n FORCED_ROTATION = 3 # testo con rotazione forzata\n\n\n#===============================================================================\n# QadDimStyleArcSymbolPosEnum class.\n#===============================================================================\nclass QadDimStyleArcSymbolPosEnum():\n BEFORE_TEXT = 0 # simbolo prima del testo\n ABOVE_TEXT = 1 # simbolo sopra il testo\n NONE = 2 # niente simbolo\n\n\n#===============================================================================\n# QadDimStyleArcSymbolPosEnum class.\n#===============================================================================\nclass QadDimStyleTxtDirectionEnum():\n SX_TO_DX = 0 # da sinistra a destra\n DX_TO_SX = 1 # da destra a sinistra \n\n\n#===============================================================================\n# QadDimStyleTextBlocksAdjustEnum class.\n#===============================================================================\nclass QadDimStyleTextBlocksAdjustEnum():\n BOTH_OUTSIDE_EXT_LINES = 0 # sposta testo e frecce fuori dalle linee di estensione\n FIRST_BLOCKS_THEN_TEXT = 1 # sposta prima le frecce poi, se non basta, anche il testo\n FIRST_TEXT_THEN_BLOCKS = 2 # sposta prima il testo poi, se non basta, anche le frecce\n WHICHEVER_FITS_BEST = 3 # Sposta indistintamente il testo o le frecce (l'oggetto che si adatta meglio)\n\n\n#===============================================================================\n# QadDim dimension style class\n#===============================================================================\nclass QadDimStyle(): \n \n def __init__(self, dimStyle = None):\n self.name = \"standard\" # nome dello stile\n self.description = \"\"\n self.path = \"\" # percorso e nome del file in cui è stato salvato/caricato\n self.dimType = QadDimTypeEnum.ALIGNED # tipo di quotatura\n \n # testo di quota\n self.textPrefix = \"\" # prefisso per il testo della quota\n self.textSuffix = \"\" # suffisso per il testo della quota\n self.textSuppressLeadingZeros = False # per sopprimere o meno gli zero all'inizio del testo\n self.textDecimalZerosSuppression = True # per sopprimere gli zero finali nei decimali\n self.textHeight = 1.0 # altezza testo (DIMTXT) in unità di mappa\n self.textVerticalPos = QadDimStyleTxtVerticalPosEnum.ABOVE_LINE # posizione verticale del testo rispetto la linea di quota (DIMTAD)\n self.textHorizontalPos = QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE # posizione orizzontale del testo rispetto la linea di quota (DIMTAD)\n self.textOffsetDist = 0.5 # distanza aggiunta intorno al testo quando per inserirlo viene spezzata la linea di quota (DIMGAP)\n self.textRotMode = QadDimStyleTxtRotModeEnum.ALIGNED_LINE # modalità di rotazione del testo (DIMTIH e DIMTOH)\n self.textForcedRot = 0.0 # rotazione forzata del testo\n self.textDecimals = 2 # numero di decimali (DIMDEC)\n self.textDecimalSep = \".\" # Separatore dei decimali (DIMDSEP)\n self.textFont = \"Arial\" # nome del font di testo (DIMTXSTY)\n self.textColor = \"255,255,255,255\" # Colore per i testi della quota (DIMCLRT); bianco con opacità totale\n self.textDirection = QadDimStyleTxtDirectionEnum.SX_TO_DX # specifica la direzione del testo di quota (DIMTXTDIRECTION) 0 = da sx a dx, 1 = da dx a sx\n self.arcSymbPos = QadDimStyleArcSymbolPosEnum.BEFORE_TEXT # disegna o meno il simbolo dell'arco con DIMARC (DIMARCSYM). \n \n # linee di quota\n self.dimLine1Show = True # Mostra o nasconde la prima linea di quota (DIMSD1)\n self.dimLine2Show = True # Mostra o nasconde la seconda linea di quota (DIMSD2)\n self.dimLineLineType = \"continuous\" # Tipo di linea per le linee di quota (DIMLTYPE)\n self.dimLineColor = \"255,255,255,255\" # Colore per le linee di quota (DIMCLRD); bianco con opacità totale\n self.dimLineSpaceOffset = 3.75 # Controlla la spaziatura delle linee di quota nelle quote da linea di base (DIMDLI)\n \n # simboli per linee di quota\n # il blocco per la freccia é una freccia verso destra con il punto di inserimento sulla punta della freccia \n self.block1Name = \"triangle2\" # nome del simbolo da usare come punta della freccia sulla prima linea di quota (DIMBLK1)\n self.block2Name = \"triangle2\" # nome del simbolo da usare come punta della freccia sulla seconda linea di quota (DIMBLK2)\n self.blockLeaderName = \"triangle2\" # nome del simbolo da usare come punta della freccia sulla linea della direttrice (DIMLDRBLK)\n self.blockWidth = 0.5 # larghezza del simbolo (in orizzontale) quando la dimensione in unità di mappa = 1 (vedi \"triangle2\")\n self.blockScale = 1.0 # scala della dimensione del simbolo (DIMASZ)\n self.centerMarkSize = 0.0 # disegna o meno il marcatore di centro o le linee d'asse per le quote create con\n # DIMCENTER, DIMDIAMETER, e DIMRADIUS (DIMCEN).\n # 0 = niente, > 0 dimensione marcatore di centro, < 0 dimensione linee d'asse\n \n # adattamento del testo e delle frecce\n self.textBlockAdjust = QadDimStyleTextBlocksAdjustEnum.WHICHEVER_FITS_BEST # (DIMATFIT)\n self.blockSuppressionForNoSpace = False # Sopprime le punte della frecce se non c'é spazio sufficiente all'interno delle linee di estensione (DIMSOXD)\n \n # linee di estensione\n self.extLine1Show = True # Mostra o nasconde la prima linea di estensione (DIMSE1)\n self.extLine2Show = True # Mostra o nasconde la seconda linea di estensione (DIMSE2)\n self.extLine1LineType = \"continuous\" # Tipo di linea per la prima linea di estensione (DIMLTEX1)\n self.extLine2LineType = \"continuous\" # Tipo di linea per la seconda linea di estensione (DIMLTEX2)\n self.extLineColor = \"255,255,255,255\" # Colore per le linee di estensione (DIMCLRE); bianco con opacità totale\n self.extLineOffsetDimLine = 0.0 # distanza della linea di estensione oltre la linea di quota (DIMEXE)\n self.extLineOffsetOrigPoints = 0.0 # distanza della linea di estensione dai punti da quotare (DIMEXO)\n self.extLineIsFixedLen = False # Attiva lunghezza fissa delle line di estensione (DIMFXLON)\n self.extLineFixedLen = 1.0 # lunghezza fissa delle line di estensione (DIMFXL) dalla linea di quota \n # al punto da quotare spostato di extLineOffsetOrigPoints\n # (la linea di estensione non va oltre il punto da quotare)\n \n # layer e loro caratteristiche\n # devo allocare i campi a livello di classe QadDimStyle perché QgsFeature.setFields usa solo il puntatore alla lista fields\n # che, se allocata privatamente in qualsiasi funzione, all'uscita della funzione verrebbe distrutta \n self.textualLayerName = None # nome layer per memorizzare il testo della quota\n self.__textualLayer = None # layer per memorizzare il testo della quota\n self.__textFields = None\n self.__textualFeaturePrototype = None\n \n self.linearLayerName = None # nome layer per memorizzare le linee della quota\n self.__linearLayer = None # layer per memorizzare le linee della quota\n self.__lineFields = None\n self.__linearFeaturePrototype = None\n \n self.symbolLayerName = None # nome layer per memorizzare i blocchi delle frecce della quota\n self.__symbolLayer = None # layer per memorizzare i blocchi delle frecce della quota\n self.__symbolFields = None\n self.__symbolFeaturePrototype = None\n \n self.componentFieldName = \"type\" # nome del campo che contiene il tipo di componente della quota (vedi QadDimComponentEnum)\n self.lineTypeFieldName = \"line_type\" # nome del campo che contiene il tipolinea\n self.colorFieldName = \"color\" # nome del campo che contiene il colore 'r,g,b,alpha'; alpha é opzionale (0=trasparente, 255=opaco)\n self.idFieldName = \"id\" # nome del campo che contiene il codice del della quota nel layer di tipo testo\n self.idParentFieldName = \"id_parent\" # nome del campo che contiene il codice della quota nei layer simbolo e linea \n self.dimStyleFieldName = \"dim_style\" # nome del campo che contiene il nome dello stile di quota\n self.dimTypeFieldName = \"dim_type\" # nome del campo che contiene il tipo dello stile di quota \n self.symbolFieldName = \"block\" # nome del campo che contiene il nome del simbolo\n self.scaleFieldName = \"scale\" # nome del campo che contiene la dimensione\n self.rotFieldName = \"rot\" # nome del campo che contiene rotazione in gradi\n \n if dimStyle is None:\n return\n self.set(dimStyle)\n\n\n #============================================================================\n # FUNZIONI GENERICHE - INIZIO\n #============================================================================\n\n def set(self, dimStyle):\n self.name = dimStyle.name\n self.description = dimStyle.description\n self.path = dimStyle.path\n self.dimType = dimStyle.dimType\n \n # testo di quota\n self.textPrefix = dimStyle.textPrefix\n self.textSuffix = dimStyle.textSuffix\n self.textSuppressLeadingZeros = dimStyle.textSuppressLeadingZeros\n self.textDecimaZerosSuppression = dimStyle.textDecimalZerosSuppression\n self.textHeight = dimStyle.textHeight\n self.textVerticalPos = dimStyle.textVerticalPos\n self.textHorizontalPos = dimStyle.textHorizontalPos\n self.textOffsetDist = dimStyle.textOffsetDist\n self.textRotMode = dimStyle.textRotMode\n self.textForcedRot = dimStyle.textForcedRot\n self.textDecimals = dimStyle.textDecimals\n self.textDecimalSep = dimStyle.textDecimalSep\n self.textFont = dimStyle.textFont\n self.textColor = dimStyle.textColor\n self.textDirection = dimStyle.textDirection\n self.arcSymbPos = dimStyle.arcSymbPos\n \n # linee di quota\n self.dimLine1Show = dimStyle.dimLine1Show\n self.dimLine2Show = dimStyle.dimLine2Show\n self.dimLineLineType = dimStyle.dimLineLineType\n self.dimLineColor = dimStyle.dimLineColor\n self.dimLineSpaceOffset = dimStyle.dimLineSpaceOffset\n \n # simboli per linee di quota\n self.block1Name = dimStyle.block1Name\n self.block2Name = dimStyle.block2Name\n self.blockLeaderName = dimStyle.blockLeaderName\n self.blockWidth = dimStyle.blockWidth\n self.blockScale = dimStyle.blockScale\n self.blockSuppressionForNoSpace = dimStyle.blockSuppressionForNoSpace\n self.centerMarkSize = dimStyle.centerMarkSize\n \n # adattamento del testo e delle frecce\n self.textBlockAdjust = dimStyle.textBlockAdjust\n \n # linee di estensione\n self.extLine1Show = dimStyle.extLine1Show\n self.extLine2Show = dimStyle.extLine2Show\n self.extLine1LineType = dimStyle.extLine1LineType\n self.extLine2LineType = dimStyle.extLine2LineType\n self.extLineColor = dimStyle.extLineColor\n self.extLineOffsetDimLine = dimStyle.extLineOffsetDimLine\n self.extLineOffsetOrigPoints = dimStyle.extLineOffsetOrigPoints\n self.extLineIsFixedLen = dimStyle.extLineIsFixedLen\n self.extLineFixedLen = dimStyle.extLineFixedLen\n \n # layer e loro caratteristiche\n self.textualLayerName = dimStyle.textualLayerName\n self.__textualLayer = dimStyle.__textualLayer\n self.__textFields = dimStyle.__textFields\n self.__textualFeaturePrototype = dimStyle.__textualFeaturePrototype \n self.linearLayerName = dimStyle.linearLayerName\n self.__linearLayer = dimStyle.__linearLayer\n self.__lineFields = dimStyle.__lineFields\n self.__linearFeaturePrototype = dimStyle.__linearFeaturePrototype \n self.symbolLayerName = dimStyle.symbolLayerName\n self.__symbolLayer = dimStyle.__symbolLayer\n self.__symbolFields = dimStyle.__symbolFields\n self.__symbolFeaturePrototype = dimStyle.__symbolFeaturePrototype \n\n self.componentFieldName = dimStyle.componentFieldName\n self.symbolFieldName = dimStyle.symbolFieldName\n self.lineTypeFieldName = dimStyle.lineTypeFieldName\n self.colorFieldName = dimStyle.colorFieldName\n self.idFieldName = dimStyle.idFieldName\n self.idParentFieldName = dimStyle.idParentFieldName\n self.dimStyleFieldName = dimStyle.dimStyleFieldName\n self.dimTypeFieldName = dimStyle.dimTypeFieldName\n self.scaleFieldName = dimStyle.scaleFieldName\n self.rotFieldName = dimStyle.rotFieldName\n\n\n #============================================================================\n # getPropList\n #============================================================================\n def getPropList(self):\n proplist = dict() # dizionario di nome con lista [descrizione, valore]\n propDescr = QadMsg.translate(\"Dimension\", \"Name\")\n proplist[\"name\"] = [propDescr, self.name]\n propDescr = QadMsg.translate(\"Dimension\", \"Description\")\n proplist[\"description\"] = [propDescr, self.description]\n propDescr = QadMsg.translate(\"Dimension\", \"File path\")\n proplist[\"path\"] = [propDescr, self.path]\n \n # testo di quota\n value = self.textPrefix\n if len(self.textPrefix) > 0:\n value += \"<>\"\n value += self.textSuffix\n propDescr = QadMsg.translate(\"Dimension\", \"Text prefix and suffix\")\n proplist[\"textPrefix\"] = [propDescr, value]\n propDescr = QadMsg.translate(\"Dimension\", \"Leading zero suppression\")\n proplist[\"textSuppressLeadingZeros\"] = [propDescr, self.textSuppressLeadingZeros]\n propDescr = QadMsg.translate(\"Dimension\", \"Trailing zero suppression\")\n proplist[\"textDecimalZerosSuppression\"] = [propDescr, self.textDecimalZerosSuppression]\n propDescr = QadMsg.translate(\"Dimension\", \"Text height\")\n proplist[\"textHeight\"] = [propDescr, self.textHeight]\n propDescr = QadMsg.translate(\"Dimension\", \"Vertical text position\")\n proplist[\"textVerticalPos\"] = [propDescr, self.textVerticalPos]\n propDescr = QadMsg.translate(\"Dimension\", \"Horizontal text position\")\n proplist[\"textHorizontalPos\"] = [propDescr, self.textHorizontalPos]\n propDescr = QadMsg.translate(\"Dimension\", \"Text offset\")\n proplist[\"textOffsetDist\"] = [propDescr, self.textOffsetDist]\n propDescr = QadMsg.translate(\"Dimension\", \"Text alignment\")\n proplist[\"textRotMode\"] = [propDescr, self.textRotMode]\n propDescr = QadMsg.translate(\"Dimension\", \"Fixed text rotation\")\n proplist[\"textForcedRot\"] = [propDescr, self.textForcedRot]\n propDescr = QadMsg.translate(\"Dimension\", \"Precision\")\n proplist[\"textDecimals\"] = [propDescr, self.textDecimals]\n propDescr = QadMsg.translate(\"Dimension\", \"Decimal separator\")\n proplist[\"textDecimalSep\"] = [propDescr, self.textDecimalSep]\n propDescr = QadMsg.translate(\"Dimension\", \"Text font\")\n proplist[\"textFont\"] = [propDescr, self.textFont]\n propDescr = QadMsg.translate(\"Dimension\", \"Text color\")\n proplist[\"textColor\"] = [propDescr, self.textColor]\n if self.textDirection == QadDimStyleTxtDirectionEnum.SX_TO_DX:\n value = QadMsg.translate(\"Dimension\", \"From left to right\")\n else:\n value = QadMsg.translate(\"Dimension\", \"From right to left\")\n propDescr = QadMsg.translate(\"Dimension\", \"Text direction\")\n proplist[\"textDirection\"] = [propDescr, value]\n propDescr = QadMsg.translate(\"Dimension\", \"Arc len. symbol\")\n proplist[\"arcSymbPos\"] = [propDescr, self.arcSymbPos]\n \n # linee di quota\n propDescr = QadMsg.translate(\"Dimension\", \"Dim line 1 visible\")\n proplist[\"dimLine1Show\"] = [propDescr, self.dimLine1Show]\n propDescr = QadMsg.translate(\"Dimension\", \"Dim line 2 visible\")\n proplist[\"dimLine2Show\"] = [propDescr, self.dimLine2Show]\n propDescr = QadMsg.translate(\"Dimension\", \"Dim line linetype\")\n proplist[\"dimLineLineType\"] = [propDescr, self.dimLineLineType]\n propDescr = QadMsg.translate(\"Dimension\", \"Dim line color\")\n proplist[\"dimLineColor\"] = [propDescr, self.dimLineColor]\n propDescr = QadMsg.translate(\"Dimension\", \"Offset from origin\")\n proplist[\"dimLineSpaceOffset\"] = [propDescr, self.dimLineSpaceOffset]\n \n # simboli per linee di quota\n propDescr = QadMsg.translate(\"Dimension\", \"Arrow 1\")\n proplist[\"block1Name\"] = [propDescr, self.block1Name]\n propDescr = QadMsg.translate(\"Dimension\", \"Arrow 2\")\n proplist[\"block2Name\"] = [propDescr, self.block2Name]\n propDescr = QadMsg.translate(\"Dimension\", \"Leader arrow\")\n proplist[\"blockLeaderName\"] = [propDescr, self.blockLeaderName]\n propDescr = QadMsg.translate(\"Dimension\", \"Arrowhead width\")\n proplist[\"blockWidth\"] = [propDescr, self.blockWidth]\n propDescr = QadMsg.translate(\"Dimension\", \"Arrowhead scale\")\n proplist[\"blockScale\"] = [propDescr, self.blockScale]\n propDescr = QadMsg.translate(\"Dimension\", \"Center mark size\")\n proplist[\"centerMarkSize\"] = [propDescr, self.centerMarkSize]\n \n # adattamento del testo e delle frecce\n propDescr = QadMsg.translate(\"Dimension\", \"Fit: arrows and text\")\n proplist[\"textBlockAdjust\"] = [propDescr, self.textBlockAdjust]\n propDescr = QadMsg.translate(\"Dimension\", \"Suppress arrows for lack of space\")\n proplist[\"blockSuppressionForNoSpace\"] = [propDescr, self.blockSuppressionForNoSpace]\n \n # linee di estensione\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line 1 visible\")\n proplist[\"extLine1Show\"] = [propDescr, self.extLine1Show]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line 2 visible\")\n proplist[\"extLine2Show\"] = [propDescr, self.extLine2Show]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line 1 linetype\")\n proplist[\"extLine1LineType\"] = [propDescr, self.extLine1LineType]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line 2 linetype\")\n proplist[\"extLine2LineType\"] = [propDescr, self.extLine2LineType]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line color\")\n proplist[\"extLineColor\"] = [propDescr, self.extLineColor]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line extension\")\n proplist[\"extLineOffsetDimLine\"] = [propDescr, self.extLineOffsetDimLine]\n propDescr = QadMsg.translate(\"Dimension\", \"Ext. line offset\")\n proplist[\"extLineOffsetOrigPoints\"] = [propDescr, self.extLineOffsetOrigPoints]\n propDescr = QadMsg.translate(\"Dimension\", \"Fixed length ext. line activated\")\n proplist[\"extLineIsFixedLen\"] = [propDescr, self.extLineIsFixedLen]\n propDescr = QadMsg.translate(\"Dimension\", \"Fixed length ext. line\")\n proplist[\"extLineFixedLen\"] = [propDescr, self.extLineFixedLen]\n \n # layer e loro caratteristiche\n propDescr = QadMsg.translate(\"Dimension\", \"Layer for dim texts\")\n proplist[\"textualLayerName\"] = [propDescr, self.textualLayerName]\n propDescr = QadMsg.translate(\"Dimension\", \"Layer for dim lines\")\n proplist[\"linearLayerName\"] = [propDescr, self.linearLayerName]\n propDescr = QadMsg.translate(\"Dimension\", \"Layer for dim arrows\")\n proplist[\"symbolLayerName\"] = [propDescr, self.symbolLayerName]\n \n propDescr = QadMsg.translate(\"Dimension\", \"Field for component type\")\n proplist[\"componentFieldName\"] = [propDescr, self.componentFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for linetype\")\n proplist[\"lineTypeFieldName\"] = [propDescr, self.lineTypeFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for color\")\n proplist[\"colorFieldName\"] = [propDescr, self.colorFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for dim ID in texts\")\n proplist[\"idFieldName\"] = [propDescr, self.idFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for dim ID in lines and arrows\")\n proplist[\"idParentFieldName\"] = [propDescr, self.idParentFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for dim style name\")\n proplist[\"dimStyleFieldName\"] = [propDescr, self.dimStyleFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for dim type\")\n proplist[\"dimTypeFieldName\"] = [propDescr, self.dimTypeFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for symbol name\")\n proplist[\"symbolFieldName\"] = [propDescr, self.symbolFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for arrows scale\")\n proplist[\"scaleFieldName\"] = [propDescr, self.scaleFieldName]\n propDescr = QadMsg.translate(\"Dimension\", \"Field for arrows rotation\")\n proplist[\"rotFieldName\"] = [propDescr, self.rotFieldName]\n \n return proplist\n\n\n #============================================================================\n # getLayer\n #============================================================================\n def getLayer(self, layerName):\n layerList = qad_layer.getLayersByName(qad_utils.wildCard2regularExpr(layerName))\n if len(layerList) == 1:\n return layerList[0]\n return None\n\n\n #============================================================================\n # layer testuale\n def getTextualLayer(self):\n if self.__textualLayer is None:\n self.__textualLayer = self.getLayer(self.textualLayerName)\n return self.__textualLayer\n \n def getTextualLayerFields(self):\n if self.__textFields is None:\n self.__textFields = None if self.getTextualLayer() is None else self.getTextualLayer().pendingFields()\n return self.__textFields\n\n def getTextualFeaturePrototype(self):\n if self.__textualFeaturePrototype is None:\n if self.getTextualLayerFields() is not None:\n self.__textualFeaturePrototype = QgsFeature(self.getTextualLayerFields()) \n self.initFeatureToDefautlValues(self.getTextualLayer(), self.__textualFeaturePrototype)\n return self.__textualFeaturePrototype\n\n\n #============================================================================\n # layer lineare\n def getLinearLayer(self):\n if self.__linearLayer is None:\n self.__linearLayer = self.getLayer(self.linearLayerName)\n return self.__linearLayer\n \n def getLinearLayerFields(self):\n if self.__lineFields is None:\n self.__lineFields = None if self.getLinearLayer() is None else self.getLinearLayer().pendingFields()\n return self.__lineFields\n\n def getLinearFeaturePrototype(self):\n if self.__linearFeaturePrototype is None:\n if self.getLinearLayerFields() is not None:\n self.__linearFeaturePrototype = QgsFeature(self.getLinearLayerFields()) \n self.initFeatureToDefautlValues(self.getLinearLayer(), self.__linearFeaturePrototype)\n return self.__linearFeaturePrototype\n\n\n #============================================================================\n # layer simbolo\n def getSymbolLayer(self):\n if self.__symbolLayer is None:\n self.__symbolLayer = self.getLayer(self.symbolLayerName)\n return self.__symbolLayer\n \n def getSymbolLayerFields(self):\n if self.__symbolFields is None:\n self.__symbolFields = None if self.getSymbolLayer() is None else self.getSymbolLayer().pendingFields()\n return self.__symbolFields\n\n def getSymbolFeaturePrototype(self):\n if self.__symbolFeaturePrototype is None:\n if self.getSymbolLayerFields() is not None:\n self.__symbolFeaturePrototype = QgsFeature(self.getSymbolLayerFields()) \n self.initFeatureToDefautlValues(self.getSymbolLayer(), self.__symbolFeaturePrototype)\n return self.__symbolFeaturePrototype\n \n \n #============================================================================\n # initFeatureToDefautlValues\n #============================================================================\n def initFeatureToDefautlValues(self, layer, f):\n # assegno i valori di default\n provider = layer.dataProvider()\n fields = f.fields()\n for field in fields.toList():\n i = fields.indexFromName(field.name())\n f[field.name()] = provider.defaultValue(i)\n \n \n #============================================================================\n # save\n #============================================================================\n def save(self, path = \"\", overwrite = True):\n \"\"\"\n Salva le impostazioni dello stile di quotatura in un file.\n \"\"\"\n if path == \"\" and self.path != \"\":\n _path = self.path\n else: \n dir, base = os.path.split(path)\n if dir == \"\":\n dir = QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + \"python/plugins/qad\") + \"/\"\n else:\n dir = QDir.cleanPath(dir) + \"/\"\n \n name, ext = os.path.splitext(base)\n if name == \"\":\n name = self.name\n \n if ext == \"\": # se non c'è estensione la aggiungo\n ext = \".dim\"\n \n _path = dir + name + ext\n \n if overwrite == False: # se non si vuole sovrascrivere\n if os.path.exists(_path):\n return False\n \n dir = QFileInfo(_path).absoluteDir() \n if not dir.exists():\n os.makedirs(dir.absolutePath())\n\n config = qad_utils.QadRawConfigParser(allow_no_value=True)\n config.add_section(\"dimension_options\")\n config.set(\"dimension_options\", \"name\", str(self.name))\n config.set(\"dimension_options\", \"description\", self.description)\n config.set(\"dimension_options\", \"dimType\", str(self.dimType))\n \n # testo di quota\n config.set(\"dimension_options\", \"textPrefix\", str(self.textPrefix))\n config.set(\"dimension_options\", \"textSuffix\", str(self.textSuffix))\n config.set(\"dimension_options\", \"textSuppressLeadingZeros\", str(self.textSuppressLeadingZeros))\n config.set(\"dimension_options\", \"textDecimalZerosSuppression\", str(self.textDecimalZerosSuppression))\n config.set(\"dimension_options\", \"textHeight\", str(self.textHeight))\n config.set(\"dimension_options\", \"textVerticalPos\", str(self.textVerticalPos))\n config.set(\"dimension_options\", \"textHorizontalPos\", str(self.textHorizontalPos))\n config.set(\"dimension_options\", \"textOffsetDist\", str(self.textOffsetDist))\n config.set(\"dimension_options\", \"textRotMode\", str(self.textRotMode))\n config.set(\"dimension_options\", \"textForcedRot\", str(self.textForcedRot))\n config.set(\"dimension_options\", \"textDecimals\", str(self.textDecimals))\n config.set(\"dimension_options\", \"textDecimalSep\", str(self.textDecimalSep))\n config.set(\"dimension_options\", \"textFont\", str(self.textFont))\n config.set(\"dimension_options\", \"textColor\", str(self.textColor))\n config.set(\"dimension_options\", \"textDirection\", str(self.textDirection))\n config.set(\"dimension_options\", \"arcSymbPos\", str(self.arcSymbPos))\n\n # linee di quota\n config.set(\"dimension_options\", \"dimLine1Show\", str(self.dimLine1Show))\n config.set(\"dimension_options\", \"dimLine2Show\", str(self.dimLine2Show))\n config.set(\"dimension_options\", \"dimLineLineType\", str(self.dimLineLineType))\n config.set(\"dimension_options\", \"dimLineColor\", str(self.dimLineColor))\n config.set(\"dimension_options\", \"dimLineSpaceOffset\", str(self.dimLineSpaceOffset))\n \n # simboli per linee di quota\n config.set(\"dimension_options\", \"block1Name\", str(self.block1Name))\n config.set(\"dimension_options\", \"block2Name\", str(self.block2Name))\n config.set(\"dimension_options\", \"blockLeaderName\", str(self.blockLeaderName))\n config.set(\"dimension_options\", \"blockWidth\", str(self.blockWidth))\n config.set(\"dimension_options\", \"blockScale\", str(self.blockScale))\n config.set(\"dimension_options\", \"blockSuppressionForNoSpace\", str(self.blockSuppressionForNoSpace))\n config.set(\"dimension_options\", \"centerMarkSize\", str(self.centerMarkSize))\n\n # adattamento del testo e delle frecce\n config.set(\"dimension_options\", \"textBlockAdjust\", str(self.textBlockAdjust))\n\n # linee di estensione\n config.set(\"dimension_options\", \"extLine1Show\", str(self.extLine1Show))\n config.set(\"dimension_options\", \"extLine2Show\", str(self.extLine2Show))\n config.set(\"dimension_options\", \"extLine1LineType\", str(self.extLine1LineType))\n config.set(\"dimension_options\", \"extLine2LineType\", str(self.extLine2LineType))\n config.set(\"dimension_options\", \"extLineColor\", str(self.extLineColor))\n config.set(\"dimension_options\", \"extLineOffsetDimLine\", str(self.extLineOffsetDimLine))\n config.set(\"dimension_options\", \"extLineOffsetOrigPoints\", str(self.extLineOffsetOrigPoints))\n config.set(\"dimension_options\", \"extLineIsFixedLen\", str(self.extLineIsFixedLen))\n config.set(\"dimension_options\", \"extLineFixedLen\", str(self.extLineFixedLen))\n\n # layer e loro caratteristiche\n config.set(\"dimension_options\", \"textualLayerName\", \"\" if self.textualLayerName is None else self.textualLayerName)\n config.set(\"dimension_options\", \"linearLayerName\", \"\" if self.linearLayerName is None else self.linearLayerName)\n config.set(\"dimension_options\", \"symbolLayerName\", \"\" if self.symbolLayerName is None else self.symbolLayerName)\n config.set(\"dimension_options\", \"componentFieldName\", str(self.componentFieldName))\n config.set(\"dimension_options\", \"symbolFieldName\", str(self.symbolFieldName))\n config.set(\"dimension_options\", \"lineTypeFieldName\", str(self.lineTypeFieldName))\n config.set(\"dimension_options\", \"colorFieldName\", str(self.colorFieldName))\n config.set(\"dimension_options\", \"idFieldName\", str(self.idFieldName))\n config.set(\"dimension_options\", \"idParentFieldName\", str(self.idParentFieldName))\n config.set(\"dimension_options\", \"dimStyleFieldName\", str(self.dimStyleFieldName))\n config.set(\"dimension_options\", \"dimTypeFieldName\", str(self.dimTypeFieldName))\n config.set(\"dimension_options\", \"scaleFieldName\", str(self.scaleFieldName))\n config.set(\"dimension_options\", \"rotFieldName\", str(self.rotFieldName))\n\n with codecs.open(_path, 'w', 'utf-8') as configFile: \n config.write(configFile)\n \n self.path = _path\n \n return True\n\n\n #============================================================================\n # getDefaultDimFilePath\n #============================================================================\n def getDefaultDimFilePath(self, fileName):\n # ottiene il percorso automatico dove salvare/caricare il file della quotatura\n # se esiste un progetto caricato il percorso è quello del progetto\n prjFileInfo = QFileInfo(QgsProject.instance().fileName())\n path = prjFileInfo.absolutePath()\n if len(path) == 0:\n # se non esiste un progetto caricato uso il percorso di installazione di qad\n path = QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + \"python/plugins/qad\")\n return path + \"/\" + fileName\n\n \n #============================================================================\n # load\n #============================================================================\n def load(self, path):\n \"\"\"\n Carica le impostazioni dello stile di quotatura da un file.\n \"\"\"\n if path is None or path == \"\":\n return False\n \n if os.path.dirname(path) == \"\": # path contiene solo il nome del file (senza dir)\n _path = self.getDefaultDimFilePath(path)\n else:\n _path = path\n \n if not os.path.exists(_path):\n return False\n\n config = qad_utils.QadRawConfigParser(allow_no_value=True)\n config.readfp(codecs.open(_path, \"r\", \"utf-8\"))\n #config.read(_path)\n\n self.name = config.get(\"dimension_options\", \"name\")\n self.description = config.get(\"dimension_options\", \"description\")\n self.dimType = config.get(\"dimension_options\", \"dimType\")\n \n # testo di quota\n self.textPrefix = config.get(\"dimension_options\", \"textPrefix\")\n self.textSuffix = config.get(\"dimension_options\", \"textSuffix\")\n self.textSuppressLeadingZeros = config.getboolean(\"dimension_options\", \"textSuppressLeadingZeros\")\n self.textDecimalZerosSuppression = config.getboolean(\"dimension_options\", \"textDecimalZerosSuppression\")\n self.textHeight = config.getfloat(\"dimension_options\", \"textHeight\")\n self.textVerticalPos = config.getint(\"dimension_options\", \"textVerticalPos\")\n self.textHorizontalPos = config.getint(\"dimension_options\", \"textHorizontalPos\")\n self.textOffsetDist = config.getfloat(\"dimension_options\", \"textOffsetDist\")\n self.textRotMode = config.getint(\"dimension_options\", \"textRotMode\")\n self.textForcedRot = config.getfloat(\"dimension_options\", \"textForcedRot\")\n self.textDecimals = config.getint(\"dimension_options\", \"textDecimals\")\n self.textDecimalSep = config.get(\"dimension_options\", \"textDecimalSep\")\n self.textFont = config.get(\"dimension_options\", \"textFont\")\n self.textColor = config.get(\"dimension_options\", \"textColor\")\n self.textDirection = config.getint(\"dimension_options\", \"textDirection\")\n self.arcSymbPos = config.getint(\"dimension_options\", \"arcSymbPos\")\n\n # linee di quota\n self.dimLine1Show = config.getboolean(\"dimension_options\", \"dimLine1Show\")\n self.dimLine2Show = config.getboolean(\"dimension_options\", \"dimLine2Show\")\n self.dimLineLineType = config.get(\"dimension_options\", \"dimLineLineType\")\n self.dimLineColor = config.get(\"dimension_options\", \"dimLineColor\")\n self.dimLineSpaceOffset = config.getfloat(\"dimension_options\", \"dimLineSpaceOffset\")\n \n # simboli per linee di quota\n self.block1Name = config.get(\"dimension_options\", \"block1Name\")\n self.block2Name = config.get(\"dimension_options\", \"block2Name\")\n self.blockLeaderName = config.get(\"dimension_options\", \"blockLeaderName\")\n self.blockWidth = config.getfloat(\"dimension_options\", \"blockWidth\")\n self.blockScale = config.getfloat(\"dimension_options\", \"blockScale\")\n self.blockSuppressionForNoSpace = config.getboolean(\"dimension_options\", \"blockSuppressionForNoSpace\")\n self.centerMarkSize = config.getfloat(\"dimension_options\", \"centerMarkSize\")\n\n # adattamento del testo e delle frecce\n self.textBlockAdjust = config.getint(\"dimension_options\", \"textBlockAdjust\")\n\n # linee di estensione\n self.extLine1Show = config.getboolean(\"dimension_options\", \"extLine1Show\")\n self.extLine2Show = config.getboolean(\"dimension_options\", \"extLine2Show\")\n self.extLine1LineType = config.get(\"dimension_options\", \"extLine1LineType\")\n self.extLine2LineType = config.get(\"dimension_options\", \"extLine2LineType\")\n self.extLineColor = config.get(\"dimension_options\", \"extLineColor\")\n self.extLineOffsetDimLine = config.getfloat(\"dimension_options\", \"extLineOffsetDimLine\")\n self.extLineOffsetOrigPoints = config.getfloat(\"dimension_options\", \"extLineOffsetOrigPoints\")\n self.extLineIsFixedLen = config.getboolean(\"dimension_options\", \"extLineIsFixedLen\")\n self.extLineFixedLen = config.getfloat(\"dimension_options\", \"extLineFixedLen\")\n\n # layer e loro caratteristiche\n self.textualLayerName = config.get(\"dimension_options\", \"textualLayerName\")\n self.linearLayerName = config.get(\"dimension_options\", \"linearLayerName\")\n self.symbolLayerName = config.get(\"dimension_options\", \"symbolLayerName\")\n \n self.componentFieldName = config.get(\"dimension_options\", \"componentFieldName\")\n self.symbolFieldName = config.get(\"dimension_options\", \"symbolFieldName\")\n self.lineTypeFieldName = config.get(\"dimension_options\", \"lineTypeFieldName\")\n self.colorFieldName = config.get(\"dimension_options\", \"colorFieldName\")\n self.idFieldName = config.get(\"dimension_options\", \"idFieldName\")\n self.idParentFieldName = config.get(\"dimension_options\", \"idParentFieldName\")\n self.dimStyleFieldName = config.get(\"dimension_options\", \"dimStyleFieldName\")\n self.dimTypeFieldName = config.get(\"dimension_options\", \"dimTypeFieldName\")\n self.scaleFieldName = config.get(\"dimension_options\", \"scaleFieldName\")\n self.rotFieldName = config.get(\"dimension_options\", \"rotFieldName\")\n \n self.path = _path\n \n return True\n\n\n #============================================================================\n # remove\n #============================================================================\n def remove(self):\n \"\"\"\n Cancella il file delle impostazioni dello stile di quotatura.\n \"\"\"\n currDimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n if self.name == currDimStyleName: # lo stile da cancellare è quello corrente\n return False\n \n if self.path is not None and self.path != \"\":\n if os.path.exists(self.path):\n try:\n os.remove(self.path)\n except:\n return False\n \n return True\n\n #============================================================================\n # rename\n #============================================================================\n def rename(self, newName):\n \"\"\"\n Rinomina il nome dello stile e del file delle impostazioni dello stile di quotatura.\n \"\"\"\n if newName == self.name: # nome uguale\n return True\n oldName = self.name\n \n if self.path is not None or self.path != \"\":\n if os.path.exists(self.path):\n try:\n dir, base = os.path.split(self.path)\n dir = QDir.cleanPath(dir) + \"/\"\n \n name, ext = os.path.splitext(base)\n newPath = dir + \"/\" + newName + ext\n \n os.rename(self.path, newPath)\n self.path = newPath\n self.name = newName\n self.save()\n except:\n return False\n else:\n self.name = newName\n\n currDimStyleName = QadVariables.get(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"))\n if oldName == currDimStyleName: # lo stile da rinominare è quello corrente\n QadVariables.set(QadMsg.translate(\"Environment variables\", \"DIMSTYLE\"), newName)\n\n self.name = newName\n return True\n\n\n #============================================================================\n # getInValidErrMsg\n #============================================================================\n def getInValidErrMsg(self):\n \"\"\"\n Verifica se lo stile di quotatura é invalido e in caso affermativo ritorna il messaggio di errore.\n Se la quotatura é valida ritorna None.\n \"\"\"\n prefix = QadMsg.translate(\"Dimension\", \"\\nThe dimension style \\\"{0}\\\" \").format(self.name)\n \n if self.getTextualLayer() is None:\n return prefix + QadMsg.translate(\"Dimension\", \"has not the textual layer for dimension.\\n\")\n if qad_layer.isTextLayer(self.getTextualLayer()) == False:\n errMsg = prefix + QadMsg.translate(\"Dimension\", \"has the textual layer for dimension which is not a textual layer.\") \n errMsg = errMsg + QadMsg.translate(\"QAD\", \"\\nA textual layer is a vectorial punctual layer having a label and the symbol transparency no more than 10%.\\n\")\n return errMsg\n\n if self.getSymbolLayer() is None:\n return prefix + QadMsg.translate(\"Dimension\", \"has not the symbol layer for dimension.\\n\")\n if qad_layer.isSymbolLayer(self.getSymbolLayer()) == False:\n errMsg = prefix + QadMsg.translate(\"Dimension\", \"has the symbol layer for dimension which is not a symbol layer.\") \n errMsg = errMsg + QadMsg.translate(\"QAD\", \"\\nA symbol layer is a vectorial punctual layer without label.\\n\")\n return errMsg\n\n if self.getLinearLayer() is None:\n return prefix + QadMsg.translate(\"Dimension\", \"has not the linear layer for dimension.\\n\")\n # deve essere un VectorLayer di tipo linea\n if (self.getLinearLayer().type() != QgsMapLayer.VectorLayer) or (self.getLinearLayer().geometryType() != QGis.Line):\n errMsg = prefix + QadMsg.translate(\"Dimension\", \"has the linear layer for dimension which is not a linear layer.\") \n return errMsg\n # i layer devono avere lo stesso sistema di coordinate\n if not (self.getTextualLayer().crs() == self.getLinearLayer().crs() and self.getLinearLayer().crs() == self.getSymbolLayer().crs()):\n errMsg = prefix + QadMsg.translate(\"Dimension\", \"has not the layers with the same coordinate reference system.\") \n return errMsg\n \n return None\n \n \n #===============================================================================\n # getNotGraphEditableErrMsg\n #===============================================================================\n def getNotGraphEditableErrMsg(self):\n \"\"\"\n Verifica se i layer dello stile di quotatura sono in sola lettura e in caso affermativo ritorna il messaggio di errore.\n Se i layer dello stile di quotatura sono modificabili ritorna None.\n \"\"\"\n prefix = QadMsg.translate(\"Dimension\", \"\\nThe dimension style \\\"{0}\\\" \").format(self.name)\n \n provider = self.getTextualLayer().dataProvider()\n if not (provider.capabilities() & QgsVectorDataProvider.EditingCapabilities):\n return prefix + QadMsg.translate(\"Dimension\", \"has the textual layer not editable.\\n\")\n if not self.getTextualLayer().isEditable():\n return prefix + QadMsg.translate(\"Dimension\", \"has the textual layer not editable.\\n\")\n\n provider = self.getSymbolLayer().dataProvider()\n if not (provider.capabilities() & QgsVectorDataProvider.EditingCapabilities):\n return prefix + QadMsg.translate(\"Dimension\", \"has the symbol layer not editable.\\n\")\n if not self.getSymbolLayer().isEditable():\n return prefix + QadMsg.translate(\"Dimension\", \"has the symbol layer not editable.\\n\")\n \n provider = self.getLinearLayer().dataProvider()\n if not (provider.capabilities() & QgsVectorDataProvider.EditingCapabilities):\n return prefix + QadMsg.translate(\"Dimension\", \"has the linear layer not editable.\\n\")\n if not self.getLinearLayer().isEditable():\n return prefix + QadMsg.translate(\"Dimension\", \"has the linear layer not editable.\\n\")\n \n return None\n \n \n #============================================================================\n # adjustLineAccordingTextRect\n #============================================================================\n def adjustLineAccordingTextRect(self, textRect, pt1, pt2, textLinearDimComponentOn):\n \"\"\"\n Data una linea (pt1-pt2), che tipo di componente di quota rappresenta (textLinearDimComponentOn)\n e un rettangolo che rappresenta l'occupazione del testo di quota, la funzione restituisce\n due linee (possono essere None) in modo che il testo non si sovrapponga alla linea e che le \n impostazioni di quota siano rispettate (dimLine1Show, dimLine2Show, extLine1Show, extLine2Show)\n \"\"\" \n line1 = None\n line2 = None \n intPts = self.getIntersectionPtsBetweenTextRectAndLine(textRect, pt1, pt2)\n if textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1: # linea di quota (\"Dimension line\")\n if len(intPts) == 2: # il rettangolo é sulla linea\n if self.dimLine1Show:\n line1 = [pt1, intPts[0]]\n if self.dimLine2Show:\n line2 = [intPts[1], pt2]\n else: # il rettangolo non é sulla linea \n if self.dimLine1Show and self.dimLine2Show:\n line1 = [pt1, pt2]\n else:\n space1, space2 = self.getSpaceForBlock1AndBlock2(textRect, pt1, pt2)\n rot = qad_utils.getAngleBy2Pts(pt1, pt2) # angolo della linea di quota\n intPt1 = qad_utils.getPolarPointByPtAngle(pt1, rot, space1) \n intPt2 = qad_utils.getPolarPointByPtAngle(pt2, rot - math.pi, space2)\n\n if self.dimLine1Show:\n line1 = [pt1, intPt2]\n elif self.dimLine2Show:\n line2 = [pt2, intPt1]\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE1: # prima linea di estensione (\"Extension line 1\")\n if self.extLine1Show:\n if len(intPts) > 0:\n line1 = [pt1, intPts[0]]\n else:\n line1 = [pt1, pt2]\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE2: # seconda linea di estensione (\"Extension line 2\")\n if self.extLine2Show:\n if len(intPts) > 0:\n line1 = [pt1, intPts[0]]\n else:\n line1 = [pt1, pt2]\n elif textLinearDimComponentOn == QadDimComponentEnum.LEADER_LINE: # linea porta quota usata quando il testo é fuori dalla quota (\"Leader\")\n if len(intPts) > 0:\n line1 = [pt1, intPts[0]]\n else:\n line1 = [pt1, pt2]\n\n return line1, line2\n\n \n #============================================================================\n # setDimId\n #============================================================================\n def setDimId(self, dimId, features, parentId = False):\n \"\"\"\n Setta tutte le feature passate nella lista <features> con il codice della quota.\n \"\"\"\n fieldName = self.idParentFieldName if parentId else self.idFieldName\n \n if len(fieldName) == 0:\n return True\n\n i = 0\n tot = len(features)\n while i < tot:\n try:\n f = features[i]\n if f is not None:\n # imposto il codice della quota\n f.setAttribute(fieldName, dimId)\n except:\n return False\n i = i + 1\n return True \n\n\n #============================================================================\n # recodeDimIdOnFeatures\n #============================================================================\n def recodeDimIdOnFeatures(self, oldDimId, newDimId, features, parentId = False):\n \"\"\"\n Cerca tutte le feature passate nella lista <features> con il codice della \n quota oldDimId e le ricodifica con newDimId.\n \"\"\"\n fieldName = self.idParentFieldName if parentId else self.idFieldName\n \n if len(fieldName) == 0:\n return True\n \n i = 0\n tot = len(features)\n while i < tot:\n try:\n f = features[i]\n if f is not None:\n if f.attribute(fieldName) == oldDimId:\n # imposto il codice della quota\n f.setAttribute(fieldName, newDimId)\n except:\n return False\n i = i + 1\n return True \n\n\n def textCommitChangesOnSave(self):\n \"\"\"\n Salva i testi delle quote per ottenere i nuovi ID \n e richiamare updateTextReferencesOnSave tramite il segnale committedFeaturesAdded.\n \"\"\"\n # salvo i testi per avere la codifica definitiva\n if self.getTextualLayer() is not None:\n return self.getTextualLayer().commitChanges()\n else:\n return False\n\n\n #============================================================================\n # updateTextReferencesOnSave\n #============================================================================\n def updateTextReferencesOnSave(self, plugIn, textAddedFeatures):\n \"\"\"\n Aggiorna e salva i reference delle features dello stile di quotatura contenuti in textAddedFeatures.\n \"\"\"\n if self.startEditing() == False:\n return False \n \n plugIn.beginEditCommand(\"Dimension recoded\", [self.getSymbolLayer(), self.getLinearLayer(), self.getTextualLayer()])\n \n entity = QadEntity()\n for f in textAddedFeatures:\n entity.set(self.getTextualLayer(), f.id())\n oldDimId = entity.getAttribute(self.idFieldName)\n newDimId = f.id() \n if oldDimId is None or self.recodeDimId(plugIn, oldDimId, newDimId) == False:\n return False\n\n plugIn.endEditCommand()\n \n return True\n\n\n #============================================================================\n # startEditing\n #============================================================================\n def startEditing(self):\n if self.getTextualLayer() is not None and self.getTextualLayer().isEditable() == False:\n if self.getTextualLayer().startEditing() == False:\n return False \n if self.getLinearLayer() is not None and self.getLinearLayer().isEditable() == False:\n if self.getLinearLayer().startEditing() == False:\n return False \n if self.getSymbolLayer() is not None and self.getSymbolLayer().isEditable() == False:\n if self.getSymbolLayer().startEditing() == False:\n return False \n\n\n #============================================================================\n # commitChanges\n #============================================================================\n def commitChanges(self, excludedLayer):\n if self.startEditing() == False:\n return False \n \n if (excludedLayer is None) or excludedLayer.id() != self.getTextualLayer().id():\n # salvo le entità testuali\n self.getTextualLayer().commitChanges()\n if (excludedLayer is None) or excludedLayer.id() != self.getLinearLayer().id():\n # salvo le entità lineari\n self.getLinearLayer().commitChanges()\n if (excludedLayer is None) or excludedLayer.id() != self.getSymbolLayer().id():\n # salvo le entità puntuali\n self.getSymbolLayer().commitChanges()\n \n\n #============================================================================\n # recodeDimId\n #============================================================================\n def getEntitySet(self, dimId):\n \"\"\"\n Ricava un QadEntitySet con tutte le feature della quota dimId.\n \"\"\"\n result = QadEntitySet()\n if len(self.idFieldName) == 0 or len(self.idParentFieldName) == 0:\n return result\n \n layerEntitySet = QadLayerEntitySet()\n \n # ricerco l'entità testo\n expression = \"\\\"\" + self.idFieldName + \"\\\"=\" + str(dimId)\n featureIter = self.getTextualLayer().getFeatures(QgsFeatureRequest().setFilterExpression(expression))\n layerEntitySet.set(self.getTextualLayer())\n layerEntitySet.addFeatures(featureIter)\n result.addLayerEntitySet(layerEntitySet)\n\n expression = \"\\\"\" + self.idParentFieldName + \"\\\"=\" + str(dimId) \n\n # ricerco le entità linea\n layerEntitySet.clear()\n featureIter = self.getLinearLayer().getFeatures(QgsFeatureRequest().setFilterExpression(expression))\n layerEntitySet.set(self.getLinearLayer())\n layerEntitySet.addFeatures(featureIter)\n result.addLayerEntitySet(layerEntitySet)\n\n # ricerco e setto id_parent per le entità puntuali\n layerEntitySet.clear()\n featureIter = self.getSymbolLayer().getFeatures(QgsFeatureRequest().setFilterExpression(expression)) \n layerEntitySet.set(self.getSymbolLayer())\n layerEntitySet.addFeatures(featureIter)\n result.addLayerEntitySet(layerEntitySet)\n\n return result\n \n \n #============================================================================\n # recodeDimId\n #============================================================================\n def recodeDimId(self, plugIn, oldDimId, newDimId):\n \"\"\"\n Ricodifica tutte le feature della quota oldDimId con il nuovo codice newDimId.\n \"\"\"\n if len(self.idFieldName) == 0 or len(self.idParentFieldName) == 0:\n return True\n \n entitySet = self.getEntitySet(oldDimId)\n\n # setto l'entità testo\n layerEntitySet = entitySet.findLayerEntitySet(self.getTextualLayer())\n if layerEntitySet is not None:\n features = layerEntitySet.getFeatureCollection()\n if self.setDimId(newDimId, features, False) == False:\n return False\n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(plugIn, self.getTextualLayer(), features, False, False) == False:\n return False\n \n # setto id_parent per le entità linea\n layerEntitySet = entitySet.findLayerEntitySet(self.getLinearLayer())\n if layerEntitySet is not None:\n features = layerEntitySet.getFeatureCollection()\n if self.setDimId(newDimId, features, True) == False:\n return False\n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(plugIn, self.getLinearLayer(), features, False, False) == False:\n return False\n \n # setto id_parent per le entità puntuali\n layerEntitySet = entitySet.findLayerEntitySet(self.getSymbolLayer())\n if layerEntitySet is not None:\n features = layerEntitySet.getFeatureCollection()\n if self.setDimId(newDimId, features, True) == False:\n return False\n # plugIn, layer, features, refresh, check_validity\n if qad_layer.updateFeaturesToLayer(plugIn, self.getSymbolLayer(), features, False, False) == False:\n return False\n\n return True\n\n\n #============================================================================\n # getDimIdByEntity\n #============================================================================\n def getDimIdByEntity(self, entity):\n \"\"\"\n La funzione, data un'entità, verifica se fa parte dello stile di quotatura e,\n in caso di successo, restituisce il codice della quotatura altrimenti None.\n In più, la funzione, setta il tipo di quotatura se é possibile.\n \"\"\"\n if entity.layer.name() == self.textualLayerName:\n dimId = entity.getAttribute(self.idFieldName)\n if dimId is None:\n return None\n f = entity.getFeature()\n elif entity.layer.name() == self.linearLayerName or \\\n entity.layer.name() == self.symbolLayerName:\n dimId = entity.getAttribute(self.idParentFieldName)\n if dimId is None:\n return None\n # ricerco l'entità testo\n expression = \"\\\"\" + self.idFieldName + \"\\\"=\" + str(dimId)\n f = QgsFeature()\n if self.getTextualLayer().getFeatures(QgsFeatureRequest().setFilterExpression(expression)).nextFeature(f) == False:\n return None\n else:\n return None\n\n try:\n # leggo il nome dello stile di quotatura\n dimName = f.attribute(self.dimStyleFieldName)\n if dimName != self.name:\n return None \n except:\n return None\n \n try:\n # leggo il tipo dello stile di quotatura\n self.dimType = f.attribute(self.dimTypeFieldName) \n except:\n pass\n \n return dimId\n \n\n #============================================================================\n # isDimLayer\n #============================================================================\n def isDimLayer(self, layer):\n \"\"\"\n La funzione, dato un layer, verifica se fa parte dello stile di quotatura.\n \"\"\"\n if layer.name() == self.textualLayerName or \\\n layer.name() == self.linearLayerName or \\\n layer.name() == self.symbolLayerName:\n return True\n else:\n return False\n\n\n #============================================================================\n # getFilteredFeatureCollection\n #============================================================================\n def getFilteredFeatureCollection(self, layerEntitySet):\n \"\"\"\n La funzione, dato un QadLayerEntitySet, filtra e restituisce solo quelle appartenenti allo stile di quotatura.\n \"\"\"\n result = []\n entity = QadEntity()\n for f in layerEntitySet.getFeatureCollection():\n entity.set(layerEntitySet.layer, f.id())\n if self.getDimIdByEntity(entity) is not None:\n result.append(f)\n \n return result\n\n\n #============================================================================\n # FUNZIONI PER I BLOCCHI - INIZIO\n #============================================================================\n\n \n #============================================================================\n # getBlock1Size\n #============================================================================\n def getBlock1Size(self):\n \"\"\"\n Restituisce la dimensione del blocco 1 delle frecce in unità di mappa.\n \"\"\"\n return 0 if self.block1Name == \"\" else self.blockWidth * self.blockScale\n\n\n #============================================================================\n # getBlock2Size\n #============================================================================\n def getBlock2Size(self):\n \"\"\"\n Restituisce la dimensione del blocco 2 delle frecce in unità di mappa.\n \"\"\"\n # blockWidth = larghezza del simbolo (in orizzontale) quando la dimensione in unità di mappa = 1 (vedi \"triangle2\")\n # blockScale = scala della dimensione del simbolo (DIMASZ)\n return 0 if self.block2Name == \"\" else self.blockWidth * self.blockScale\n \n \n #============================================================================\n # getBlocksRot\n #============================================================================\n def getBlocksRot(self, dimLinePt1, dimLinePt2, inside):\n \"\"\"\n Restituisce una lista di 2 elementi che descrivono le rotazioni dei due blocchi:\n - il primo elemento é la rotazione del blocco 1\n - il secondo elemento é la rotazione del blocco 2\n \n dimLinePt1 = primo punto della linea di quota (QgsPoint)\n dimLinePt2 = secondo punto della linea di quota (QgsPoint)\n inside = flag di modo, se = true le frecce sono interne altrimenti sono esterne\n \"\"\"\n rot = qad_utils.getAngleBy2Pts(dimLinePt1, dimLinePt2) # angolo della linea di quota\n if inside:\n rot1 = rot + math.pi\n rot2 = rot\n else:\n rot1 = rot\n rot2 = rot + math.pi\n \n return qad_utils.normalizeAngle(rot1), qad_utils.normalizeAngle(rot2)\n\n\n #============================================================================\n # getSpaceForBlock1AndBlock2\n #============================================================================\n def getSpaceForBlock1AndBlock2Auxiliary(self, dimLinePt1, dimLinePt2, rectCorner):\n # calcolo la proiezione di un vertice del rettangolo sulla linea dimLinePt1, dimLinePt2\n perpPt = qad_utils.getPerpendicularPointOnInfinityLine(dimLinePt1, dimLinePt2, rectCorner)\n # se la proienzione non é nel segmento\n if qad_utils.isPtOnSegment(dimLinePt1, dimLinePt2, perpPt) == False:\n # se la proiezione ricade oltre il punto dimLinePt1\n if qad_utils.getDistance(dimLinePt1, perpPt) < qad_utils.getDistance(dimLinePt2, perpPt):\n return 0, qad_utils.getDistance(dimLinePt1, dimLinePt2) \n else: # se la proiezione ricade oltre il punto dimLinePt2\n return qad_utils.getDistance(dimLinePt1, dimLinePt2), 0\n else:\n return qad_utils.getDistance(dimLinePt1, perpPt), qad_utils.getDistance(dimLinePt2, perpPt)\n \n def getSpaceForBlock1AndBlock2(self, txtRect, dimLinePt1, dimLinePt2):\n \"\"\"\n txtRect = rettangolo di occupazione del testo o None se non c'é il testo\n dimLinePt1 = primo punto della linea di quotatura\n dimLinePt2 = primo punto della linea di quotatura\n Restituisce lo spazio disponibile per i blocchi 1 e 2 considerando il rettangolo (QadLinearObjectList) che rappresenta il testo\n e la linea di quota dimLinePt1-dimLinePt2.\n \"\"\"\n if txtRect is None: # se non c'é il testo (é stato spostato fuori dalla linea di quota)\n spaceForBlock1 = qad_utils.getDistance(dimLinePt1, dimLinePt2) / 2\n spaceForBlock2 = spaceForBlock1\n else:\n # calcolo la proiezione dei quattro vertici del rettangolo sulla linea dimLinePt1, dimLinePt2\n linearObject = txtRect.getLinearObjectAt(0)\n partial1SpaceForBlock1, partial1SpaceForBlock2 = self.getSpaceForBlock1AndBlock2Auxiliary(dimLinePt1, dimLinePt2, \\\n linearObject.getStartPt())\n linearObject = txtRect.getLinearObjectAt(1)\n partial2SpaceForBlock1, partial2SpaceForBlock2 = self.getSpaceForBlock1AndBlock2Auxiliary(dimLinePt1, dimLinePt2, \\\n linearObject.getStartPt())\n spaceForBlock1 = partial1SpaceForBlock1 if partial1SpaceForBlock1 < partial2SpaceForBlock1 else partial2SpaceForBlock1\n spaceForBlock2 = partial1SpaceForBlock2 if partial1SpaceForBlock2 < partial2SpaceForBlock2 else partial2SpaceForBlock2\n \n linearObject = txtRect.getLinearObjectAt(2)\n partial3SpaceForBlock1, partial3SpaceForBlock2 = self.getSpaceForBlock1AndBlock2Auxiliary(dimLinePt1, dimLinePt2, \\\n linearObject.getStartPt())\n if partial3SpaceForBlock1 < spaceForBlock1:\n spaceForBlock1 = partial3SpaceForBlock1\n if partial3SpaceForBlock2 < spaceForBlock2:\n spaceForBlock2 = partial3SpaceForBlock2\n \n linearObject = txtRect.getLinearObjectAt(3)\n partial4SpaceForBlock1, partial4SpaceForBlock2 = self.getSpaceForBlock1AndBlock2Auxiliary(dimLinePt1, dimLinePt2, \\\n linearObject.getStartPt())\n if partial4SpaceForBlock1 < spaceForBlock1:\n spaceForBlock1 = partial4SpaceForBlock1\n if partial4SpaceForBlock2 < spaceForBlock2:\n spaceForBlock2 = partial4SpaceForBlock2\n\n return spaceForBlock1, spaceForBlock2\n\n\n #============================================================================\n # getSymbolFeature\n #============================================================================\n def getSymbolFeature(self, insPt, rot, isBlock1, textLinearDimComponentOn, sourceCrs = None):\n \"\"\"\n Restituisce la feature per il simbolo delle frecce.\n insPt = punto di inserimento\n rot = rotazione espressa in radianti\n isBlock1 = se True si tratta del blocco1 altrimenti del blocco2\n textLinearDimComponentOn = indica il componente della quota dove é situato il testo di quota (QadDimComponentEnum)\n sourceCrs = sistema di coordinate di insPt\n \"\"\" \n # se non c'é il simbolo di quota\n if insPt is None or rot is None:\n return None \n # se si tratta del simbolo 1\n if isBlock1 == True:\n # se non deve essere mostrata la linea 1 di quota (vale solo se il testo é sulla linea di quota)\n if self.dimLine1Show == False and \\\n (textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1 or textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE2):\n return None\n else: # se si tratta del simbolo 2\n # se non deve essere mostrata la linea 2 di quota (vale solo se il testo é sulla linea di quota)\n if self.dimLine2Show == False and \\\n (textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1 or textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE2):\n return None\n \n f = QgsFeature(self.getSymbolFeaturePrototype())\n g = QgsGeometry.fromPoint(insPt)\n \n if (sourceCrs is not None) and sourceCrs != self.getSymbolLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getSymbolLayer().crs()) # trasformo la geometria\n g.transform(coordTransform) \n\n f.setGeometry(g)\n\n # imposto la scala del blocco\n try:\n if len(self.scaleFieldName) > 0:\n f.setAttribute(self.scaleFieldName, self.blockScale)\n except:\n pass\n\n # imposto la rotazione\n try:\n if len(self.rotFieldName) > 0:\n f.setAttribute(self.rotFieldName, qad_utils.toDegrees(rot)) # Converte da radianti a gradi\n except:\n pass\n\n # imposto il colore\n try:\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.dimLineColor) \n except:\n pass\n \n # imposto il tipo di componente della quotatura\n if self.dimType == QadDimTypeEnum.RADIUS: # se quotatura tipo raggio\n try:\n if len(self.componentFieldName) > 0:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.LEADER_BLOCK)\n except:\n pass\n \n try:\n if len(self.symbolFieldName) > 0:\n f.setAttribute(self.symbolFieldName, self.blockLeaderName)\n except:\n pass \n else:\n try:\n if len(self.componentFieldName) > 0:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.BLOCK1 if isBlock1 else QadDimComponentEnum.BLOCK2)\n except:\n pass \n\n try:\n if len(self.symbolFieldName) > 0:\n f.setAttribute(self.symbolFieldName, self.block1Name if isBlock1 else self.block2Name)\n except:\n pass\n\n return f\n\n\n #============================================================================\n # getDimPointFeature\n #============================================================================\n def getDimPointFeature(self, insPt, isDimPt1, sourceCrs):\n \"\"\"\n Restituisce la feature per il punto di quotatura.\n insPt = punto di inserimento\n isDimPt1 = se True si tratta del punto di quotatura 1 altrimenti del punto di quotatura 2\n sourceCrs = sistema di coordinate di insPt\n \"\"\"\n symbolFeaturePrototype = self.getSymbolFeaturePrototype()\n if symbolFeaturePrototype is None:\n return None\n f = QgsFeature(symbolFeaturePrototype)\n g = QgsGeometry.fromPoint(insPt)\n \n if (sourceCrs is not None) and sourceCrs != self.getSymbolLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getSymbolLayer().crs()) # trasformo la geometria\n g.transform(coordTransform) \n \n f.setGeometry(g)\n \n # imposto il tipo di componente della quotatura\n try:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.DIM_PT1 if isDimPt1 else QadDimComponentEnum.DIM_PT2)\n except:\n pass\n\n try:\n # imposto il colore\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.dimLineColor) \n except:\n pass\n\n return f\n\n\n #============================================================================\n # FUNZIONI PER I BLOCCHI - FINE\n # FUNZIONI PER IL TESTO - INIZIO\n #============================================================================\n\n\n #============================================================================\n # getFormattedText\n #============================================================================\n def getFormattedText(self, measure):\n \"\"\"\n Restituisce il testo della misura della quota formattato\n \"\"\"\n if type(measure) == int or type(measure) == float:\n strIntPart, strDecPart = qad_utils.getStrIntDecParts(round(measure, self.textDecimals)) # numero di decimali\n \n if strIntPart == \"0\" and self.textSuppressLeadingZeros == True: # per sopprimere o meno gli zero all'inizio del testo\n strIntPart = \"\"\n \n for i in xrange(0, self.textDecimals - len(strDecPart), 1): # aggiunge \"0\" per arrivare al numero di decimali\n strDecPart = strDecPart + \"0\"\n \n if self.textDecimalZerosSuppression == True: # per sopprimere gli zero finali nei decimali\n strDecPart = strDecPart.rstrip(\"0\")\n \n formattedText = \"-\" if measure < 0 else \"\" # segno\n formattedText = formattedText + strIntPart # parte intera\n if len(strDecPart) > 0: # parte decimale\n formattedText = formattedText + self.textDecimalSep + strDecPart # Separatore dei decimali\n # aggiungo prefisso e suffisso per il testo della quota\n return self.textPrefix + formattedText + self.textSuffix\n elif type(measure) == unicode or type(measure) == str:\n return measure\n else:\n return \"\"\n\n\n #============================================================================\n # getNumericText\n #============================================================================\n def getNumericText(self, text):\n \"\"\"\n Restituisce il valore numerico del testo della misura della quota formattato\n \"\"\"\n textToConvert = text.lstrip(self.textPrefix)\n textToConvert = textToConvert.rstrip(self.textSuffix)\n textToConvert = textToConvert.replace(self.textDecimalSep, \".\")\n\n return qad_utils.str2float(textToConvert)\n\n \n #============================================================================\n # textRectToQadLinearObjectList\n #============================================================================\n def textRectToQadLinearObjectList(self, ptBottomLeft, textWidth, textHeight, rot):\n \"\"\"\n Restituisce il rettangolo che rappresenta il testo sotto forma di una QadLinearObjectList.\n <2>----width----<3>\n | |\n height height\n | |\n <1>----width----<4> \n \"\"\"\n pt2 = qad_utils.getPolarPointByPtAngle(ptBottomLeft, rot + (math.pi / 2), textHeight) \n pt3 = qad_utils.getPolarPointByPtAngle(pt2, rot, textWidth) \n pt4 = qad_utils.getPolarPointByPtAngle(ptBottomLeft, rot , textWidth)\n res = qad_utils.QadLinearObjectList()\n res.fromPolyline([ptBottomLeft, pt2, pt3, pt4, ptBottomLeft])\n return res\n\n\n #============================================================================\n # getBoundingPointsTextRectProjectedToLine\n #============================================================================\n def getBoundingPointsTextRectProjectedToLine(self, pt1, pt2, textRect):\n \"\"\"\n Restituisce una lista di 2 punti che sono i punti estremi della proiezione dei 4 angoli del rettangolo\n sulla linea pt1-pt2.\n \"\"\"\n rectCorners = textRect.asPolyline()\n # calcolo la proiezione degli angoli del rettangolo sulla linea pt1-pt2\n perpPts = []\n \n qad_utils.appendUniquePointToList(perpPts, qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectCorners[0])) \n qad_utils.appendUniquePointToList(perpPts, qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectCorners[1]))\n qad_utils.appendUniquePointToList(perpPts, qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectCorners[2]))\n qad_utils.appendUniquePointToList(perpPts, qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectCorners[3]))\n \n return qad_utils.getBoundingPtsOnOnInfinityLine(pt1, pt2, perpPts)\n\n\n #============================================================================\n # getIntersectionPtsBetweenTextRectAndLine\n #============================================================================\n def getIntersectionPtsBetweenTextRectAndLine(self, rect, pt1, pt2):\n \"\"\"\n Restituisce i punti di intersezione tra il rettangolo (QadLinearObjectList) che rappresenta il testo\n e un segmento pt1-pt2. La lista é ordinata per distanza da pt1.\n \"\"\"\n segment = qad_utils.QadLinearObject([pt1, pt2])\n return rect.getIntersectionPtsWithLinearObject(segment, True)[0] # orderByStartPtOfPart = True\n \n\n #============================================================================\n # getTextPositionOnLine\n #============================================================================\n def getTextPositionOnLine(self, pt1, pt2, textWidth, textHeight, horizontalPos, verticalPos, rotMode):\n \"\"\"\n pt1 = primo punto della linea\n pt2 = secondo punto della linea\n textWidth = larghezza testo\n textHeight = altezza testo\n \n Restituisce il punto di inserimento e la rotazione del testo lungo la linea pt1-pt2 con le modalità:\n horizontalPos = QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE (centrato alla linea)\n QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE (vicino al punto pt1)\n QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE (vicino al punto pt2)\n verticalPos = QadDimStyleTxtVerticalPosEnum.CENTERED_LINE (centrato alla linea)\n QadDimStyleTxtVerticalPosEnum.ABOVE_LINE (sopra alla linea)\n QadDimStyleTxtVerticalPosEnum.BELOW_LINE (sotto alla linea)\n rotMode = QadDimStyleTxtRotModeEnum.HORIZONTAL (testo orizzontale)\n QadDimStyleTxtRotModeEnum.ALIGNED_LINE (testo allineato con la linea)\n QadDimStyleTxtRotModeEnum.FORCED_ROTATION (testo con rotazione forzata)\n \"\"\"\n lineRot = qad_utils.getAngleBy2Pts(pt1, pt2) # angolo della linea\n \n if (lineRot > math.pi * 3 / 2 and lineRot <= math.pi * 2) or \\\n (lineRot >= 0 and lineRot <= math.pi / 2): # da sx a dx\n textInsPtCloseToPt1 = True\n else: # da dx a sx\n textInsPtCloseToPt1 = False\n \n if rotMode == QadDimStyleTxtRotModeEnum.ALIGNED_LINE: # testo allineato alla linea \n if lineRot > (math.pi / 2) and lineRot <= math.pi * 3 / 2: # se il testo é capovolto lo giro\n textRot = lineRot - math.pi\n else:\n textRot = lineRot\n \n # allineamento orizzontale\n #=========================\n if horizontalPos == QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE: # testo centrato alla linea\n middlePt = qad_utils.getMiddlePoint(pt1, pt2)\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(middlePt, lineRot - math.pi, textWidth / 2) \n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(middlePt, lineRot, textWidth / 2)\n \n elif horizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE: # testo vicino a pt1\n # uso 2 volte textOffsetDist perché una volta é la distanza dal punto pt1 + un offset intorno al testo\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(pt1, lineRot, self.textOffsetDist + self.textOffsetDist)\n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(pt1, lineRot, textWidth + self.textOffsetDist + self.textOffsetDist)\n\n elif horizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE: # testo vicino a pt2\n # uso 2 volte textOffsetDist perché una volta é la distanza dal punto pt1 + un offset intorno al testo\n lineLen = qad_utils.getDistance(pt1, pt2)\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(pt1, lineRot, lineLen - textWidth - (self.textOffsetDist + self.textOffsetDist))\n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(pt1, lineRot, lineLen - (self.textOffsetDist + self.textOffsetDist)) \n\n # allineamento verticale\n #=========================\n if verticalPos == QadDimStyleTxtVerticalPosEnum.CENTERED_LINE: # testo centrato alla linea\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot - math.pi / 2, textHeight / 2)\n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot + math.pi / 2, textHeight / 2)\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # uso 2 volte textOffsetDist perché una volta é la distanza dalla linea + un offset intorno al testo\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot + math.pi / 2, self.textOffsetDist + self.textOffsetDist)\n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot - math.pi / 2, self.textOffsetDist + self.textOffsetDist)\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # uso 2 volte textOffsetDist perché una volta é la distanza dalla linea + un offset intorno al testo\n if textInsPtCloseToPt1: # il punto di inserimento del testo é vicino a pt1\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot - math.pi / 2, textHeight + (self.textOffsetDist + self.textOffsetDist))\n else: # il punto di inserimento del testo é vicino a pt2\n insPt = qad_utils.getPolarPointByPtAngle(insPt, lineRot + math.pi / 2, textHeight + (self.textOffsetDist + self.textOffsetDist))\n \n # testo orizzontale o testo con rotazione forzata\n elif rotMode == QadDimStyleTxtRotModeEnum.HORIZONTAL or rotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION:\n \n lineLen = qad_utils.getDistance(pt1, pt2) # lunghezza della linea\n textRot = 0.0 if rotMode == QadDimStyleTxtRotModeEnum.HORIZONTAL else self.textForcedRot\n \n # cerco qual'é l'angolo del rettangolo più vicino alla linea\n # <2>----width----<3>\n # | |\n # height height\n # | |\n # <1>----width----<4>\n # ricavo il rettangolo che racchiude il testo e lo posiziono con il suo angolo in basso a sinistra sul punto pt1\n textRect = self.textRectToQadLinearObjectList(pt1, textWidth, textHeight, textRot)\n # ottengo i punti estremi della proiezione del rettangolo sulla linea\n pts = self.getBoundingPointsTextRectProjectedToLine(pt1, pt2, textRect)\n projectedTextWidth = qad_utils.getDistance(pts[0], pts[1])\n\n # allineamento orizzontale\n #=========================\n if horizontalPos == QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE: # testo centrato alla linea\n closestPtToPt1 = qad_utils.getPolarPointByPtAngle(pt1, lineRot, (lineLen - projectedTextWidth) / 2)\n \n elif horizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE: # testo vicino a pt1\n closestPtToPt1 = qad_utils.getPolarPointByPtAngle(pt1, lineRot, self.textOffsetDist)\n \n elif horizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE: # testo vicino a pt2\n closestPtToPt1 = qad_utils.getPolarPointByPtAngle(pt1, lineRot, lineLen - self.textOffsetDist - projectedTextWidth)\n \n # se la linea ha una angolo tra (0-90] gradi (primo quadrante)\n if lineRot > 0 and lineRot <= math.pi / 2:\n # il punto più vicino a pt1 corrisponde all'angolo in basso a sinistra del rettangolo che racchiude il testo\n # mi ricavo il punto di inserimento del testo (angolo in basso a sinistra) \n insPt = QgsPoint(closestPtToPt1)\n textRect = self.textRectToQadLinearObjectList(insPt, textWidth, textHeight, textRot)\n rectCorners = textRect.asPolyline()\n \n # allineamento verticale\n #=========================\n if verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # l'angolo 4 deve essere sopra la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[3]\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # l'angolo 2 deve essere sotto la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[1]\n \n # se la linea ha una angolo tra (90-180] gradi (secondo quadrante)\n elif lineRot > math.pi / 2 and lineRot <= math.pi:\n # il punto più vicino a pt1 corrisponde all'angolo in basso a destra del rettangolo che racchiude il testo\n # mi ricavo il punto di inserimento del testo (angolo in basso a sinistra) \n insPt = QgsPoint(closestPtToPt1.x() - textWidth, closestPtToPt1.y())\n textRect = self.textRectToQadLinearObjectList(insPt, textWidth, textHeight, textRot)\n rectCorners = textRect.asPolyline()\n \n # allineamento verticale\n #=========================\n if verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # l'angolo 1 deve essere sopra la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[0]\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # l'angolo 3 deve essere sotto la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[2]\n \n # se la linea ha una angolo tra (180-270] gradi (terzo quadrante)\n elif lineRot > math.pi and lineRot <= math.pi * 3 / 2:\n # il punto più vicino a pt1 corrisponde all'angolo in alto a destra del rettangolo che racchiude il testo\n # mi ricavo il punto di inserimento del testo (angolo in basso a sinistra) \n insPt = QgsPoint(closestPtToPt1.x() - textWidth, closestPtToPt1.y() - textHeight)\n textRect = self.textRectToQadLinearObjectList(insPt, textWidth, textHeight, textRot)\n rectCorners = textRect.asPolyline()\n\n # allineamento verticale\n #=========================\n if verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # l'angolo 4 deve essere sopra la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[3]\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # l'angolo 2 deve essere sotto la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[1]\n \n # se la linea ha una angolo tra (270-360] gradi (quarto quadrante)\n elif (lineRot > math.pi * 3 / 2 and lineRot <= 360) or lineRot == 0:\n # il punto più vicino a pt1 corrisponde all'angolo in alto a destra del rettangolo che racchiude il testo\n # mi ricavo il punto di inserimento del testo (angolo in alto a sinistra) \n insPt = QgsPoint(closestPtToPt1.x(), closestPtToPt1.y() - textHeight)\n textRect = self.textRectToQadLinearObjectList(insPt, textWidth, textHeight, textRot)\n rectCorners = textRect.asPolyline()\n \n # allineamento verticale\n #=========================\n if verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # l'angolo 1 deve essere sopra la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[0]\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # l'angolo 3 deve essere sotto la linea distante self.textOffsetDist dalla stessa\n rectPt = rectCorners[2]\n\n # allineamento verticale\n #========================= \n if verticalPos == QadDimStyleTxtVerticalPosEnum.CENTERED_LINE: # testo centrato alla linea\n # il centro del rettangolo deve essere sulla linea\n centerPt = qad_utils.getPolarPointByPtAngle(rectCorners[0], \\\n qad_utils.getAngleBy2Pts(rectCorners[0], rectCorners[2]), \\\n qad_utils.getDistance(rectCorners[0], rectCorners[2]) / 2) \n perpPt = qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, centerPt)\n offsetAngle = qad_utils.getAngleBy2Pts(centerPt, perpPt)\n offsetDist = qad_utils.getDistance(centerPt, perpPt) \n elif verticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE: # sopra alla linea\n # l'angolo deve essere sopra la linea distante self.textOffsetDist dalla stessa\n perpPt = qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectPt)\n # se la linea ha una angolo tra (90-270] gradi\n if lineRot > math.pi / 2 and lineRot <= math.pi * 3 / 2:\n offsetAngle = lineRot - math.pi / 2\n else: # se la linea ha una angolo tra (270-90] gradi\n offsetAngle = lineRot + math.pi / 2\n offsetDist = qad_utils.getDistance(rectPt, perpPt) + self.textOffsetDist\n elif verticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE: # sotto alla linea\n # l'angolo deve essere sotto la linea distante self.textOffsetDist dalla stessa\n perpPt = qad_utils.getPerpendicularPointOnInfinityLine(pt1, pt2, rectPt)\n # se la linea ha una angolo tra (90-270] gradi\n if lineRot > math.pi / 2 and lineRot <= math.pi * 3 / 2:\n offsetAngle = lineRot + math.pi / 2\n else: # se la linea ha una angolo tra (270-90] gradi\n offsetAngle = lineRot - math.pi / 2\n offsetDist = qad_utils.getDistance(rectPt, perpPt) + self.textOffsetDist\n \n # traslo il rettangolo\n insPt = qad_utils.getPolarPointByPtAngle(insPt, offsetAngle, offsetDist)\n textRect = self.textRectToQadLinearObjectList(insPt, textWidth, textHeight, textRot)\n \n return insPt, textRot\n\n\n #============================================================================\n # getTextPosAndLinesOutOfDimLines\n #============================================================================\n def getTextPosAndLinesOutOfDimLines(self, dimLinePt1, dimLinePt2, textWidth, textHeight):\n \"\"\" \n Restituisce una lista di 3 elementi nel caso il testo venga spostato fuori dalle linee \n di estensione perché era troppo grosso:\n - il primo elemento é il punto di inserimento\n - il secondo elemento é la rotazione del testo \n - il terzo elemento é una lista di linee da usare come porta quota\n \n La funzione lo posizione a lato della linea di estensione 2. \n dimLinePt1 = primo punto della linea di quota (QgsPoint)\n dimLinePt2 = secondo punto della linea di quota (QgsPoint)\n textWidth = larghezza testo\n textHeight = altezza testo\n \"\"\"\n # Ottengo le linee porta quota per il testo esterno\n lines = self.getLeaderLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n # considero l'ultima che é quella che si riferisce al testo\n line = lines[-1]\n \n if self.textRotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION:\n textRotMode = QadDimStyleTxtRotModeEnum.FORCED_ROTATION\n else:\n textRotMode = QadDimStyleTxtRotModeEnum.ALIGNED_LINE\n \n textInsPt, textRot = self.getTextPositionOnLine(line[0], line[1], textWidth, textHeight, \\\n QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE, \\\n self.textVerticalPos, textRotMode)\n return textInsPt, textRot, lines\n\n\n #============================================================================\n # getLinearTextAndBlocksPosition\n #============================================================================\n def getLinearTextAndBlocksPosition(self, dimPt1, dimPt2, dimLinePt1, dimLinePt2, textWidth, textHeight):\n \"\"\"\n dimPt1 = primo punto da quotare\n dimPt2 = secondo punto da quotare\n dimLinePt1 = primo punto della linea di quota (QgsPoint)\n dimLinePt2 = secondo punto della linea di quota (QgsPoint)\n textWidth = larghezza testo\n textHeight = altezza testo\n \n Restituisce una lista di 4 elementi:\n - il primo elemento é una lista con il punto di inserimento del testo della quota e la sua rotazione\n - il secondo elemento é una lista con flag che indica il tipo della linea sulla quale é stato messo il testo; vedi QadDimComponentEnum\n e una lista di linee \"leader\" nel caso il testo sia all'esterno della quota\n - il terzo elemento é la rotazione del primo blocco delle frecce; può essere None se non visibile\n - il quarto elemento é la rotazione del secondo blocco delle frecce; può essere None se non visibile \n \"\"\" \n textInsPt = None # punto di inserimento del testo\n textRot = None # rotazione del testo\n textLinearDimComponentOn = None # codice del componente lineare sul quale é posizionato il testo\n txtLeaderLines = None # lista di linee \"leader\" nel caso il testo sia all'esterno della quota\n block1Rot = None # rotazione del primo blocco delle frecce\n block2Rot = None # rotazione del secondo blocco delle frecce\n \n # se il testo é tra le linee di estensione della quota\n if self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.CENTERED_LINE or \\\n self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE or \\\n self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE:\n\n dimLineRot = qad_utils.getAngleBy2Pts(dimLinePt1, dimLinePt2) # angolo della linea di quota\n \n # cambio gli estremi della linea di quota per considerare lo spazio occupato dai blocchi\n dimLinePt1Offset = qad_utils.getPolarPointByPtAngle(dimLinePt1, dimLineRot, self.getBlock1Size())\n dimLinePt2Offset = qad_utils.getPolarPointByPtAngle(dimLinePt2, dimLineRot + math.pi, self.getBlock2Size())\n \n # testo sopra o sotto alla linea di quota nel caso la linea di quota non sia orizzontale \n # e il testo sia dentro le linee di estensione e forzato orizzontale allora il testo diventa centrato\n if (self.textVerticalPos == QadDimStyleTxtVerticalPosEnum.ABOVE_LINE or self.textVerticalPos == QadDimStyleTxtVerticalPosEnum.BELOW_LINE) and \\\n (dimLineRot != 0 and dimLineRot != math.pi) and self.textRotMode == QadDimStyleTxtRotModeEnum.HORIZONTAL: \n textVerticalPos = QadDimStyleTxtVerticalPosEnum.CENTERED_LINE\n # testo posizionato nella parte opposta ai punti di quotatura\n elif self.textVerticalPos == QadDimStyleTxtVerticalPosEnum.EXTERN_LINE:\n # angolo dal primo punto di quota al primo punto della linea di quota\n dimPtToDimLinePt_rot = qad_utils.getAngleBy2Pts(dimPt1, dimLinePt1)\n if dimPtToDimLinePt_rot > 0 and \\\n (dimPtToDimLinePt_rot < math.pi or qad_utils.doubleNear(dimPtToDimLinePt_rot, math.pi)):\n textVerticalPos = QadDimStyleTxtVerticalPosEnum.ABOVE_LINE\n else:\n textVerticalPos = QadDimStyleTxtVerticalPosEnum.BELOW_LINE\n else:\n textVerticalPos = self.textVerticalPos\n \n if self.textRotMode == QadDimStyleTxtRotModeEnum.ISO:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1Offset, dimLinePt2Offset, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, QadDimStyleTxtRotModeEnum.ALIGNED_LINE)\n else:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1Offset, dimLinePt2Offset, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, self.textRotMode)\n \n rect = self.textRectToQadLinearObjectList(textInsPt, textWidth, textHeight, textRot)\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(rect, dimLinePt1, dimLinePt2)\n \n # se lo spazio non é sufficiente per inserire testo e simboli all'interno delle linee di estensione,\n # uso qad_utils.doubleSmaller perché a volte i due numeri sono quasi uguali \n if spaceForBlock1 == 0 or spaceForBlock2 == 0 or \\\n qad_utils.doubleSmaller(spaceForBlock1, self.getBlock1Size() + self.textOffsetDist) or \\\n qad_utils.doubleSmaller(spaceForBlock2, self.getBlock2Size() + self.textOffsetDist):\n if self.blockSuppressionForNoSpace: # sopprime i simboli se non c'é spazio sufficiente all'interno delle linee di estensione\n block1Rot = None\n block2Rot = None\n \n # considero il testo senza frecce\n if self.textRotMode == QadDimStyleTxtRotModeEnum.ISO:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, QadDimStyleTxtRotModeEnum.ALIGNED_LINE)\n else:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, self.textRotMode)\n \n rect = self.textRectToQadLinearObjectList(textInsPt, textWidth, textHeight, textRot)\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(rect, dimLinePt1, dimLinePt2)\n # se non c'é spazio neanche per il testo senza le frecce\n if spaceForBlock1 == 0 or spaceForBlock2 == 0 or \\\n spaceForBlock1 < self.textOffsetDist or spaceForBlock2 < self.textOffsetDist: \n # sposta testo fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE\n else:\n textLinearDimComponentOn = QadDimComponentEnum.DIM_LINE1 \n else: # non devo sopprimere i simboli\n # la prima cosa da spostare all'esterno é :\n if self.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.BOTH_OUTSIDE_EXT_LINES:\n # sposta testo e frecce fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE \n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False) # frecce esterne \n # sposta prima le frecce poi, se non basta, anche il testo\n elif self.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.FIRST_BLOCKS_THEN_TEXT:\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False) # frecce esterne \n # considero il testo senza frecce\n if self.textRotMode == QadDimStyleTxtRotModeEnum.ISO:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, QadDimStyleTxtRotModeEnum.ALIGNED_LINE)\n else:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, self.textRotMode)\n \n rect = self.textRectToQadLinearObjectList(textInsPt, textWidth, textHeight, textRot)\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(rect, dimLinePt1, dimLinePt2)\n # se non c'é spazio neanche per il testo senza le frecce\n if spaceForBlock1 == 0 or spaceForBlock2 == 0 or \\\n spaceForBlock1 < self.textOffsetDist or spaceForBlock2 < self.textOffsetDist: \n # sposta testo fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE\n else:\n textLinearDimComponentOn = QadDimComponentEnum.DIM_LINE1 \n # sposta prima il testo poi, se non basta, anche le frecce\n elif self.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.FIRST_TEXT_THEN_BLOCKS:\n # sposto il testo fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE \n # se non ci stanno neanche le frecce\n if qad_utils.getDistance(dimLinePt1, dimLinePt2) <= self.getBlock1Size() + self.getBlock2Size():\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False) # frecce esterne \n else:\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, True) # frecce interne\n # Sposta indistintamente il testo o le frecce (l'oggetto che si adatta meglio)\n elif self.textBlockAdjust == QadDimStyleTextBlocksAdjustEnum.WHICHEVER_FITS_BEST:\n # sposto il più ingombrante\n if self.getBlock1Size() + self.getBlock2Size() > textWidth: # le frecce sono più ingombranti del testo\n textLinearDimComponentOn = QadDimComponentEnum.DIM_LINE1\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False) # frecce esterne\n \n # considero il testo senza frecce\n if self.textRotMode == QadDimStyleTxtRotModeEnum.ISO: \n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, QadDimStyleTxtRotModeEnum.ALIGNED_LINE)\n else:\n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, dimLinePt2, textWidth, textHeight, \\\n self.textHorizontalPos, textVerticalPos, self.textRotMode)\n \n rect = self.textRectToQadLinearObjectList(textInsPt, textWidth, textHeight, textRot)\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(rect, dimLinePt1, dimLinePt2)\n # se non c'é spazio neanche per il testo senza le frecce\n if spaceForBlock1 == 0 or spaceForBlock2 == 0 or \\\n spaceForBlock1 < self.textOffsetDist or spaceForBlock2 < self.textOffsetDist: \n # sposta testo fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE\n else:\n textLinearDimComponentOn = QadDimComponentEnum.DIM_LINE1 \n else: # il testo é più ingombrante dei simboli\n # sposto il testo fuori dalle linee di estensione\n textInsPt, textRot, txtLeaderLines = self.getTextPosAndLinesOutOfDimLines(dimLinePt1, dimLinePt2, textWidth, textHeight)\n textLinearDimComponentOn = QadDimComponentEnum.LEADER_LINE \n # se non ci stanno neanche le frecce\n if qad_utils.getDistance(dimLinePt1, dimLinePt2) <= self.getBlock1Size() + self.getBlock2Size():\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False) # frecce esterne \n else:\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, True) # frecce interne\n else: # se lo spazio é sufficiente per inserire testo e simboli all'interno delle linee di estensione,\n textLinearDimComponentOn = QadDimComponentEnum.DIM_LINE1\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, True) # frecce interne\n \n # il testo é sopra e allineato alla prima linea di estensione \n elif self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE_UP:\n # angolo della linea che va dal punto di quota all'inizio della linea di quota\n rotLine = qad_utils.getAngleBy2Pts(dimPt1, dimLinePt1)\n pt = qad_utils.getPolarPointByPtAngle(dimLinePt1, rotLine, self.textOffsetDist + textWidth)\n if self.textVerticalPos == QadDimStyleTxtVerticalPosEnum.EXTERN_LINE:\n textVerticalPos = QadDimStyleTxtVerticalPosEnum.ABOVE_LINE\n else:\n textVerticalPos = self.textVerticalPos\n \n if self.textRotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION:\n textRotMode = QadDimStyleTxtRotModeEnum.FORCED_ROTATION\n else:\n textRotMode = QadDimStyleTxtRotModeEnum.ALIGNED_LINE\n \n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt1, pt, textWidth, textHeight, \\\n QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE, \\\n textVerticalPos, textRotMode)\n textLinearDimComponentOn = QadDimComponentEnum.EXT_LINE1 \n \n # calcolo lo spazio dei blocchi in assenza del testo\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(None, dimLinePt1, dimLinePt2)\n # se non c'é spazio per i blocchi\n if spaceForBlock1 < self.getBlock1Size() or spaceForBlock2 < self.getBlock2Size():\n if self.blockSuppressionForNoSpace: # i blocchi sono soppressi\n block1Rot = None\n block2Rot = None\n else: # sposto le frecce all'esterno\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False)\n else: # c'é spazio per i blocchi\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, True) # frecce interne\n \n # il testo é sopra e allineato alla seconda linea di estensione \n elif self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.SECOND_EXT_LINE_UP:\n # angolo della linea che va dal punto di quota all'inizio della linea di quota\n rotLine = qad_utils.getAngleBy2Pts(dimPt2, dimLinePt2)\n pt = qad_utils.getPolarPointByPtAngle(dimLinePt2, rotLine, self.textOffsetDist + textWidth)\n if self.textVerticalPos == QadDimStyleTxtVerticalPosEnum.EXTERN_LINE:\n textVerticalPos = QadDimStyleTxtVerticalPosEnum.ABOVE_LINE\n else:\n textVerticalPos = self.textVerticalPos\n \n if self.textRotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION:\n textRotMode = QadDimStyleTxtRotModeEnum.FORCED_ROTATION\n else:\n textRotMode = QadDimStyleTxtRotModeEnum.ALIGNED_LINE\n \n textInsPt, textRot = self.getTextPositionOnLine(dimLinePt2, pt, textWidth, textHeight, \\\n QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE, \\\n textVerticalPos, textRotMode)\n textLinearDimComponentOn = QadDimComponentEnum.EXT_LINE2 \n \n # calcolo lo spazio dei blocchi in assenza del testo\n spaceForBlock1, spaceForBlock2 = self.getSpaceForBlock1AndBlock2(None, dimLinePt1, dimLinePt2)\n # se non c'é spazio per i blocchi\n if spaceForBlock1 < self.getBlock1Size() or spaceForBlock2 < self.getBlock2Size():\n if self.blockSuppressionForNoSpace: # i blocchi sono soppressi\n block1Rot = None\n block2Rot = None\n else: # sposto le frecce all'esterno\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, False)\n else: # c'é spazio per i blocchi\n block1Rot, block2Rot = self.getBlocksRot(dimLinePt1, dimLinePt2, True) # frecce interne\n \n if self.textDirection == QadDimStyleTxtDirectionEnum.DX_TO_SX:\n # il punto di inserimento diventa l'angolo in alto a destra del rettangolo\n textInsPt = qad_utils.getPolarPointByPtAngle(textInsPt, textRot, textWidth)\n textInsPt = qad_utils.getPolarPointByPtAngle(textInsPt, textRot + math.pi / 2, textHeight)\n # la rotazione viene capovolta\n textRot = qad_utils.normalizeAngle(textRot + math.pi)\n \n return [[textInsPt, textRot], [textLinearDimComponentOn, txtLeaderLines], block1Rot, block2Rot]\n \n \n #============================================================================\n # getTextFeature\n #============================================================================\n def getTextFeature(self, measure, pt = None, rot = None, sourceCrs = None):\n \"\"\"\n Restituisce la feature per il testo della quota.\n La rotazione é espressa in radianti.\n sourceCrs = sistema di coordinate di pt\n \"\"\"\n _pt = QgsPoint(0,0) if pt is None else pt\n _rot = 0 if rot is None else rot\n \n textualFeaturePrototype = self.getTextualFeaturePrototype()\n if textualFeaturePrototype is None:\n return None\n f = QgsFeature(textualFeaturePrototype)\n g = QgsGeometry.fromPoint(_pt)\n \n if (sourceCrs is not None) and sourceCrs != self.getTextualLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getTextualLayer().crs()) # trasformo la geometria\n g.transform(coordTransform) \n \n f.setGeometry(g)\n\n # se il testo dipende da un solo campo \n labelFieldNames = qad_label.get_labelFieldNames(self.getTextualLayer())\n if len(labelFieldNames) == 1 and len(labelFieldNames[0]) > 0:\n f.setAttribute(labelFieldNames[0], self.getFormattedText(measure))\n\n # se l'altezza testo dipende da un solo campo \n sizeFldNames = qad_label.get_labelSizeFieldNames(self.getTextualLayer())\n if len(sizeFldNames) == 1 and len(sizeFldNames[0]) > 0:\n f.setAttribute(sizeFldNames[0], self.textHeight) # altezza testo\n \n # se la rotazione dipende da un solo campo\n rotFldNames = qad_label.get_labelRotationFieldNames(self.getTextualLayer())\n if len(rotFldNames) == 1 and len(rotFldNames[0]) > 0:\n f.setAttribute(rotFldNames[0], qad_utils.toDegrees(_rot)) # Converte da radianti a gradi\n \n # se il font dipende da un solo campo\n fontFamilyFldNames = qad_label.get_labelFontFamilyFieldNames(self.getTextualLayer())\n if len(fontFamilyFldNames) == 1 and len(fontFamilyFldNames[0]) > 0:\n f.setAttribute(fontFamilyFldNames[0], self.textFont) # nome del font di testo \n \n # imposto il colore\n try:\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.textColor)\n except:\n pass\n \n # imposto lo stile di quotatura\n try:\n if len(self.dimStyleFieldName) > 0:\n f.setAttribute(self.dimStyleFieldName, self.name) \n if len(self.dimTypeFieldName) > 0:\n f.setAttribute(self.dimTypeFieldName, self.dimType) \n except:\n pass\n \n return f \n\n \n #============================================================================\n # FUNZIONI PER IL TESTO - FINE\n # FUNZIONI PER LA LINEA DI LEADER - INIZIO\n #============================================================================\n\n\n #============================================================================\n # getLeaderLines\n #============================================================================\n def getLeaderLines(self, dimLinePt1, dimLinePt2, textWidth, textHeight):\n \"\"\"\n Restituisce una lista di linee che formano il porta quota nel caso il testo venga spostato\n fuori dalle linee di estensione perché era troppo grosso.\n dimLinePt1 = primo punto della linea di quota (QgsPoint)\n dimLinePt2 = secondo punto della linea di quota (QgsPoint)\n textWidth = larghezza testo\n textHeight = altezza testo\n \"\"\"\n # le linee sono a lato della linea di estensione 1\n if self.textHorizontalPos == QadDimStyleTxtHorizontalPosEnum.FIRST_EXT_LINE:\n rotLine = qad_utils.getAngleBy2Pts(dimLinePt2, dimLinePt1) # angolo della linea porta quota\n pt1 = qad_utils.getPolarPointByPtAngle(dimLinePt1, rotLine, self.getBlock1Size())\n line1 = [dimLinePt1, pt1]\n # le linee sono a lato della linea di estensione 2\n else:\n rotLine = qad_utils.getAngleBy2Pts(dimLinePt1, dimLinePt2) # angolo della linea porta quota\n pt1 = qad_utils.getPolarPointByPtAngle(dimLinePt2, rotLine, self.getBlock1Size())\n line1 = [dimLinePt2, pt1]\n \n # modalità di rotazione del testo orizzontale o\n # testo allineato con la linea di quota se tra le linee di estensione, altrimenti testo orizzontale\n if self.textRotMode == QadDimStyleTxtRotModeEnum.HORIZONTAL or \\\n self.textRotMode == QadDimStyleTxtRotModeEnum.ISO:\n if qad_utils.doubleNear(rotLine, math.pi / 2): # verticale dal basso verso l'alto\n pt2 = qad_utils.getPolarPointByPtAngle(pt1, 0, self.textOffsetDist + textWidth)\n elif qad_utils.doubleNear(rotLine, math.pi * 3 / 2): # verticale dall'alto verso il basso \n pt2 = qad_utils.getPolarPointByPtAngle(pt1, math.pi, self.textOffsetDist + textWidth)\n elif (rotLine > math.pi * 3 / 2 and rotLine <= math.pi * 2) or \\\n (rotLine >= 0 and rotLine < math.pi / 2): # da sx a dx\n pt2 = qad_utils.getPolarPointByPtAngle(pt1, 0, self.textOffsetDist + textWidth)\n else: # da dx a sx\n pt2 = qad_utils.getPolarPointByPtAngle(pt1, math.pi, self.textOffsetDist + textWidth)\n elif self.textRotMode == QadDimStyleTxtRotModeEnum.ALIGNED_LINE: # testo allineato con la linea di quota\n pt2 = qad_utils.getPolarPointByPtAngle(pt1, rotLine, self.textOffsetDist + textWidth)\n elif self.textRotMode == QadDimStyleTxtRotModeEnum.FORCED_ROTATION: # testo con rotazione forzata\n pt2 = qad_utils.getPolarPointByPtAngle(pt1, self.textForcedRot, self.textOffsetDist + textWidth)\n\n line2 = [pt1, pt2]\n return [line1, line2] \n\n\n #============================================================================\n # getExtLineFeature\n #============================================================================\n def getLeaderFeature(self, leaderLines, sourceCrs = None):\n \"\"\"\n Restituisce la feature per la linea di estensione.\n leaderLines = lista di linee di leader [line1, line2 ...]\n sourceCrs = sistema di coordinate di leaderLines\n \"\"\"\n if leaderLines is None:\n return None\n\n linearFeaturePrototype = self.getLinearFeaturePrototype()\n if linearFeaturePrototype is None:\n return None\n f = QgsFeature(linearFeaturePrototype)\n \n pts = []\n first = True\n for line in leaderLines:\n if first:\n pts.append(line[0])\n first = False\n pts.append(line[1])\n \n g = QgsGeometry.fromPolyline(pts)\n \n if (sourceCrs is not None) and sourceCrs != self.getLinearLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getLinearLayer().crs()) # trasformo la geometria\n g.transform(coordTransform) \n \n f.setGeometry(g)\n \n try:\n # imposto il tipo di componente della quotatura\n if len(self.componentFieldName) > 0:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.LEADER_LINE)\n except:\n pass\n\n try:\n # imposto il tipo di linea\n if len(self.lineTypeFieldName) > 0:\n f.setAttribute(self.lineTypeFieldName, self.dimLineLineType) \n except:\n pass\n\n try:\n # imposto il colore\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.dimLineColor) \n except:\n pass\n\n return f\n \n\n #============================================================================\n # FUNZIONI PER LA LINEA DI LEADER - FINE\n # FUNZIONI PER LE LINEE DI ESTENSIONE - INIZIO\n #============================================================================\n\n\n #============================================================================\n # getExtLine\n #============================================================================\n def getExtLine(self, dimPt, dimLinePt):\n \"\"\"\n dimPt = punto da quotare\n dimLinePt = corrispondente punto della linea di quotatura\n \n ritorna una linea di estensione modificata secondo lo stile di quotatura\n il primo punto é vicino alla linea di quota, il secondo al punto da quotare\n \"\"\"\n\n angle = qad_utils.getAngleBy2Pts(dimPt, dimLinePt)\n # distanza della linea di estensione oltre la linea di quota\n pt1 = qad_utils.getPolarPointByPtAngle(dimLinePt, angle, self.extLineOffsetDimLine)\n # distanza della linea di estensione dai punti da quotare\n pt2 = qad_utils.getPolarPointByPtAngle(dimPt, angle, self.extLineOffsetOrigPoints) \n\n if self.extLineIsFixedLen == True: # attivata lunghezza fissa delle line di estensione \n if qad_utils.getDistance(pt1, pt2) > self.extLineFixedLen:\n # lunghezza fissa delle line di estensione (DIMFXL) dalla linea di quota \n # al punto da quotare spostato di extLineOffsetOrigPoints\n # (la linea di estensione non va oltre il punto da quotare)\n d = qad_utils.getDistance(dimLinePt, dimPt)\n if d > self.extLineFixedLen:\n d = self.extLineFixedLen\n pt2 = qad_utils.getPolarPointByPtAngle(dimLinePt, angle + math.pi, d) \n\n return [pt1, pt2]\n\n\n #============================================================================\n # getExtLineFeature\n #============================================================================\n def getExtLineFeature(self, extLine, isExtLine1, sourceCrs = None):\n \"\"\"\n Restituisce la feature per la linea di estensione.\n extLine = linea di estensione [pt1, pt2]\n isExtLine1 = se True si tratta della linea di estensione 1 altrimenti della linea di estensione 2\n sourceCrs = sistema di coordinate di extLine\n \"\"\"\n if (isExtLine1 == True and self.extLine1Show == False) or \\\n (isExtLine1 == False and self.extLine2Show == False):\n return None\n \n f = QgsFeature(self.getLinearFeaturePrototype())\n g = QgsGeometry.fromPolyline(extLine)\n \n if (sourceCrs is not None) and sourceCrs != self.getLinearLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getLinearLayer().crs()) # trasformo la geometria\n g.transform(coordTransform)\n \n f.setGeometry(g)\n \n try:\n # imposto il tipo di componente della quotatura\n if len(self.componentFieldName) > 0:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.EXT_LINE1 if isExtLine1 else QadDimComponentEnum.EXT_LINE2)\n except:\n pass\n\n try:\n # imposto il tipo di linea\n if len(self.lineTypeFieldName) > 0:\n f.setAttribute(self.lineTypeFieldName, self.extLine1LineType if isExtLine1 else self.extLine2LineType) \n except:\n pass\n\n try:\n # imposto il colore\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.extLineColor) \n except:\n pass\n\n return f\n\n \n #============================================================================\n # FUNZIONI PER LE LINEE DI ESTENSIONE - FINE\n # FUNZIONI PER LA LINEA DI QUOTA - INIZIO\n #============================================================================\n \n\n #============================================================================\n # getDimLine\n #============================================================================\n def getDimLine(self, dimPt1, dimPt2, linePosPt, preferredAlignment = QadDimStyleAlignmentEnum.HORIZONTAL,\n dimLineRotation = 0.0):\n \"\"\"\n Restituisce la linea di quotatura:\n\n dimPt1 = primo punto da quotare\n dimPt2 = secondo punto da quotare\n linePosPt = punto per indicare dove deve essere posizionata la linea di quota\n preferredAlignment = indica se ci si deve allineare ai punti di quota in modo orizzontale o verticale\n (se i punti di quota formano una linea obliqua). Usato solo per le quotature lineari \n dimLineRotation = angolo della linea di quotatura (default = 0). Usato solo per le quotature lineari \n \"\"\" \n if self.dimType == QadDimTypeEnum.ALIGNED:\n # calcolo la proiezione perpendicolare del punto <linePosPt> sulla linea che congiunge <dimPt1> a <dimPt2>\n ptPerp = qad_utils.getPerpendicularPointOnInfinityLine(dimPt1, dimPt2, linePosPt)\n d = qad_utils.getDistance(linePosPt, ptPerp)\n \n angle = qad_utils.getAngleBy2Pts(dimPt1, dimPt2)\n if qad_utils.leftOfLine(linePosPt, dimPt1, dimPt2) < 0: # a sinistra della linea che congiunge <dimPt1> a <dimPt2>\n angle = angle + (math.pi / 2)\n else:\n angle = angle - (math.pi / 2)\n \n return [qad_utils.getPolarPointByPtAngle(dimPt1, angle, d), \\\n qad_utils.getPolarPointByPtAngle(dimPt2, angle, d)]\n elif self.dimType == QadDimTypeEnum.LINEAR:\n if preferredAlignment == QadDimStyleAlignmentEnum.HORIZONTAL:\n ptDummy = qad_utils.getPolarPointByPtAngle(dimPt1, dimLineRotation + math.pi / 2, 1)\n pt1 = qad_utils.getPerpendicularPointOnInfinityLine(dimPt1, ptDummy, linePosPt)\n ptDummy = qad_utils.getPolarPointByPtAngle(dimPt2, dimLineRotation + math.pi / 2, 1)\n pt2 = qad_utils.getPerpendicularPointOnInfinityLine(dimPt2, ptDummy, linePosPt)\n \n return [pt1, pt2]\n elif preferredAlignment == QadDimStyleAlignmentEnum.VERTICAL:\n ptDummy = qad_utils.getPolarPointByPtAngle(dimPt1, dimLineRotation, 1)\n pt1 = qad_utils.getPerpendicularPointOnInfinityLine(dimPt1, ptDummy, linePosPt)\n ptDummy = qad_utils.getPolarPointByPtAngle(dimPt2, dimLineRotation, 1)\n pt2 = qad_utils.getPerpendicularPointOnInfinityLine(dimPt2, ptDummy, linePosPt)\n \n return [pt1, pt2]\n\n\n #============================================================================\n # getDimLineFeature\n #============================================================================\n def getDimLineFeature(self, dimLine, isDimLine1, textLinearDimComponentOn, sourceCrs = None):\n \"\"\"\n Restituisce la feature per la linea di quota.\n dimLine = linea di quota [pt1, pt2]\n isDimLine1 = se True si tratta della linea di quota 1 altrimenti della linea di quota 2\n textLinearDimComponentOn = indica il componente della quota dove é situato il testo di quota (QadDimComponentEnum)\n sourceCrs = sistema di coordinate di dimLine\n \"\"\"\n \n # se non c'é la linea di quota\n if dimLine is None:\n return None\n if isDimLine1 == True: # se si tratta della linea di quota 1\n # se la linea di quota 1 deve essere invisibile (vale solo se il testo é sulla linea di quota)\n if self.dimLine1Show == False and \\\n (textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1 or textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE2):\n return None\n else: # se si tratta della linea di quota 2\n # se la linea di quota 2 deve essere invisibile (vale solo se il testo é sulla linea di quota)\n if self.dimLine2Show == False and \\\n (textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1 or textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE2):\n return None\n \n f = QgsFeature(self.getLinearFeaturePrototype())\n g = QgsGeometry.fromPolyline(dimLine)\n \n if (sourceCrs is not None) and sourceCrs != self.getLinearLayer().crs():\n coordTransform = QgsCoordinateTransform(sourceCrs, self.getLinearLayer().crs()) # trasformo la geometria\n g.transform(coordTransform) \n \n f.setGeometry(g)\n \n try:\n # imposto il tipo di componente della quotatura\n if len(self.componentFieldName) > 0:\n f.setAttribute(self.componentFieldName, QadDimComponentEnum.DIM_LINE1 if isDimLine1 else QadDimComponentEnum.DIM_LINE2)\n except:\n pass\n\n try:\n # imposto il tipo di linea\n if len(self.lineTypeFieldName) > 0:\n f.setAttribute(self.lineTypeFieldName, self.dimLineLineType) \n except:\n pass\n\n try:\n # imposto il colore\n if len(self.colorFieldName) > 0:\n f.setAttribute(self.colorFieldName, self.dimLineColor) \n except:\n pass\n\n return f\n \n\n #============================================================================\n # FUNZIONI PER LA LINEA DI QUOTA - FINE\n # FUNZIONI PER LA QUOTATURA LINEARE - INIZIO\n #============================================================================\n \n\n #============================================================================\n # getLinearDimFeatures\n #============================================================================\n def getLinearDimFeatures(self, canvas, dimPt1, dimPt2, linePosPt, measure = None, \\\n preferredAlignment = QadDimStyleAlignmentEnum.HORIZONTAL, \\\n dimLineRotation = 0.0):\n \"\"\"\n dimPt1 = primo punto da quotare (in unita di mappa)\n dimPt2 = secondo punto da quotare (in unita di mappa)\n linePosPt = punto per indicare dove deve essere posizionata la linea di quota (in unita di mappa)\n measure = indica se la misura é predeterminata oppure (se = None) deve essere calcolata\n preferredAlignment = se lo stile di quota é lineare, indica se ci si deve allienare ai punti di quota\n in modo orizzontale o verticale (se i punti di quota formano una linea obliqua) \n dimLineRotation = angolo della linea di quotatura (default = 0) \n \n # quota lineare con una linea di quota orizzontale o verticale\n # ritorna una lista di elementi che descrivono la geometria della quota:\n # 1 lista = feature del primo e del secondo punto di quota; QgsFeature 1, QgsFeature 2\n # 2 lista = feature della prima e della seconda linea di quota (quest'ultima può essere None); QgsFeature 1, QgsFeature 2\n # 3 lista = feature del punto del testo di quota e geometria del rettangolo di occupazione; QgsFeature, QgsGeometry\n # 4 lista = feature del primo e del secondo simbolo per la linea di quota (possono essere None); QgsFeature 1, QgsFeature 2\n # 5 lista = feature della prima e della seconda linea di estensione (possono essere None); QgsFeature 1, QgsFeature 2\n # 6 elemento = feature della linea di leader (può essere None); QgsFeature\n \"\"\"\n self.dimType = QadDimTypeEnum.LINEAR\n \n # punti di quotatura\n dimPt1Feature = self.getDimPointFeature(dimPt1, True, \\\n canvas.mapRenderer().destinationCrs()) # True = primo punto di quotatura\n dimPt2Feature = self.getDimPointFeature(dimPt2, False, \\\n canvas.mapRenderer().destinationCrs()) # False = secondo punto di quotatura \n \n # linea di quota\n dimLine1 = self.getDimLine(dimPt1, dimPt2, linePosPt, preferredAlignment, dimLineRotation)\n dimLine2 = None\n \n # testo e blocchi\n if measure is None:\n textValue = qad_utils.getDistance(dimLine1[0], dimLine1[1])\n else:\n textValue = unicode(measure)\n \n textFeature = self.getTextFeature(textValue) \n textWidth, textHeight = qad_label.calculateLabelSize(self.getTextualLayer(), textFeature, canvas)\n \n # creo un rettangolo intorno al testo con un buffer = self.textOffsetDist\n textWidthOffset = textWidth + self.textOffsetDist * 2\n textHeightOffset = textHeight + self.textOffsetDist * 2\n\n # Restituisce una lista di 4 elementi:\n # - il primo elemento é una lista con il punto di inserimento del testo della quota e la sua rotazione\n # - il secondo elemento é una lista con flag che indica il tipo della linea sulla quale é stato messo il testo; vedi QadDimComponentEnum\n # e una lista di linee \"leader\" nel caso il testo sia all'esterno della quota\n # - il terzo elemento é la rotazione del primo blocco delle frecce; può essere None se non visibile\n # - il quarto elemento é la rotazione del secondo blocco delle frecce; può essere None se non visibile \n dummy1, dummy2, block1Rot, block2Rot = self.getLinearTextAndBlocksPosition(dimPt1, dimPt2, \\\n dimLine1[0], dimLine1[1], \\\n textWidthOffset, textHeightOffset)\n \n textOffsetRectInsPt = dummy1[0]\n textRot = dummy1[1]\n textLinearDimComponentOn = dummy2[0]\n txtLeaderLines = dummy2[1]\n\n # trovo il vero punto di inserimento del testo tenendo conto del buffer intorno \n textInsPt = qad_utils.getPolarPointByPtAngle(textOffsetRectInsPt, textRot, self.textOffsetDist)\n textInsPt = qad_utils.getPolarPointByPtAngle(textInsPt, textRot + math.pi / 2, self.textOffsetDist)\n \n # testo\n textGeom = QgsGeometry.fromPoint(textInsPt)\n textFeature = self.getTextFeature(textValue, textInsPt, textRot, canvas.mapRenderer().destinationCrs()) \n \n # blocchi frecce\n block1Feature = self.getSymbolFeature(dimLine1[0], block1Rot, True, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # True = primo punto di quotatura\n block2Feature = self.getSymbolFeature(dimLine1[1], block2Rot, False, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # False = secondo punto di quotatura \n \n extLine1 = self.getExtLine(dimPt1, dimLine1[0])\n extLine2 = self.getExtLine(dimPt2, dimLine1[1])\n \n # creo un rettangolo intorno al testo con un offset\n textOffsetRect = self.textRectToQadLinearObjectList(textOffsetRectInsPt, textWidthOffset, textHeightOffset, textRot)\n \n if textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1: # linea di quota (\"Dimension line\")\n dimLine1, dimLine2 = self.adjustLineAccordingTextRect(textOffsetRect, dimLine1[0], dimLine1[1], QadDimComponentEnum.DIM_LINE1)\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE1: # prima linea di estensione (\"Extension line 1\")\n if extLine1 is not None:\n extLineRot = qad_utils.getAngleBy2Pts(dimPt1, dimLine1[0])\n extLine1 = self.getExtLine(dimPt1, qad_utils.getPolarPointByPtAngle(dimLine1[0], extLineRot, textWidth + self.textOffsetDist))\n # passo prima il secondo punto e poi il primo perché getExtLine restituisce una linea dalla linea di quota verso il punto di quotatura \n extLine1, dummy = self.adjustLineAccordingTextRect(textOffsetRect, extLine1[1], extLine1[0], QadDimComponentEnum.EXT_LINE1)\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE2: # seconda linea di estensione (\"Extension line 2\")\n if extLine2 is not None:\n extLineRot = qad_utils.getAngleBy2Pts(dimPt2, dimLine1[1])\n extLine2 = self.getExtLine(dimPt2, qad_utils.getPolarPointByPtAngle(dimLine1[1], extLineRot, textWidth + self.textOffsetDist)) \n # passo prima il secondo punto e poi il primo perché getExtLine restituisce una linea dalla linea di quota verso il punto di quotatura \n extLine2, dummy = self.adjustLineAccordingTextRect(textOffsetRect, extLine2[1], extLine2[0], QadDimComponentEnum.EXT_LINE2)\n elif textLinearDimComponentOn == QadDimComponentEnum.LEADER_LINE: # linea porta quota usata quando il testo é fuori dalla quota (\"Leader\")\n lastLine = txtLeaderLines[-1]\n lastLine, dummy = self.adjustLineAccordingTextRect(textOffsetRect, lastLine[0], lastLine[1], QadDimComponentEnum.LEADER_LINE)\n del txtLeaderLines[-1] # sostituisco l'ultimo elemento\n txtLeaderLines.append(lastLine)\n \n # linee di quota\n dimLine1Feature = self.getDimLineFeature(dimLine1, True, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # True = prima linea di quota\n dimLine2Feature = self.getDimLineFeature(dimLine2, False, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # False = seconda linea di quota\n \n # linee di estensione\n extLine1Feature = self.getExtLineFeature(extLine1, True, canvas.mapRenderer().destinationCrs()) # True = prima linea di estensione\n extLine2Feature = self.getExtLineFeature(extLine2, False, canvas.mapRenderer().destinationCrs()) # False = seconda linea di estensione\n \n # linea di leader\n txtLeaderLineFeature = self.getLeaderFeature(txtLeaderLines, canvas.mapRenderer().destinationCrs())\n\n dimEntity = QadDimEntity()\n dimEntity.dimStyle = self\n # features testuali\n dimEntity.textualFeature = textFeature\n # features lineari\n if dimLine1Feature is not None:\n dimEntity.linearFeatures.append(dimLine1Feature)\n if dimLine2Feature is not None:\n dimEntity.linearFeatures.append(dimLine2Feature)\n if extLine1Feature is not None:\n dimEntity.linearFeatures.append(extLine1Feature)\n if extLine2Feature is not None:\n dimEntity.linearFeatures.append(extLine2Feature)\n if txtLeaderLineFeature is not None:\n dimEntity.linearFeatures.append(txtLeaderLineFeature)\n # features puntuali\n dimEntity.symbolFeatures.extend([dimPt1Feature, dimPt2Feature])\n if block1Feature is not None:\n dimEntity.symbolFeatures.append(block1Feature)\n if block2Feature is not None:\n dimEntity.symbolFeatures.append(block2Feature)\n \n return dimEntity, QgsGeometry.fromPolygon([textOffsetRect.asPolyline()])\n\n\n #============================================================================\n # addLinearDimToLayers\n #============================================================================\n def addLinearDimToLayers(self, plugIn, dimPt1, dimPt2, linePosPt, measure = None, \\\n preferredAlignment = QadDimStyleAlignmentEnum.HORIZONTAL, \\\n dimLineRotation = 0.0):\n \"\"\"\n Aggiunge ai layers le features che compongono una quota lineare.\n \"\"\"\n self.dimType = QadDimTypeEnum.LINEAR\n \n dimEntity, textOffsetRect = self.getLinearDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure, \\\n preferredAlignment, \\\n dimLineRotation)\n \n plugIn.beginEditCommand(\"Linear dimension added\", [self.getSymbolLayer(), self.getLinearLayer(), self.getTextualLayer()])\n \n # prima di tutto inserisco il testo di quota\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(plugIn, self.getTextualLayer(), dimEntity.textualFeature, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n dimId = dimEntity.textualFeature.id()\n if self.setDimId(dimId, [dimEntity.textualFeature], False) == True: # setto id\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(plugIn, self.getTextualLayer(), dimEntity.textualFeature, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n \n # features puntuali\n self.setDimId(dimId, dimEntity.symbolFeatures, True) # setto id_parent\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getSymbolLayer(), dimEntity.symbolFeatures, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n \n # features lineari\n self.setDimId(dimId, dimEntity.linearFeatures, True) # setto id_parent\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getLinearLayer(), dimEntity.linearFeatures, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n\n plugIn.endEditCommand()\n \n return True\n\n\n #============================================================================\n # FUNZIONI PER LA QUOTATURA LINEARE - FINE\n # FUNZIONI PER LA QUOTATURA ALLINEATA - INIZIO\n #============================================================================\n \n\n #============================================================================\n # getAlignedDimFeatures\n #============================================================================\n def getAlignedDimFeatures(self, canvas, dimPt1, dimPt2, linePosPt, measure = None):\n \"\"\"\n dimPt1 = primo punto da quotare (in unita di mappa)\n dimPt2 = secondo punto da quotare (in unita di mappa)\n linePosPt = punto per indicare dove deve essere posizionata la linea di quota (in unita di mappa)\n measure = indica se la misura é predeterminata oppure (se = None) deve essere calcolata\n \n # quota lineare con una linea di quota orizzontale o verticale\n # ritorna una lista di elementi che descrivono la geometria della quota:\n # 1 lista = feature del primo e del secondo punto di quota; QgsFeature 1, QgsFeature 2\n # 2 lista = feature della prima e della seconda linea di quota (quest'ultima può essere None); QgsFeature 1, QgsFeature 2\n # 3 lista = feature del punto del testo di quota e geometria del rettangolo di occupazione; QgsFeature, QgsGeometry\n # 4 lista = feature del primo e del secondo simbolo per la linea di quota (possono essere None); QgsFeature 1, QgsFeature 2\n # 5 lista = feature della prima e della seconda linea di estensione (possono essere None); QgsFeature 1, QgsFeature 2\n # 6 elemento = feature della linea di leader (può essere None); QgsFeature\n \"\"\"\n self.dimType = QadDimTypeEnum.ALIGNED\n \n # punti di quotatura\n dimPt1Feature = self.getDimPointFeature(dimPt1, True, \\\n canvas.mapRenderer().destinationCrs()) # True = primo punto di quotatura\n dimPt2Feature = self.getDimPointFeature(dimPt2, False, \\\n canvas.mapRenderer().destinationCrs()) # False = secondo punto di quotatura \n \n # linea di quota\n dimLine1 = self.getDimLine(dimPt1, dimPt2, linePosPt)\n dimLine2 = None\n \n # testo e blocchi\n if measure is None:\n textValue = qad_utils.getDistance(dimLine1[0], dimLine1[1])\n else:\n textValue = unicode(measure)\n \n textFeature = self.getTextFeature(textValue) \n textWidth, textHeight = qad_label.calculateLabelSize(self.getTextualLayer(), textFeature, canvas)\n\n # creo un rettangolo intorno al testo con un buffer = self.textOffsetDist\n textWidthOffset = textWidth + self.textOffsetDist * 2\n textHeightOffset = textHeight + self.textOffsetDist * 2\n\n # Restituisce una lista di 4 elementi:\n # - il primo elemento é una lista con il punto di inserimento del testo della quota e la sua rotazione\n # - il secondo elemento é una lista con flag che indica il tipo della linea sulla quale é stato messo il testo; vedi QadDimComponentEnum\n # e una lista di linee \"leader\" nel caso il testo sia all'esterno della quota\n # - il terzo elemento é la rotazione del primo blocco delle frecce; può essere None se non visibile\n # - il quarto elemento é la rotazione del secondo blocco delle frecce; può essere None se non visibile \n dummy1, dummy2, block1Rot, block2Rot = self.getLinearTextAndBlocksPosition(dimPt1, dimPt2, \\\n dimLine1[0], dimLine1[1], \\\n textWidthOffset, textHeightOffset)\n textOffsetRectInsPt = dummy1[0]\n textRot = dummy1[1]\n textLinearDimComponentOn = dummy2[0]\n txtLeaderLines = dummy2[1]\n\n # trovo il vero punto di inserimento del testo tenendo conto del buffer intorno \n textInsPt = qad_utils.getPolarPointByPtAngle(textOffsetRectInsPt, textRot, self.textOffsetDist)\n textInsPt = qad_utils.getPolarPointByPtAngle(textInsPt, textRot + math.pi / 2, self.textOffsetDist)\n\n # testo\n textGeom = QgsGeometry.fromPoint(textInsPt)\n textFeature = self.getTextFeature(textValue, textInsPt, textRot, canvas.mapRenderer().destinationCrs()) \n\n # blocchi frecce\n block1Feature = self.getSymbolFeature(dimLine1[0], block1Rot, True, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # True = primo punto di quotatura\n block2Feature = self.getSymbolFeature(dimLine1[1], block2Rot, False, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # False = secondo punto di quotatura \n \n extLine1 = self.getExtLine(dimPt1, dimLine1[0])\n extLine2 = self.getExtLine(dimPt2, dimLine1[1])\n \n # creo un rettangolo intorno al testo con un offset\n textOffsetRect = self.textRectToQadLinearObjectList(textOffsetRectInsPt, textWidthOffset, textHeightOffset, textRot)\n \n if textLinearDimComponentOn == QadDimComponentEnum.DIM_LINE1: # linea di quota (\"Dimension line\")\n dimLine1, dimLine2 = self.adjustLineAccordingTextRect(textOffsetRect, dimLine1[0], dimLine1[1], QadDimComponentEnum.DIM_LINE1)\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE1: # prima linea di estensione (\"Extension line 1\")\n if extLine1 is not None:\n extLineRot = qad_utils.getAngleBy2Pts(dimPt1, dimLine1[0])\n extLine1 = self.getExtLine(dimPt1, qad_utils.getPolarPointByPtAngle(dimLine1[0], extLineRot, textWidth + self.textOffsetDist))\n # passo prima il secondo punto e poi il primo perché getExtLine restituisce una linea dalla linea di quota verso il punto di quotatura \n extLine1, dummy = self.adjustLineAccordingTextRect(textOffsetRect, extLine1[1], extLine1[0], QadDimComponentEnum.EXT_LINE1)\n elif textLinearDimComponentOn == QadDimComponentEnum.EXT_LINE2: # seconda linea di estensione (\"Extension line 2\")\n if extLine2 is not None:\n extLineRot = qad_utils.getAngleBy2Pts(dimPt2, dimLine1[1])\n extLine2 = self.getExtLine(dimPt2, qad_utils.getPolarPointByPtAngle(dimLine1[1], extLineRot, textWidth + self.textOffsetDist)) \n # passo prima il secondo punto e poi il primo perché getExtLine restituisce una linea dalla linea di quota verso il punto di quotatura \n extLine2, dummy = self.adjustLineAccordingTextRect(textOffsetRect, extLine2[1], extLine2[0], QadDimComponentEnum.EXT_LINE2)\n elif textLinearDimComponentOn == QadDimComponentEnum.LEADER_LINE: # linea porta quota usata quando il testo é fuori dalla quota (\"Leader\")\n lastLine = txtLeaderLines[-1]\n lastLine, dummy = self.adjustLineAccordingTextRect(textOffsetRect, lastLine[0], lastLine[1], QadDimComponentEnum.LEADER_LINE)\n del txtLeaderLines[-1] # sostituisco l'ultimo elemento\n txtLeaderLines.append(lastLine)\n \n # linee di quota\n dimLine1Feature = self.getDimLineFeature(dimLine1, True, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # True = prima linea di quota\n dimLine2Feature = self.getDimLineFeature(dimLine2, False, textLinearDimComponentOn, canvas.mapRenderer().destinationCrs()) # False = seconda linea di quota\n\n # linee di estensione\n extLine1Feature = self.getExtLineFeature(extLine1, True, canvas.mapRenderer().destinationCrs()) # True = prima linea di estensione\n extLine2Feature = self.getExtLineFeature(extLine2, False, canvas.mapRenderer().destinationCrs()) # False = seconda linea di estensione\n\n # linea di leader\n txtLeaderLineFeature = self.getLeaderFeature(txtLeaderLines, canvas.mapRenderer().destinationCrs())\n \n dimEntity = QadDimEntity()\n dimEntity.dimStyle = self\n # features testuali\n dimEntity.textualFeature = textFeature\n # features lineari\n if dimLine1Feature is not None:\n dimEntity.linearFeatures.append(dimLine1Feature)\n if dimLine2Feature is not None:\n dimEntity.linearFeatures.append(dimLine2Feature)\n if extLine1Feature is not None:\n dimEntity.linearFeatures.append(extLine1Feature)\n if extLine2Feature is not None:\n dimEntity.linearFeatures.append(extLine2Feature)\n if txtLeaderLineFeature is not None:\n dimEntity.linearFeatures.append(txtLeaderLineFeature)\n # features puntuali\n dimEntity.symbolFeatures.extend([dimPt1Feature, dimPt2Feature])\n if block1Feature is not None:\n dimEntity.symbolFeatures.append(block1Feature)\n if block2Feature is not None:\n dimEntity.symbolFeatures.append(block2Feature)\n \n return dimEntity, QgsGeometry.fromPolygon([textOffsetRect.asPolyline()])\n\n\n #============================================================================\n # addAlignedDimToLayers\n #============================================================================\n def addAlignedDimToLayers(self, plugIn, dimPt1, dimPt2, linePosPt, measure = None, \\\n preferredAlignment = QadDimStyleAlignmentEnum.HORIZONTAL, \\\n dimLineRotation = 0.0):\n \"\"\"\n dimPt1 = primo punto da quotare (in unita di mappa)\n dimPt2 = secondo punto da quotare (in unita di mappa)\n linePosPt = punto per indicare dove deve essere posizionata la linea di quota (in unita di mappa)\n measure = indica se la misura é predeterminata oppure (se = None) deve essere calcolata\n preferredAlignment = se lo stile di quota é lineare, indica se ci si deve allienare ai punti di quota\n in modo orizzontale o verticale (se i punti di quota formano una linea obliqua) \n dimLineRotation = angolo della linea di quotatura (default = 0) \n\n Aggiunge ai layers le features che compongono una quota allineata.\n \"\"\"\n self.dimType = QadDimTypeEnum.ALIGNED\n \n dimEntity, textOffsetRect = self.getAlignedDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure)\n \n plugIn.beginEditCommand(\"Aligned dimension added\", [self.getSymbolLayer(), self.getLinearLayer(), self.getTextualLayer()])\n\n # prima di tutto inserisco il testo di quota\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(plugIn, self.getTextualLayer(), dimEntity.textualFeature, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n dimId = dimEntity.textualFeature.id()\n if self.setDimId(dimId, [dimEntity.textualFeature], False) == True: # setto id\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(plugIn, self.getTextualLayer(), dimEntity.textualFeature, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n \n # features puntuali\n self.setDimId(dimId, dimEntity.symbolFeatures, True) # setto id_parent\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getSymbolLayer(), dimEntity.symbolFeatures, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n \n # features lineari\n self.setDimId(dimId, dimEntity.linearFeatures, True) # setto id_parent\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getLinearLayer(), dimEntity.linearFeatures, None, False, False) == False:\n plugIn.destroyEditCommand()\n return False\n\n plugIn.endEditCommand()\n \n return True\n\n\n#===============================================================================\n# QadDimStylesClass list of dimension styles\n#===============================================================================\nclass QadDimStylesClass():\n \n def __init__(self, dimStyleList = None):\n if dimStyleList is None:\n self.dimStyleList = []\n else:\n self.set(dimStyleList)\n\n\n def __del__(self):\n if dimStyleList is None:\n del self.dimStyleList[:]\n\n \n def isEmpty(self):\n return True if self.count() == 0 else False\n\n \n def count(self):\n return len(self.dimStyleList)\n \n\n def clear(self):\n del self.dimStyleList[:] \n\n\n def findDimStyle(self, dimStyleName):\n \"\"\"\n La funzione, dato un nome di stile di quotatura, lo cerca nella lista e,\n in caso di successo, restituisce lo stile di quotatura.\n \"\"\"\n for dimStyle in self.dimStyleList:\n if dimStyle.name == dimStyleName:\n return dimStyle\n return None\n\n\n def addDimStyle(self, dimStyle, toFile = False, filePath = \"\"):\n d = self.findDimStyle(dimStyle)\n if d is None: \n self.dimStyleList.append(QadDimStyle(dimStyle))\n if toFile:\n if dimStyle.save(filePath, False) == False: # senza sovrascrivere file\n return False\n return True\n \n return False \n \n\n #============================================================================\n # removeDimStyle\n #============================================================================\n def removeDimStyle(self, dimStyleName, toFile = False):\n i = 0\n for dimStyle in self.dimStyleList:\n if dimStyle.name == dimStyleName:\n del self.dimStyleList[i]\n if toFile:\n dimStyle.remove()\n return True\n else:\n i = i + 1\n \n return False\n \n \n #============================================================================\n # renameDimStyle\n #============================================================================\n def renameDimStyle(self, dimStyleName, newDimStyleName):\n if dimStyleName == newDimStyleName: # nome uguale\n return True\n\n if self.findDimStyle(newDimStyleName) is not None:\n return False\n dimStyle = self.findDimStyle(dimStyleName)\n if dimStyle is None:\n return False\n return dimStyle.rename(newDimStyleName)\n\n \n #============================================================================\n # load\n #============================================================================\n def load(self, dir = None, append = False):\n \"\"\"\n Carica le impostazioni di tutti gli stili di quotatura presenti nella directory indicata.\n se dir = None se esiste un progetto caricato il percorso è quello del progetto altrimenti + il percorso locale di qad\n \"\"\"\n if dir is None:\n if append == False:\n self.clear()\n \n # se esiste un progetto caricato il percorso è quello del progetto\n prjFileInfo = QFileInfo(QgsProject.instance().fileName())\n path = prjFileInfo.absolutePath()\n if len(path) > 0:\n path += \"/;\"\n path += QgsApplication.qgisSettingsDirPath() + \"python/plugins/qad/\"\n \n # lista di directory separate da \";\"\n dirList = path.strip().split(\";\")\n for _dir in dirList:\n self.load(_dir, True) # in append\n else:\n _dir = QDir.cleanPath(dir)\n if _dir == \"\":\n return False\n \n if _dir.endswith(\"/\") == False:\n _dir = _dir + \"/\"\n \n if not os.path.exists(_dir):\n return False\n \n if append == False:\n self.clear()\n dimStyle = QadDimStyle()\n \n fileNames = os.listdir(_dir)\n for fileName in fileNames:\n if fileName.endswith(\".dim\"):\n path = _dir + fileName \n if dimStyle.load(path) == True:\n if self.findDimStyle(dimStyle.name) is None: \n self.addDimStyle(dimStyle)\n \n return True\n\n\n #============================================================================\n # getDimIdByEntity\n #============================================================================\n def getDimIdByEntity(self, entity):\n \"\"\"\n La funzione, data un'entità, verifica se fa parte di uno stile di quotatura della lista e,\n in caso di successo, restituisce lo stile di quotatura e il codice della quotatura altrimenti None, None.\n \"\"\"\n for dimStyle in self.dimStyleList:\n dimId = dimStyle.getDimIdByEntity(entity)\n if dimId is not None:\n return dimStyle, dimId\n return None, None\n\n\n #============================================================================\n # getDimEntity\n #============================================================================\n def getDimEntity(self, layer, fid = None):\n \"\"\"\n la funzione può essere richiamata in 2 modi:\n con un solo parametro di tipo QadEntity\n con due parametri, il primo QgsVectorLayer e il secondo l'id della feature\n \"\"\"\n # verifico se l'entità appartiene ad uno stile di quotatura\n if type(layer) == QgsVectorLayer:\n entity = QadEntity()\n entity.set(layer, fid)\n dimStyle, dimId = self.getDimIdByEntity(entity)\n else: # il parametro layer puo essere un oggetto QadEntity\n dimStyle, dimId = self.getDimIdByEntity(layer)\n \n if (dimStyle is None) or (dimId is None):\n return None\n \n dimEntity = QadDimEntity()\n if dimEntity.initByDimId(dimStyle, dimId) == False:\n return None\n\n return dimEntity\n\n\n #============================================================================\n # getDimListByLayer\n #============================================================================\n def getDimListByLayer(self, layer):\n \"\"\"\n La funzione, dato un layer, verifica se fa parte di uno o più stili di quotatura della lista e,\n in caso di successo, restituisce la lista degli stili di quotatura di appartenenza.\n \"\"\"\n result = []\n for dimStyle in self.dimStyleList:\n if dimStyle.isDimLayer(layer):\n if dimStyle not in result:\n result.append(dimStyle)\n\n return result\n\n\n #============================================================================\n # addAllDimComponentsToEntitySet\n #============================================================================\n def addAllDimComponentsToEntitySet(self, entitySet, onlyEditableLayers):\n \"\"\"\n La funzione verifica se le entità che fanno parte di un entitySet sono anche parte di quotatura e,\n in caso affermativo, aggiunge tutti i componenti della quotatura all'entitySet.\n \"\"\"\n elaboratedDimEntitySet = QadEntitySet() # lista delle entità di quota elaborate\n entity = QadEntity()\n for layerEntitySet in entitySet.layerEntitySetList: \n # verifico se il layer appartiene ad uno o più stili di quotatura\n dimStyleList = self.getDimListByLayer(layerEntitySet.layer)\n for dimStyle in dimStyleList: # per tutti gli stili di quotatura\n if dimStyle is not None:\n remove = False\n if onlyEditableLayers == True:\n # se anche un solo layer non é modificabile \n if dimStyle.getTextualLayer().isEditable() == False or \\\n dimStyle.getSymbolLayer().isEditable() == False or \\\n dimStyle.getLinearLayer().isEditable() == False:\n remove = True\n features = layerEntitySet.getFeatureCollection()\n for feature in features:\n entity.set(layerEntitySet.layer, feature.id())\n if not elaboratedDimEntitySet.containsEntity(entity): \n dimId = dimStyle.getDimIdByEntity(entity)\n if dimId is not None:\n dimEntitySet = dimStyle.getEntitySet(dimId)\n if remove == False:\n entitySet.unite(dimEntitySet)\n else:\n entitySet.subtract(dimEntitySet)\n \n elaboratedDimEntitySet.unite(entitySet)\n\n\n #============================================================================\n # removeAllDimLayersFromEntitySet\n #============================================================================\n def removeAllDimLayersFromEntitySet(self, entitySet):\n \"\"\"\n La funzione rimuove tutte le entità che fanno parte di quotature dall'entitySet.\n \"\"\"\n for dimStyle in self.dimStyleList:\n entitySet.removeLayerEntitySet(dimStyle.getTextualLayer())\n entitySet.removeLayerEntitySet(dimStyle.getSymbolLayer())\n entitySet.removeLayerEntitySet(dimStyle.getLinearLayer())\n\n\n#===============================================================================\n# QadDimEntity dimension entity class\n#===============================================================================\nclass QadDimEntity():\n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, dimEntity = None):\n if dimEntity is not None:\n self.set(dimEntity)\n else:\n self.dimStyle = None\n self.textualFeature = None\n self.linearFeatures = []\n self.symbolFeatures = []\n\n \n def whatIs(self):\n return \"DIMENTITY\"\n\n\n def isInitialized(self):\n if (self.dimStyle is None) or (self.textualFeature is None):\n return False\n else:\n return True\n\n\n def __eq__(self, dimEntity):\n \"\"\"self == other\"\"\"\n if self.isInitialized() == False or dimEntity.isInitialized() == False :\n return False\n\n if self.getTextualLayer() == dimEntity.getTextualLayer() and self.getDimId() == dimEntity.getDimId():\n return True\n else:\n return False \n\n\n #============================================================================\n # getTextualLayer\n #============================================================================\n def getTextualLayer(self):\n if self.dimStyle is None:\n return None\n return self.dimStyle.getTextualLayer()\n \n \n #============================================================================\n # getLinearLayer\n #============================================================================\n def getLinearLayer(self):\n if self.dimStyle is None:\n return None\n return self.dimStyle.getLinearLayer()\n \n \n #============================================================================\n # getSymbolLayer\n #============================================================================\n def getSymbolLayer(self):\n if self.dimStyle is None:\n return None\n return self.dimStyle.getSymbolLayer()\n \n \n #============================================================================\n # set\n #============================================================================\n def set(self, dimEntity):\n self.dimStyle = QadDimStyle(dimEntity.dimStyle)\n \n self.textualFeature = QgsFeature(dimEntity.textualFeature)\n\n del self.linearFeatures[:]\n for f in dimEntity.linearFeatures:\n self.linearFeatures.append(QgsFeature(f))\n\n del self.symbolFeatures[:]\n for f in dimEntity.symbolFeatures:\n self.symbolFeatures.append(QgsFeature(f))\n\n\n #============================================================================\n # getLinearGeometryCollection\n #============================================================================\n def getLinearGeometryCollection(self):\n result = []\n for f in self.linearFeatures:\n result.append(f.geometry())\n return result\n\n \n #============================================================================\n # getSymbolGeometryCollection\n #============================================================================\n def getSymbolGeometryCollection(self):\n result = []\n for f in self.symbolFeatures:\n result.append(f.geometry())\n return result\n\n\n #============================================================================\n # getDimId\n #============================================================================\n def getDimId(self):\n \"\"\"\n La funzione restituisce il codice della quotatura altrimenti None.\n \"\"\"\n try:\n return self.textualFeature.attribute(self.idFieldName)\n except:\n return None \n\n\n def recodeDimIdToFeature(self, newDimId): \n try:\n # imposto il codice della quota\n self.textualFeature.setAttribute(self.dimStyle.idFieldName, newDimId)\n for f in self.linearFeatures:\n f.setAttribute(self.dimStyle.idParentFieldName, newDimId)\n for f in self.symbolFeatures:\n f.setAttribute(self.dimStyle.idParentFieldName, newDimId)\n except:\n return False\n\n return True\n \n \n #============================================================================\n # addToLayers\n #============================================================================\n def addToLayers(self, plugIn):\n # prima di tutto inserisco il testo di quota per ricodificare la quotatura\n # plugIn, layer, feature, coordTransform, refresh, check_validity\n if qad_layer.addFeatureToLayer(plugIn, self.getTextualLayer(), self.textualFeature, None, False, False) == False:\n return False\n newDimId = self.textualFeature.id()\n \n if self.recodeDimIdToFeature(newDimId) == False:\n return False\n\n # plugIn, layer, feature, refresh, check_validity\n if qad_layer.updateFeatureToLayer(plugIn, self.getTextualLayer(), self.textualFeature, False, False) == False:\n return False\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getLinearLayer(), self.linearFeatures, None, False, False) == False: \n return False\n # plugIn, layer, features, coordTransform, refresh, check_validity\n if qad_layer.addFeaturesToLayer(plugIn, self.getSymbolLayer(), self.symbolFeatures, None, False, False) == False: \n return False\n \n return True\n \n \n #============================================================================\n # deleteToLayers\n #============================================================================\n def deleteToLayers(self, plugIn):\n ids =[]\n\n # plugIn, layer, featureId, refresh\n if qad_layer.deleteFeatureToLayer(plugIn, self.getTextualLayer(), self.textualFeature.id(), False) == False:\n return False\n \n for f in self.linearFeatures:\n ids.append(f.id())\n # plugIn, layer, featureIds, refresh\n if qad_layer.deleteFeaturesToLayer(plugIn, self.getLinearLayer(), ids, False) == False:\n return False\n \n del ids[:]\n for f in self.symbolFeatures:\n ids.append(f.id())\n # plugIn, layer, featureIds, refresh\n if qad_layer.deleteFeaturesToLayer(plugIn, self.getSymbolLayer(), ids, False) == False:\n return False\n \n return True\n \n \n #============================================================================\n # initByEntity\n #============================================================================\n def initByEntity(self, dimStyle, entity):\n dimId = dimStyle.getDimIdByEntity(entity)\n if dimId is None:\n return False\n return self.initByDimId(dimStyle, dimId)\n\n\n #============================================================================\n # initByDimId\n #============================================================================\n def initByDimId(self, dimStyle, dimId):\n self.dimStyle = QadDimStyle(dimStyle)\n entitySet = self.dimStyle.getEntitySet(dimId)\n\n self.textualFeature = None\n layerEntitySet = entitySet.findLayerEntitySet(self.getTextualLayer())\n features = layerEntitySet.getFeatureCollection()\n self.textualFeature = features[0]\n \n # entità lineari\n layerEntitySet = entitySet.findLayerEntitySet(self.getLinearLayer())\n del self.linearFeatures[:] # svuoto la lista\n if layerEntitySet is not None:\n self.linearFeatures = layerEntitySet.getFeatureCollection()\n \n # entità puntuali\n layerEntitySet = entitySet.findLayerEntitySet(self.getSymbolLayer())\n del self.symbolFeatures[:] # svuoto la lista\n if layerEntitySet is not None:\n self.symbolFeatures = layerEntitySet.getFeatureCollection()\n \n return True\n\n\n #============================================================================\n # getEntitySet\n #============================================================================\n def getEntitySet(self): \n result = QadEntitySet()\n \n layerEntitySet = QadLayerEntitySet()\n layerEntitySet.set(self.getTextualLayer(), [self.textualFeature])\n result.addLayerEntitySet(layerEntitySet)\n\n layerEntitySet = QadLayerEntitySet()\n layerEntitySet.set(self.getLinearLayer(), self.linearFeatures)\n result.addLayerEntitySet(layerEntitySet)\n \n layerEntitySet = QadLayerEntitySet()\n layerEntitySet.set(self.getSymbolLayer(), self.symbolFeatures)\n result.addLayerEntitySet(layerEntitySet)\n \n return result\n \n\n #============================================================================\n # selectOnLayer\n #============================================================================\n def selectOnLayer(self, incremental = True):\n self.getEntitySet().selectOnLayer(incremental)\n \n\n #============================================================================\n # deselectOnLayer\n #============================================================================\n def deselectOnLayer(self):\n self.getEntitySet().deselectOnLayer()\n\n \n #============================================================================\n # getDimPts\n #============================================================================\n def getDimPts(self, destinationCrs = None):\n \"\"\"\n destinationCrs = sistema di coordinate in cui verrà restituito il risultato\n \"\"\"\n \n dimPt1 = None\n dimPt2 = None\n\n if len(self.dimStyle.componentFieldName) > 0:\n # cerco tra gli elementi puntuali\n for f in self.symbolFeatures:\n try:\n value = f.attribute(self.dimStyle.componentFieldName)\n if value == QadDimComponentEnum.DIM_PT1: # primo punto da quotare (\"Dimension point 1\")\n g = f.geometry()\n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(self.getSymbolLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n \n dimPt1 = g.asPoint()\n elif value == QadDimComponentEnum.DIM_PT2: # secondo punto da quotare (\"Dimension point 2\")\n g = f.geometry()\n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(self.getSymbolLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n \n dimPt2 = g.asPoint()\n except:\n return None, None\n\n return dimPt1, dimPt2 \n \n\n #============================================================================\n # getDimLinePosPt\n #============================================================================\n def getDimLinePosPt(self, containerGeom = None, destinationCrs = None):\n \"\"\"\n Trova fra i vari punti possibili un punto che indichi dove si trova la linea di quota (in destinationCrs tipicamente = map coordinate)\n se containerGeom <> None il punto deve essere contenuto in containerGeom\n containerGeom = può essere una QgsGeometry rappresentante un poligono (in destinationCrs tipicamente = map coordinate) contenente i punti di geom da stirare\n oppure una lista dei punti da stirare (in destinationCrs tipicamente = map coordinate)\n destinationCrs = sistema di coordinate in cui è espresso containerGeom e in cui verrà restituito il risultato\n \"\"\"\n \n if len(self.dimStyle.componentFieldName) > 0:\n # prima cerco tra gli elementi lineari\n for f in self.linearFeatures:\n try:\n value = f.attribute(self.dimStyle.componentFieldName)\n # primo punto da quotare (\"Dimension point 1\") o secondo punto da quotare (\"Dimension point 2\")\n if value == QadDimComponentEnum.DIM_LINE1 or value == QadDimComponentEnum.DIM_LINE2:\n g = f.geometry()\n\n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(self.getLinearLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n\n pts = g.asPolyline()\n if containerGeom is not None: # verifico che il punto iniziale sia interno a containerGeom\n if type(containerGeom) == QgsGeometry: # geometria \n if containerGeom.contains(pts[0]) == True:\n return pts[0]\n else:\n # verifico che il punto finale sia interno a containerGeom\n if containerGeom.contains(pts[-1]) == True:\n return pts[-1]\n elif type(containerGeom) == list: # lista di punti\n for containerPt in containerGeom:\n if ptNear(containerPt, pts[0]): # se i punti sono sufficientemente vicini\n return pts[0]\n else:\n # verifico il punto finale\n if ptNear(containerPt,pts[-1]):\n return pts[-1]\n else:\n return pts[0] # punto iniziale\n except:\n return None\n \n # poi cerco tra gli elementi puntuali\n for f in self.symbolFeatures:\n try:\n value = f.attribute(self.dimStyle.componentFieldName)\n # primo blocco della freccia (\"Block 1\") o secondo blocco della freccia (\"Block 2\")\n if value == QadDimComponentEnum.BLOCK1 or value == QadDimComponentEnum.BLOCK2:\n g = f.geometry()\n\n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(self.getSymbolLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n \n dimLinePosPt = g.asPoint()\n if containerGeom is not None: # verifico che il punto sia interno a containerGeom\n if type(containerGeom) == QgsGeometry: # geometria \n if containerGeom.contains(dimLinePosPt) == True:\n return dimLinePosPt\n elif type(containerGeom) == list: # lista di punti\n for containerPt in containerGeom:\n if ptNear(containerPt, dimLinePosPt): # se i punti sono sufficientemente vicini\n return dimLinePosPt\n else:\n return dimLinePosPt\n except:\n return None\n\n return None\n\n\n #============================================================================\n # getDimLinearAlignment\n #============================================================================\n def getDimLinearAlignment(self):\n dimLinearAlignment = None\n dimLineRotation = None\n Pts = []\n \n if len(self.dimStyle.componentFieldName) > 0:\n # prima cerco tra gli elementi lineari\n for f in self.linearFeatures:\n try:\n value = f.attribute(self.dimStyle.componentFieldName)\n if value == QadDimComponentEnum.DIM_LINE1: # primo punto da quotare (\"Dimension point 1\")\n Pts = f.geometry().asPolyline()\n break\n elif value == QadDimComponentEnum.DIM_LINE2: # secondo punto da quotare (\"Dimension point 2\")\n Pts = f.geometry().asPolyline()\n break\n except:\n return None, None\n\n if Pts is None:\n # poi cerco tra gli elementi puntuali\n for f in self.symbolFeatures:\n try:\n value = f.attribute(self.dimStyle.componentFieldName)\n if value == QadDimComponentEnum.BLOCK1: # primo blocco della freccia (\"Block 1\")\n Pts.append(f.geometry().asPoint())\n elif value == QadDimComponentEnum.BLOCK2: # secondo blocco della freccia (\"Block 1\")\n Pts.append(f.geometry().asPoint())\n except:\n return None, None\n \n if len(Pts) > 1: # almeno 2 punti \n if qad_utils.doubleNear(Pts[0].x(), Pts[-1].x()): # linea verticale (stessa x)\n dimLinearAlignment = QadDimStyleAlignmentEnum.VERTICAL\n dimLineRotation = 0\n elif qad_utils.doubleNear(Pts[0].y(), Pts[-1].y()): # linea orizzontale (stessa y)\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n dimLineRotation = 0\n else:\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n dimLineRotation = qad_utils.getAngleBy2Pts(Pts[0], Pts[-1])\n \n \n return dimLinearAlignment, dimLineRotation\n\n\n #============================================================================\n # getTextRot\n #============================================================================\n def getTextRot(self):\n textRot = None\n \n if len(self.dimStyle.rotFieldName) > 0:\n try:\n textRot = self.textualFeature.attribute(self.dimStyle.rotFieldName)\n except:\n return None\n\n return qad_utils.toRadians(textRot)\n\n\n #============================================================================\n # getTextValue\n #============================================================================\n def getTextValue(self):\n textValue = None\n\n # se il testo dipende da un solo campo \n labelFieldNames = qad_label.get_labelFieldNames(self.dimStyle.getTextualLayer())\n if len(labelFieldNames) == 1 and len(labelFieldNames[0]) > 0:\n try:\n textValue = self.textualFeature.attribute(labelFieldNames[0])\n except:\n return None\n\n return textValue\n\n\n #============================================================================\n # getTextPt\n #============================================================================\n def getTextPt(self, destinationCrs = None):\n # destinationCrs = sistema di coordinate in cui verrà restituito il risultato\n g = self.textualFeature.geometry()\n if (destinationCrs is not None) and destinationCrs != self.getTextualLayer().crs():\n g.transform(QgsCoordinateTransform(self.getTextualLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n \n return g.asPoint()\n\n\n #============================================================================\n # isCalculatedText\n #============================================================================\n def isCalculatedText(self):\n measure = self.getTextValue()\n \n if self.dimStyle.dimType == QadDimTypeEnum.ALIGNED: # quota lineare allineata ai punti di origine delle linee di estensione\n dimPt1, dimPt2 = self.getDimPts() \n return measure == self.dimStyle.getFormattedText(qad_utils.getDistance(dimPt1, dimPt2))\n elif self.dimStyle.dimType == QadDimTypeEnum.LINEAR: # quota lineare con una linea di quota orizzontale o verticale\n dimPt1, dimPt2 = self.getDimPts()\n linePosPt = self.getDimLinePosPt()\n preferredAlignment, dimLineRotation = self.getDimLinearAlignment()\n \n dimLine = self.dimStyle.getDimLine(dimPt1, dimPt2, linePosPt, preferredAlignment, dimLineRotation)\n return measure == self.dimStyle.getFormattedText(qad_utils.getDistance(dimLine[0], dimLine[1]))\n\n return True\n\n\n #============================================================================\n # move\n #============================================================================\n def move(self, offSetX, offSetY):\n # offSetX = spostamento X in map coordinate\n # offSetY = spostamento Y in map coordinate\n destinationCrs = plugIn.canvas.mapRenderer().destinationCrs()\n \n g = self.textualFeature.geometry()\n \n if (destinationCrs is not None) and destinationCrs != self.getTextualLayer().crs():\n g.transform(QgsCoordinateTransform(self.getTextualLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n\n g = qad_utils.moveQgsGeometry(g, offSetX, offSetY)\n\n if (destinationCrs is not None) and destinationCrs != self.getTextualLayer().crs():\n g.transform(QgsCoordinateTransform(destinationCrs, self.getTextualLayer().crs())) # trasformo la geometria in layer coordinate\n \n self.textualFeature.setGeometry(g)\n\n\n for f in self.linearFeatures:\n g = f.geometry()\n \n if (destinationCrs is not None) and destinationCrs != self.getLinearLayer().crs():\n g.transform(QgsCoordinateTransform(self.getLinearLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n\n g = qad_utils.moveQgsGeometry(g, offSetX, offSetY)\n\n if (destinationCrs is not None) and destinationCrs != self.getLinearLayer().crs():\n g.transform(QgsCoordinateTransform(destinationCrs, self.getLinearLayer().crs())) # trasformo la geometria in layer coordinate\n \n f.setGeometry(g)\n \n for f in self.symbolFeatures:\n g = f.geometry()\n \n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(self.getSymbolLayer().crs(), destinationCrs)) # trasformo la geometria in map coordinate\n\n g = qad_utils.moveQgsGeometry(g, offSetX, offSetY)\n\n if (destinationCrs is not None) and destinationCrs != self.getSymbolLayer().crs():\n g.transform(QgsCoordinateTransform(destinationCrs, self.getSymbolLayer().crs())) # trasformo la geometria in layer coordinate\n \n f.setGeometry(g)\n\n \n #============================================================================\n # rotate\n #============================================================================\n def rotate(self, plugIn, basePt, angle):\n # basePt = punto base espresso in map coordinate\n destinationCrs = plugIn.canvas.mapRenderer().destinationCrs()\n \n measure = self.getTextValue()\n \n if self.dimStyle.dimType == QadDimTypeEnum.ALIGNED: # quota lineare allineata ai punti di origine delle linee di estensione\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None):\n dimPt1 = qad_utils.rotatePoint(dimPt1, basePt, angle)\n dimPt2 = qad_utils.rotatePoint(dimPt2, basePt, angle) \n linePosPt = qad_utils.rotatePoint(linePosPt, basePt, angle)\n \n dimEntity, textOffsetRect = self.dimStyle.getAlignedDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure)\n self.set(dimEntity)\n elif self.dimStyle.dimType == QadDimTypeEnum.LINEAR: # quota lineare con una linea di quota orizzontale o verticale\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n preferredAlignment, dimLineRotation = self.getDimLinearAlignment()\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None) and \\\n (preferredAlignment is not None) and (dimLineRotation is not None):\n textForcedRot = self.getTextRot()\n if textForcedRot is not None:\n self.dimStyle.textForcedRot = textForcedRot\n\n dimPt1 = qad_utils.rotatePoint(dimPt1, basePt, angle)\n dimPt2 = qad_utils.rotatePoint(dimPt2, basePt, angle) \n linePosPt = qad_utils.rotatePoint(linePosPt, basePt, angle) \n dimLinearAlignment, dimLineRotation = self.getDimLinearAlignment()\n\n if dimLinearAlignment == QadDimStyleAlignmentEnum.VERTICAL:\n dimLineRotation = math.pi / 2\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n dimLineRotation = dimLineRotation + angle\n \n dimEntity, textOffsetRect = self.dimStyle.getLinearDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure, \\\n dimLinearAlignment, \\\n dimLineRotation)\n self.set(dimEntity)\n\n\n #============================================================================\n # scale\n #============================================================================\n def scale(self, plugIn, basePt, scale):\n # basePt = punto base espresso in map coordinate\n destinationCrs = plugIn.canvas.mapRenderer().destinationCrs()\n\n measure = None if self.isCalculatedText() else self.getTextValue()\n \n if self.dimStyle.dimType == QadDimTypeEnum.ALIGNED: # quota lineare allineata ai punti di origine delle linee di estensione\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None):\n dimPt1 = qad_utils.scalePoint(dimPt1, basePt, scale)\n dimPt2 = qad_utils.scalePoint(dimPt2, basePt, scale) \n linePosPt = qad_utils.scalePoint(linePosPt, basePt, scale)\n \n dimEntity, textOffsetRect = self.dimStyle.getAlignedDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure)\n self.set(dimEntity)\n elif self.dimStyle.dimType == QadDimTypeEnum.LINEAR: # quota lineare con una linea di quota orizzontale o verticale\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n preferredAlignment, dimLineRotation = self.getDimLinearAlignment()\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None) and \\\n (preferredAlignment is not None) and (dimLineRotation is not None):\n textForcedRot = self.getTextRot()\n if textForcedRot is not None:\n self.dimStyle.textForcedRot = textForcedRot\n\n dimPt1 = qad_utils.scalePoint(dimPt1, basePt, scale)\n dimPt2 = qad_utils.scalePoint(dimPt2, basePt, scale) \n linePosPt = qad_utils.scalePoint(linePosPt, basePt, scale) \n dimLinearAlignment, dimLineRotation = self.getDimLinearAlignment()\n\n if dimLinearAlignment == QadDimStyleAlignmentEnum.VERTICAL:\n dimLineRotation = math.pi / 2\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n\n dimEntity, textOffsetRect = self.dimStyle.getLinearDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure, \\\n dimLinearAlignment, \\\n dimLineRotation)\n self.set(dimEntity)\n\n\n #============================================================================\n # mirror\n #============================================================================\n def mirror(self, plugIn, mirrorPt, mirrorAngle):\n # mirrorPt = punto base espresso in map coordinate\n destinationCrs = plugIn.canvas.mapRenderer().destinationCrs()\n\n measure = None if self.isCalculatedText() else self.getTextValue()\n \n if self.dimStyle.dimType == QadDimTypeEnum.ALIGNED: # quota lineare allineata ai punti di origine delle linee di estensione\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None):\n dimPt1 = qad_utils.mirrorPoint(dimPt1, mirrorPt, mirrorAngle)\n dimPt2 = qad_utils.mirrorPoint(dimPt2, mirrorPt, mirrorAngle) \n linePosPt = qad_utils.mirrorPoint(linePosPt, mirrorPt, mirrorAngle)\n \n dimEntity, textOffsetRect = self.dimStyle.getAlignedDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure)\n self.set(dimEntity)\n elif self.dimStyle.dimType == QadDimTypeEnum.LINEAR: # quota lineare con una linea di quota orizzontale o verticale\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(None, destinationCrs)\n preferredAlignment, dimLineRotation = self.getDimLinearAlignment()\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None) and \\\n (preferredAlignment is not None) and (dimLineRotation is not None):\n textForcedRot = self.getTextRot()\n if textForcedRot is not None:\n self.dimStyle.textForcedRot = textForcedRot\n\n dimPt1 = qad_utils.mirrorPoint(dimPt1, mirrorPt, mirrorAngle)\n dimPt2 = qad_utils.mirrorPoint(dimPt2, mirrorPt, mirrorAngle) \n linePosPt = qad_utils.mirrorPoint(linePosPt, mirrorPt, mirrorAngle) \n dimLinearAlignment, dimLineRotation = self.getDimLinearAlignment()\n\n if dimLinearAlignment == QadDimStyleAlignmentEnum.VERTICAL:\n dimLineRotation = math.pi / 2\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n \n ptDummy = qad_utils.getPolarPointByPtAngle(mirrorPt, dimLineRotation, 1)\n ptDummy = qad_utils.mirrorPoint(ptDummy, mirrorPt, mirrorAngle)\n dimLineRotation = qad_utils.getAngleBy2Pts(mirrorPt, ptDummy) \n\n dimEntity, textOffsetRect = self.dimStyle.getLinearDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure, \\\n dimLinearAlignment, \\\n dimLineRotation)\n self.set(dimEntity)\n\n\n #============================================================================\n # stretch\n #============================================================================\n def stretch(self, plugIn, containerGeom, offSetX, offSetY):\n \"\"\"\n containerGeom = può essere una QgsGeometry rappresentante un poligono contenente i punti di geom da stirare\n oppure una lista dei punti da stirare espressi in map coordinate\n offSetX = spostamento X in map coordinate\n offSetY = spostamento Y in map coordinate\n \"\"\"\n destinationCrs = plugIn.canvas.mapRenderer().destinationCrs()\n \n measure = None if self.isCalculatedText() else self.getTextValue()\n \n if self.dimStyle.dimType == QadDimTypeEnum.ALIGNED: # quota lineare allineata ai punti di origine delle linee di estensione\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(containerGeom, destinationCrs)\n \n if dimPt1 is not None:\n newPt = qad_stretch_fun.stretchPoint(dimPt1, containerGeom, offSetX, offSetY)\n if newPt is not None:\n dimPt1 = newPt\n \n if dimPt2 is not None:\n newPt = qad_stretch_fun.stretchPoint(dimPt2, containerGeom, offSetX, offSetY)\n if newPt is not None:\n dimPt2 = newPt\n\n if linePosPt is not None:\n newPt = qad_stretch_fun.stretchPoint(linePosPt, containerGeom, offSetX, offSetY)\n if newPt is not None:\n linePosPt = newPt\n else:\n linePosPt = self.getDimLinePosPt()\n # verifico se è stato coinvolto il testo della quota\n if qad_stretch_fun.isPtContainedForStretch(self.getTextPt(destinationCrs), containerGeom):\n if linePosPt is not None:\n linePosPt = qad_utils.movePoint(linePosPt, offSetX, offSetY)\n \n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None):\n dimEntity, textOffsetRect = self.dimStyle.getAlignedDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure)\n self.set(dimEntity)\n elif self.dimStyle.dimType == QadDimTypeEnum.LINEAR: # quota lineare con una linea di quota orizzontale o verticale\n dimPt1, dimPt2 = self.getDimPts(destinationCrs)\n linePosPt = self.getDimLinePosPt(containerGeom, destinationCrs)\n \n dimLinearAlignment, dimLineRotation = self.getDimLinearAlignment()\n \n if dimPt1 is not None:\n newPt = qad_stretch_fun.stretchPoint(dimPt1, containerGeom, offSetX, offSetY)\n if newPt is not None:\n dimPt1 = newPt\n \n if dimPt2 is not None:\n newPt = qad_stretch_fun.stretchPoint(dimPt2, containerGeom, offSetX, offSetY)\n if newPt is not None:\n dimPt2 = newPt\n\n if linePosPt is not None:\n newPt = qad_stretch_fun.stretchPoint(linePosPt, containerGeom, offSetX, offSetY)\n if newPt is not None:\n linePosPt = newPt\n else:\n linePosPt = self.getDimLinePosPt()\n # verifico se è stato coinvolto il testo della quota\n if qad_stretch_fun.isPtContainedForStretch(self.getTextPt(destinationCrs), containerGeom):\n if linePosPt is not None:\n linePosPt = qad_utils.movePoint(linePosPt, offSetX, offSetY)\n\n if (dimPt1 is not None) and (dimPt2 is not None) and \\\n (linePosPt is not None) and \\\n (dimLinearAlignment is not None) and (dimLineRotation is not None):\n textForcedRot = self.getTextRot()\n if textForcedRot is not None:\n self.dimStyle.textForcedRot = textForcedRot\n\n if dimLinearAlignment == QadDimStyleAlignmentEnum.VERTICAL:\n dimLineRotation = math.pi / 2\n dimLinearAlignment = QadDimStyleAlignmentEnum.HORIZONTAL\n \n dimEntity, textOffsetRect = self.dimStyle.getLinearDimFeatures(plugIn.canvas, \\\n dimPt1, \\\n dimPt2, \\\n linePosPt, \\\n measure, \\\n dimLinearAlignment, \\\n dimLineRotation)\n self.set(dimEntity)\n\n\n #============================================================================\n # getDimComponentByEntity\n #============================================================================\n def getDimComponentByEntity(self, entity):\n \"\"\"\n La funzione, data un'entità, restituisce il componente della quotatura.\n \"\"\"\n if entity.layer == self.getTextualLayer():\n return QadDimComponentEnum.TEXT_PT\n elif entity.layer == self.getLinearLayer() or \\\n entity.layer == self.getSymbolLayer():\n try:\n return entity.getFeature().attribute(self.dimStyle.componentFieldName)\n except:\n return None\n \n return None\n\n\n#===============================================================================\n# = variabile globale\n#===============================================================================\n\nQadDimStyles = QadDimStylesClass() # lista degli stili di quotatura caricati"
},
{
"alpha_fraction": 0.6098405122756958,
"alphanum_fraction": 0.6130547523498535,
"avg_line_length": 42.96195602416992,
"blob_id": "5856a63683b3020eebba27ae1e4de1f364ac5348",
"content_id": "e7beed74da453de0953f11bcbcfa42ef64ada56a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8093,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 184,
"path": "/qad_setcurrlayerbygraph_cmd.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n comando SETCURRLAYERBYGRAPH per settare il layer corrente tramite selezione grafica\n comando SETCURRUPDATEABLELAYERBYGRAPH per settare il layer corrente e porlo in modifica \n tramite selezione grafica\n \n ------------------\n begin : 2013-05-22\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_generic_cmd import QadCommandClass\nfrom qad_snapper import *\nfrom qad_getpoint import *\nfrom qad_entsel_cmd import QadEntSelClass\nfrom qad_ssget_cmd import QadSSGetClass\nfrom qad_msg import QadMsg\n\n\n# Classe che gestisce il comando SETCURRLAYERBYGRAPH\nclass QadSETCURRLAYERBYGRAPHCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadSETCURRLAYERBYGRAPHCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"SETCURRLAYERBYGRAPH\")\n\n def getEnglishName(self):\n return \"SETCURRLAYERBYGRAPH\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runSETCURRLAYERBYGRAPHCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/setcurrlayerbygraph.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_SETCURRLAYERBYGRAPH\", \"Sets a layer of a graphical object as current.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.EntSelClass = None\n\n def __del__(self):\n QadCommandClass.__del__(self)\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 0 or self.step == 1: # quando si é in fase di selezione entità\n return self.EntSelClass.getPointMapTool(drawMode)\n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n \n def waitForEntsel(self, msgMapTool, msg):\n if self.EntSelClass is not None:\n del self.EntSelClass \n self.EntSelClass = QadEntSelClass(self.plugIn)\n self.EntSelClass.msg = QadMsg.translate(\"Command_SETCURRLAYERBYGRAPH\", \"Select object whose layer will be the current layer: \")\n self.getPointMapTool().setSnapType(QadSnapTypeEnum.DISABLE)\n self.EntSelClass.run(msgMapTool, msg)\n \n def run(self, msgMapTool = False, msg = None):\n if self.plugIn.canvas.mapRenderer().destinationCrs().geographicFlag():\n self.showMsg(QadMsg.translate(\"QAD\", \"\\nThe coordinate reference system of the project must be a projected coordinate system.\\n\"))\n return True # fine comando\n \n if self.step == 0: \n self.waitForEntsel(msgMapTool, msg)\n self.step = 1\n return False # continua\n \n elif self.step == 1:\n if self.EntSelClass.run(msgMapTool, msg) == True:\n if self.EntSelClass.entity.isInitialized():\n layer = self.EntSelClass.entity.layer\n if self.plugIn.canvas.currentLayer() is None or \\\n self.plugIn.canvas.currentLayer() != layer: \n self.plugIn.canvas.setCurrentLayer(layer)\n self.plugIn.iface.setActiveLayer(layer) # lancia evento di deactivate e activate dei plugin\n self.plugIn.iface.legendInterface().refreshLayerSymbology(layer)\n msg = QadMsg.translate(\"Command_SETCURRLAYERBYGRAPH\", \"\\nThe current layer is {0}.\")\n self.showMsg(msg.format(layer.name()))\n del self.EntSelClass\n return True\n else: \n self.showMsg(QadMsg.translate(\"Command_SETCURRLAYERBYGRAPH\", \"No geometries in this position.\"))\n self.waitForEntsel(msgMapTool, msg)\n return False # continua\n \n\n# Classe che gestisce il comando SETCURRUPDATEABLELAYERBYGRAPH\nclass QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(QadCommandClass):\n\n def instantiateNewCmd(self):\n \"\"\" istanzia un nuovo comando dello stesso tipo \"\"\"\n return QadSETCURRUPDATEABLELAYERBYGRAPHCommandClass(self.plugIn)\n\n def getName(self):\n return QadMsg.translate(\"Command_list\", \"SETCURRUPDATEABLELAYERBYGRAPH\")\n\n def getEnglishName(self):\n return \"SETCURRUPDATEABLELAYERBYGRAPH\"\n\n def connectQAction(self, action):\n QObject.connect(action, SIGNAL(\"triggered()\"), self.plugIn.runSETCURRUPDATEABLELAYERBYGRAPHCommand)\n\n def getIcon(self):\n return QIcon(\":/plugins/qad/icons/setcurrupdateablelayerbygraph.png\")\n \n def getNote(self):\n # impostare le note esplicative del comando \n return QadMsg.translate(\"Command_SETCURRUPDATEABLELAYERBYGRAPH\", \"Sets the layers of a graphical objects as editable.\")\n \n def __init__(self, plugIn):\n QadCommandClass.__init__(self, plugIn)\n self.SSGetClass = QadSSGetClass(plugIn)\n self.firstTime = True\n\n def __del__(self):\n QadCommandClass.__del__(self)\n del self.SSGetClass\n \n def getPointMapTool(self, drawMode = QadGetPointDrawModeEnum.NONE):\n if self.step == 0: # quando si é in fase di selezione entità\n return self.SSGetClass.getPointMapTool(drawMode)\n else:\n return QadCommandClass.getPointMapTool(self, drawMode)\n \n def run(self, msgMapTool = False, msg = None): \n if self.step == 0: # inizio del comando \n if self.firstTime == True:\n self.showMsg(QadMsg.translate(\"Command_SETCURRUPDATEABLELAYERBYGRAPH\", \"\\nSelect objects whose layers will be the editable: \"))\n self.firstTime = False\n \n if self.SSGetClass.run(msgMapTool, msg) == True:\n # selezione terminata\n self.step = 1\n return self.run(msgMapTool, msg)\n else:\n return False # continua\n\n elif self.step == 1: # dopo aver atteso la selezione di oggetti\n message = \"\" \n for layerEntitySet in self.SSGetClass.entitySet.layerEntitySetList:\n layer = layerEntitySet.layer \n if layer.isEditable() == False:\n if layer.startEditing() == True:\n self.plugIn.iface.legendInterface().refreshLayerSymbology(layer)\n self.showMsg(QadMsg.translate(\"Command_SETCURRUPDATEABLELAYERBYGRAPH\", \"\\nThe layer {0} is editable.\").format(layer.name()))\n\n if len(self.SSGetClass.entitySet.layerEntitySetList) == 1:\n layer = self.SSGetClass.entitySet.layerEntitySetList[0].layer\n if self.plugIn.canvas.currentLayer() is None or \\\n self.plugIn.canvas.currentLayer() != layer: \n self.plugIn.canvas.setCurrentLayer(layer)\n self.plugIn.iface.setActiveLayer(layer) # lancia evento di deactivate e activate dei plugin\n self.plugIn.iface.legendInterface().refreshLayerSymbology(layer)\n self.showMsg(QadMsg.translate(\"Command_SETCURRUPDATEABLELAYERBYGRAPH\", \"\\nThe current layer is {0}.\").format(layer.name()))\n \n return True\n"
},
{
"alpha_fraction": 0.5831426382064819,
"alphanum_fraction": 0.5883908271789551,
"avg_line_length": 37.221717834472656,
"blob_id": "44feaff5def661875caf58caf88ca1302fc87744",
"content_id": "4cd38f4a891129e691e0884df9be8d4652520998",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 25352,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 663,
"path": "/qad_grip.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire i grip\n \n -------------------\n begin : 2015-09-29\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\n\n\nfrom qad_arc import *\nfrom qad_circle import *\nfrom qad_variables import *\nfrom qad_entity import *\nfrom qad_dim import *\n\n\n#===============================================================================\n# QadGripStatusEnum class.\n#===============================================================================\nclass QadGripStatusEnum():\n NONE = 0 # nessuno\n UNSELECTED = 1 # grip non selezionato\n SELECTED = 2 # grip selezionato\n HOVER = 3 # grip non selezionati quando il cursore si ferma su di essi\n\n\n#===============================================================================\n# QadGripIconTypeEnum class.\n#===============================================================================\nclass QadGripIconTypeEnum():\n NONE = 0 # nessuno\n BOX = 1 # un quadrato\n CIRCLE = 2 # cerchio\n RECTANGLE = 3 # rettangolo\n\n\n#===============================================================================\n# QadGripMarker class.\n#===============================================================================\nclass QadGripMarker(QgsMapCanvasItem):\n \"\"\"\n Classe che gestisce i marcatori dei grip\n \"\"\"\n \n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, mapCanvas):\n QgsMapCanvasItem.__init__(self, mapCanvas)\n self.canvas = mapCanvas\n self.iconType = QadGripIconTypeEnum.BOX # icon to be shown\n self.iconSize = QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPSIZE\"))\n self.borderColor = QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPCONTOUR\")) # color of the border\n self.center = QgsPoint(0, 0) # coordinates of the point in the center\n self.setGrip(QadGripStatusEnum.UNSELECTED, QadGripIconTypeEnum.BOX)\n\n \n def __del__(self): \n self.removeItem()\n\n\n def removeItem(self):\n self.canvas.scene().removeItem(self)\n \n\n def setCenter(self, point):\n # point è in map coordinates\n self.center = point\n pt = self.toCanvasCoordinates(self.center)\n self.setPos(pt)\n \n \n def setGrip(self, status, iconType, rot = None):\n # rot in radians counterclockwise (0 = horizontal)\n if status == QadGripStatusEnum.UNSELECTED:\n self.fillColor = QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPCOLOR\"))\n elif status == QadGripStatusEnum.SELECTED:\n self.fillColor = QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPHOT\"))\n elif status == QadGripStatusEnum.HOVER:\n self.fillColor = QadVariables.get(QadMsg.translate(\"Environment variables\", \"GRIPHOVER\"))\n \n self.status = status\n self.__iconType = iconType\n if rot is not None:\n self.__rot = -qad_utils.toDegrees(rot) # trasformo in gradi in senso orario\n\n \n def paint(self, painter, option, widget):\n \"\"\"\n painter é un QPainter\n \"\"\"\n\n s = self.iconSize / 2\n\n pen = QPen(QColor(self.borderColor))\n pen.setWidth(1)\n painter.setPen(pen)\n painter.rotate(self.__rot)\n\n if self.__iconType == QadGripIconTypeEnum.NONE:\n pass\n elif self.__iconType == QadGripIconTypeEnum.BOX:\n # un quadrato\n painter.fillRect(-s, -s, self.iconSize, self.iconSize, QBrush(QColor(self.fillColor)));\n painter.drawRect(-s, -s, self.iconSize, self.iconSize)\n elif self.__iconType == QadGripIconTypeEnum.CIRCLE:\n # cerchio\n painter.setBrush(QBrush(QColor(self.fillColor)))\n painter.drawEllipse(QPointF(0, 0), s, s)\n elif self.__iconType == QadGripIconTypeEnum.RECTANGLE:\n # un rettangolo\n painter.fillRect(-s, -s / 2, self.iconSize, self.iconSize / 2, QBrush(QColor(self.fillColor)));\n painter.drawRect(-s, -s / 2, self.iconSize, self.iconSize / 2)\n \n\n def boundingRect(self):\n if self.__rot != 0:\n width = qad_utils.getDistance(QgsPoint(0,0), QgsPoint(self.iconSize, self.iconSize))\n height = width \n else:\n width = self.iconSize\n height = self.iconSize\n \n return QRectF(-width/2, -height/2, width, height)\n\n\n def updatePosition(self):\n self.setCenter(self.center)\n\n\n#===============================================================================\n# QadGripPointTypeEnum class.\n#===============================================================================\nclass QadGripPointTypeEnum():\n NONE = 0 # nessuno\n VERTEX = 1 # vertice di una geometria\n LINE_MID_POINT = 2 # punto medio di un segmento\n CENTER = 3 # centro di un cerchio o di un arco\n QUA_POINT = 4 # punto quadrante\n ARC_MID_POINT = 5 # punto medio di un arco\n END_VERTEX = 6 # vertice iniziale e finale di una geometria\n\n\n#===============================================================================\n# QadEntityGripPoint class.\n#===============================================================================\nclass QadEntityGripPoint():\n \"\"\"\n Classe che gestisce un punto di grip per una entità\n \"\"\"\n\n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, mapCanvas, point, type, atGeom = 0, atSubGeom = 0, nVertex = 0, rot = 0.0):\n self.atGeom = atGeom # numero di geometria (0-index)\n self.atSubGeom = atSubGeom # numero di sotto-geometria (0-index)\n self.nVertex = nVertex # numero di vertice della QadLinearObjectList della geometria e sotto-geometria (0-index)\n \n self.gripType = type\n \n self.gripMarker = QadGripMarker(mapCanvas)\n self.gripMarker.setGrip(QadGripStatusEnum.UNSELECTED, self.gripType2IconType(self.gripType), rot)\n self.gripMarker.setCenter(point)\n \n def __del__(self):\n self.removeItem()\n del self.gripMarker\n\n def removeItem(self):\n self.gripMarker.removeItem()\n \n def getPoint(self):\n return self.gripMarker.center\n \n def isIntersecting(self, point):\n # point è in map coordinate\n ToleranceInMapUnits = self.gripMarker.iconSize * self.gripMarker.canvas.mapRenderer().mapUnitsPerPixel()\n if point.x() >= self.getPoint().x() - ToleranceInMapUnits and \\\n point.x() <= self.getPoint().x() + ToleranceInMapUnits and \\\n point.y() >= self.getPoint().y() - ToleranceInMapUnits and \\\n point.y() <= self.getPoint().y() + ToleranceInMapUnits:\n return True\n else:\n return False\n \n def select(self): # seleziona un grip\n self.gripMarker.setGrip(QadGripStatusEnum.SELECTED, self.gripType2IconType(self.gripType))\n self.gripMarker.show()\n\n def unselect(self): # deseleziona un grip\n self.gripMarker.setGrip(QadGripStatusEnum.UNSELECTED, self.gripType2IconType(self.gripType))\n self.gripMarker.show()\n\n def hover(self): # grip non selezionato quando il cursore si ferma su di esso\n if self.getStatus() == QadGripStatusEnum.UNSELECTED:\n self.gripMarker.setGrip(QadGripStatusEnum.HOVER, self.gripType2IconType(self.gripType))\n self.gripMarker.show()\n \n def getStatus(self):\n return self.gripMarker.status\n \n def gripType2IconType(self, gripType):\n if gripType == QadGripPointTypeEnum.VERTEX or gripType == QadGripPointTypeEnum.END_VERTEX:\n return QadGripIconTypeEnum.BOX\n elif gripType == QadGripPointTypeEnum.LINE_MID_POINT or gripType == QadGripPointTypeEnum.ARC_MID_POINT:\n return QadGripIconTypeEnum.RECTANGLE\n elif gripType == QadGripPointTypeEnum.CENTER:\n return QadGripIconTypeEnum.CIRCLE\n elif gripType == QadGripPointTypeEnum.QUA_POINT:\n return QadGripIconTypeEnum.BOX\n else:\n return None\n\n \n#===============================================================================\n# QadEntityGripPoints class.\n#===============================================================================\nclass QadEntityGripPoints(QgsMapCanvasItem):\n \"\"\"\n Classe che gestisce i punti di grip per una entità\n \"\"\"\n \n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, plugIn, entity = None, grips = 2):\n self.plugIn = plugIn\n self.mapCanvas = plugIn.canvas\n self.gripPoints = [] # lista dei punti di grip in map coordinate\n if entity is not None:\n self.entity = QadEntity(entity) \n self.gripPoints = self.initGripPoints(grips)\n\n\n def __del__(self):\n self.removeItems()\n\n\n def set(self, layer, featureId, grips = 2):\n self.entity = QadEntity()\n self.entity.set(layer, featureId)\n self.gripPoints = self.initGripPoints(grips)\n\n\n def removeItems(self):\n for gripPoint in self.gripPoints:\n gripPoint.removeItem()\n del self.gripPoints[:]\n\n\n def selectIntersectingGripPoints(self, point):\n # seleziona i grip che intersecano un punto in map coordinate \n res = 0\n for gripPoint in self.gripPoints:\n if gripPoint.isIntersecting(point):\n gripPoint.select()\n res = res + 1\n return res\n\n \n def unselectIntersectingGripPoints(self, point):\n # deseleziona i grip che intersecano un punto in map coordinate\n res = 0\n for gripPoint in self.gripPoints:\n if gripPoint.isIntersecting(point):\n gripPoint.unselect()\n res = res + 1\n return res\n\n\n def toggleSelectIntersectingGripPoints(self, point):\n # seleziona i grip deselezionati e deseleziona i grip selezionati\n # che intersecano un punto in map coordinate \n for gripPoint in self.gripPoints:\n if gripPoint.isIntersecting(point):\n if gripPoint.getStatus() == QadGripStatusEnum.SELECTED:\n gripPoint.unselect()\n else:\n gripPoint.select()\n \n\n def hoverIntersectingGripPoints(self, point):\n # seleziono in modo hover i grip che intersecano un punto (in map coordinate)\n # non selezionati quando il cursore si ferma su di esso\n res = 0\n for gripPoint in self.gripPoints:\n if gripPoint.isIntersecting(point):\n gripPoint.hover()\n res = res + 1\n else:\n status = gripPoint.getStatus()\n if status == QadGripStatusEnum.SELECTED:\n gripPoint.select()\n else:\n gripPoint.unselect()\n return res\n\n\n def isIntersecting(self, point):\n # ritorna il primo punto di grip che interseca point (in map coordinate)\n for gripPoint in self.gripPoints:\n if gripPoint.isIntersecting(point):\n return gripPoint\n return None\n\n\n def getSelectedGripPoints(self):\n # restituisce una lista di punti in cui i grip sono selezionati\n result = []\n \n for gripPoint in self.gripPoints:\n if gripPoint.getStatus() == QadGripStatusEnum.SELECTED:\n result.append(gripPoint)\n \n return result\n \n\n def initGripPoints(self, grips = 2):\n # restituisce una lista di QadEntityGripPoint\n atGeom = 0\n atSubGeom = 0\n result = []\n\n g = self.entity.getGeometry()\n if g is None:\n return result\n\n # verifico se l'entità appartiene ad uno stile di quotatura\n dimEntity = QadDimStyles.getDimEntity(self.entity)\n if dimEntity is not None:\n return self.getGripPointsFromDimComponent(dimEntity, self.entity)\n \n wkbType = g.wkbType()\n if wkbType == QGis.WKBPoint:\n # converto il punto dal layer coordinate in map coordinates\n pt = self.mapCanvas.mapSettings().layerToMapCoordinates(self.entity.layer, g.asPoint())\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.VERTEX)\n result.append(gp)\n \n elif wkbType == QGis.WKBMultiPoint:\n pointList = g.asMultiPoint() # vettore di punti\n atGeom = 0\n for point in pointList:\n # converto il punto dal layer coordinate in map coordinates\n pt = self.mapCanvas.mapSettings().layerToMapCoordinates(self.entity.layer, point)\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.VERTEX, atGeom)\n atGeom = atGeom + 1\n result.append(gp)\n \n elif wkbType == QGis.WKBLineString:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.entity.layer.crs(), self.mapCanvas.mapRenderer().destinationCrs())\n g.transform(coordTransform) \n result = self.getGripPointsFromPolyline(g.asPolyline(), 0, 0, grips)\n \n elif wkbType == QGis.WKBMultiLineString:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.entity.layer.crs(), self.mapCanvas.mapRenderer().destinationCrs())\n g.transform(coordTransform) \n\n lineList = g.asMultiPolyline() # vettore di linee\n atGeom = 0\n for line in lineList:\n result.extend(self.getGripPointsFromPolyline(line, atGeom, 0, grips))\n atGeom = atGeom + 1\n \n elif wkbType == QGis.WKBPolygon:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.entity.layer.crs(), self.mapCanvas.mapRenderer().destinationCrs())\n g.transform(coordTransform) \n\n lineList = g.asPolygon() # vettore di linee \n atGeom = 0\n for line in lineList:\n result.extend(self.getGripPointsFromPolyline(line, atGeom, 0, grips))\n atGeom = atGeom + 1\n # aggiungo il centroide\n pt = QgsGeometry().fromPolygon([line]).centroid().asPoint()\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.CENTER, atGeom, 0)\n result.append(gp)\n \n elif wkbType == QGis.WKBMultiPolygon:\n # trasformo la geometria nel crs del canvas per lavorare con coordinate piane xy\n coordTransform = QgsCoordinateTransform(self.entity.layer.crs(), self.mapCanvas.mapRenderer().destinationCrs())\n g.transform(coordTransform) \n\n polygonList = g.asMultiPolygon() # vettore di poligoni\n atGeom = 0\n for polygon in polygonList:\n atSubGeom = 0\n result1 = []\n for line in polygon:\n result.extend(self.getGripPointsFromPolyline(line, atGeom, atSubGeom, grips))\n # aggiungo il centroide\n pt = QgsGeometry.fromPolygon([line]).centroid().asPoint()\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.CENTER, atGeom, atSubGeom)\n result.append(gp)\n \n atSubGeom = atSubGeom + 1\n atGeom = atGeom + 1\n\n return result\n \n \n def getGripPointsFromPolyline(self, pointList, atGeom = 0, atSubGeom = 0, grips = 2):\n arc = QadArc()\n startEndVertices = arc.fromPolyline(pointList, 0)\n # se la polilinea è composta solo da un arco\n if startEndVertices and startEndVertices[0] == 0 and startEndVertices[1] == len(pointList)-1:\n return self.getGripPointsFromQadArc(arc, atGeom, atSubGeom, grips)\n else:\n circle = QadCircle()\n startEndVertices = circle.fromPolyline(pointList, 0)\n # se la polilinea è composta solo da un cerchio\n if startEndVertices and startEndVertices[0] == 0 and startEndVertices[1] == len(pointList)-1:\n return self.getGripPointsFromQadCircle(circle, atGeom, atSubGeom)\n else:\n linearObjectList = qad_utils.QadLinearObjectList()\n linearObjectList.fromPolyline(pointList)\n return self.getGripPointsFromQadLinearObjectList(linearObjectList, atGeom, atSubGeom, grips)\n\n \n def getGripPointsFromQadLinearObjectList(self, linearObjectList, atGeom = 0, atSubGeom = 0, grips = 2):\n \"\"\"\n Ottiene una lista di punti di grip da una QadLinearObjectList in map coordinate (vertici e punti medi con rotaz)\n grips = 1 Displays grips\n grips = 2 Displays additional midpoint grips on polyline segments\n \"\"\"\n result = []\n \n isClosed = linearObjectList.isClosed()\n nVertex = 0\n while nVertex < linearObjectList.qty():\n linearObject = linearObjectList.getLinearObjectAt(nVertex)\n startPt = linearObject.getStartPt()\n if isClosed == False and nVertex == 0:\n gp = QadEntityGripPoint(self.mapCanvas, startPt, QadGripPointTypeEnum.END_VERTEX, atGeom, atSubGeom, nVertex)\n else:\n gp = QadEntityGripPoint(self.mapCanvas, startPt, QadGripPointTypeEnum.VERTEX, atGeom, atSubGeom, nVertex)\n result.append(gp)\n if grips == 2:\n middlePt = linearObject.getMiddlePt()\n rot = linearObject.getTanDirectionOnMiddlePt()\n if linearObject.isSegment(): # linea\n gp = QadEntityGripPoint(self.mapCanvas, middlePt, QadGripPointTypeEnum.LINE_MID_POINT, atGeom, atSubGeom, nVertex, rot)\n else: # arco\n gp = QadEntityGripPoint(self.mapCanvas, middlePt, QadGripPointTypeEnum.ARC_MID_POINT, atGeom, atSubGeom, nVertex, rot)\n result.append(gp)\n nVertex = nVertex + 1\n\n # solo se la polilinea è aperta\n if isClosed == False:\n linearObject = linearObjectList.getLinearObjectAt(-1) # ultima parte\n endPt = linearObject.getEndPt() \n gp = QadEntityGripPoint(self.mapCanvas, endPt, QadGripPointTypeEnum.END_VERTEX, atGeom, atSubGeom, nVertex)\n \n result.append(gp)\n \n return result\n\n\n def getGripPointsFromQadCircle(self, circle, atGeom = 0, atSubGeom = 0):\n \"\"\"\n Ottiene una lista di punti di grip da un QadCircle in map coordinate (centro e punti quadrante)\n \"\"\"\n result = []\n gp = QadEntityGripPoint(self.mapCanvas, circle.center, QadGripPointTypeEnum.CENTER, atGeom, atSubGeom, -1)\n result.append(gp)\n qua_points = circle.getQuadrantPoints()\n for pt in qua_points:\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.QUA_POINT, atGeom, atSubGeom, -1)\n result.append(gp)\n \n return result\n\n\n def getGripPointsFromQadArc(self, arc, atGeom = 0, atSubGeom = 0, grips = 2):\n \"\"\"\n Ottiene una lista di punti di grip da un QadArc in map coordinate (punto centrale, iniziale, finale, medio)\n \"\"\"\n result = []\n gp = QadEntityGripPoint(self.mapCanvas, arc.center, QadGripPointTypeEnum.CENTER, atGeom, atSubGeom, -1)\n result.append(gp)\n\n startPt = arc.getStartPt()\n gp = QadEntityGripPoint(self.mapCanvas, startPt, QadGripPointTypeEnum.END_VERTEX, atGeom, atSubGeom, 0)\n result.append(gp)\n\n endPt = arc.getEndPt()\n gp = QadEntityGripPoint(self.mapCanvas, endPt, QadGripPointTypeEnum.END_VERTEX, atGeom, atSubGeom, 1)\n result.append(gp)\n \n if grips == 2:\n middlePt = arc.getMiddlePt()\n gp = QadEntityGripPoint(self.mapCanvas, middlePt, QadGripPointTypeEnum.ARC_MID_POINT, atGeom, atSubGeom, 0)\n result.append(gp)\n \n return result\n\n\n def getGripPointsFromDimComponent(self, dimEntity, component):\n \"\"\"\n Ottiene una lista di punti di grip del componente di una quotatura\n \"\"\"\n result = []\n dimComponent = dimEntity.getDimComponentByEntity(component)\n if dimComponent is None:\n return result\n elif dimComponent == QadDimComponentEnum.TEXT_PT or \\\n dimComponent == QadDimComponentEnum.DIM_PT1 or \\\n dimComponent == QadDimComponentEnum.DIM_PT2:\n g = component.getGeometry()\n if g.wkbType() == QGis.WKBPoint:\n # converto il punto dal layer coordinate in map coordinates\n pt = self.mapCanvas.mapSettings().layerToMapCoordinates(self.entity.layer, g.asPoint())\n gp = QadEntityGripPoint(self.mapCanvas, pt, QadGripPointTypeEnum.VERTEX)\n result.append(gp)\n\n return result\n\n\n#===============================================================================\n# QadEntitySetGripPoints class.\n#===============================================================================\nclass QadEntitySetGripPoints(QgsMapCanvasItem):\n \"\"\"\n Classe che gestisce i punti di grip per una gruppo di selezione di entità\n \"\"\"\n \n\n #============================================================================\n # __init__\n #============================================================================\n def __init__(self, plugIn):\n self.plugIn = plugIn\n self.mapCanvas = plugIn.canvas\n self.entityGripPoints = []\n\n\n def __del__(self):\n self.removeItems()\n\n\n def removeItems(self):\n for entityGripPoint in self.entityGripPoints:\n entityGripPoint.removeItems()\n del self.entityGripPoints[:]\n\n\n def set(self, entitySet, grips = 2):\n \"\"\"\n grips = 0 Hides grips\n grips = 1 Displays grips\n grips = 2 Displays additional midpoint grips on polyline segments\n \"\"\"\n self.removeItems()\n \n if grips == 0: # nasconde i grip\n return\n\n # for each layer\n for layerEntitySet in entitySet.layerEntitySetList:\n for featureId in layerEntitySet.featureIds:\n entityGripPoints = QadEntityGripPoints(self.plugIn)\n entityGripPoints.set(layerEntitySet.layer, featureId, grips)\n self.entityGripPoints.append(entityGripPoints)\n\n\n def addEntity(self, entity, grips = 2):\n \"\"\"\n grips = 0 Hides grips\n grips = 1 Displays grips\n grips = 2 Displays additional midpoint grips on polyline segments\n \"\"\"\n if grips == 0: # nasconde i grip\n return \n if self.containsEntity(entity) == False:\n entityGripPoints = QadEntityGripPoints(self.plugIn)\n entityGripPoints.set(entity.layer, entity.featureId, grips)\n self.entityGripPoints.append(entityGripPoints)\n\n\n def hoverIntersectingGripPoints(self, point):\n res = 0\n for entityGripPoint in self.entityGripPoints:\n res = res + entityGripPoint.hoverIntersectingGripPoints(point)\n return res\n\n\n def selectIntersectingGripPoints(self, point):\n res = 0\n for entityGripPoint in self.entityGripPoints:\n res = res + entityGripPoint.selectIntersectingGripPoints(point)\n return res\n\n\n def unselectIntersectingGripPoints(self, point):\n res = 0\n for entityGripPoint in self.entityGripPoints:\n res = res + entityGripPoint.unselectIntersectingGripPoints(point)\n return res\n\n\n def toggleSelectIntersectingGripPoints(self, point):\n for entityGripPoint in self.entityGripPoints:\n entityGripPoint.toggleSelectIntersectingGripPoints(point)\n\n\n def isIntersecting(self, point):\n for entityGripPoint in self.entityGripPoints:\n res = entityGripPoint.isIntersecting(point)\n if res is not None:\n return entityGripPoint \n return None\n\n \n def getSelectedEntityGripPoints(self):\n # ritorna una lista delle entityGripPoint con dei grip point selezionati\n # la funzione non fa copie delle entityGripPoint\n result = []\n for entityGripPoint in self.entityGripPoints:\n for gripPoint in entityGripPoint.gripPoints:\n if gripPoint.getStatus() == QadGripStatusEnum.SELECTED:\n result.append(entityGripPoint)\n \n return result\n\n\n def containsEntity(self, entity):\n for entityGripPoint in self.entityGripPoints:\n if entityGripPoint.entity == entity:\n return True\n return False\n \n \n def count(self):\n return len(self.entityGripPoints)\n\n"
},
{
"alpha_fraction": 0.5294426679611206,
"alphanum_fraction": 0.5322467684745789,
"avg_line_length": 39.46808624267578,
"blob_id": "071b3c6fbd308b0cf96242ce2abcf1faf7b21983",
"content_id": "7da84b868c123e0c701d5d7e745dd7b6d1a33cbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5708,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 141,
"path": "/qad_polygon_maptool.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire il map tool in ambito del comando Ppolygon\n \n -------------------\n begin : 2014-11-17\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.gui import *\nimport math\n\n\nimport qad_utils\nfrom qad_snapper import *\nfrom qad_snappointsdisplaymanager import *\nfrom qad_variables import *\nfrom qad_getpoint import *\nfrom qad_rubberband import QadRubberBand\n\n\n#===============================================================================\n# Qad_polygon_maptool_ModeEnum class.\n#===============================================================================\nclass Qad_polygon_maptool_ModeEnum():\n # si richiede il centro\n ASK_FOR_CENTER_PT = 1 \n # noto il centro si richiede il raggio\n CENTER_PT_KNOWN_ASK_FOR_RADIUS = 2\n # si richiede il primo punto dello spigolo\n ASK_FOR_FIRST_EDGE_PT = 3\n # si richiede il secondo punto dello spigolo\n FIRST_EDGE_PT_KNOWN_ASK_FOR_SECOND_EDGE_PT = 4\n\n#===============================================================================\n# Qad_polygon_maptool class\n#===============================================================================\nclass Qad_polygon_maptool(QadGetPoint):\n \n def __init__(self, plugIn):\n QadGetPoint.__init__(self, plugIn)\n self.mode = None \n \n self.sideNumber = None\n self.centerPt = None\n self.constructionModeByCenter = None \n self.firstEdgePt = None\n self.vertices = []\n\n self.__rubberBand = QadRubberBand(self.canvas, True) \n self.geomType = QGis.Polygon\n\n def hidePointMapToolMarkers(self):\n QadGetPoint.hidePointMapToolMarkers(self)\n self.__rubberBand.hide()\n\n def showPointMapToolMarkers(self):\n QadGetPoint.showPointMapToolMarkers(self)\n self.__rubberBand.show()\n \n def clear(self):\n QadGetPoint.clear(self)\n self.__rubberBand.reset()\n self.mode = None \n \n def canvasMoveEvent(self, event):\n QadGetPoint.canvasMoveEvent(self, event)\n \n self.__rubberBand.reset()\n\n result = False\n del self.vertices[:] # svuoto la lista\n \n if self.mode is not None:\n # noto il centro si richiede il raggio\n if self.mode == Qad_polygon_maptool_ModeEnum.CENTER_PT_KNOWN_ASK_FOR_RADIUS:\n radius = qad_utils.getDistance(self.centerPt, self.tmpPoint)\n \n InscribedOption = True if self.constructionModeByCenter == QadMsg.translate(\"Command_POLYGON\", \"Inscribed in circle\") else False \n self.vertices.extend(qad_utils.getPolygonByNsidesCenterRadius(self.sideNumber, self.centerPt, radius, \\\n InscribedOption, self.tmpPoint))\n result = True\n # si richiede il secondo punto dello spigolo\n elif self.mode == Qad_polygon_maptool_ModeEnum.FIRST_EDGE_PT_KNOWN_ASK_FOR_SECOND_EDGE_PT:\n self.vertices.extend(qad_utils.getPolygonByNsidesEdgePts(self.sideNumber, self.firstEdgePt, \\\n self.tmpPoint))\n result = True\n \n if result == True: \n if self.vertices is not None:\n if self.geomType == QGis.Polygon:\n self.__rubberBand.setPolygon(self.vertices)\n else:\n self.__rubberBand.setLine(self.vertices) \n \n def activate(self):\n QadGetPoint.activate(self) \n self.__rubberBand.show()\n\n def deactivate(self):\n try: # necessario perché se si chiude QGIS parte questo evento nonostante non ci sia più l'oggetto maptool !\n QadGetPoint.deactivate(self)\n self.__rubberBand.hide()\n except:\n pass\n\n def setMode(self, mode):\n self.mode = mode\n # si richiede il centro\n if self.mode == Qad_polygon_maptool_ModeEnum.ASK_FOR_CENTER_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # noto il centro si richiede il raggio\n if self.mode == Qad_polygon_maptool_ModeEnum.CENTER_PT_KNOWN_ASK_FOR_RADIUS: \n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.centerPt)\n # si richiede il primo punto dello spigolo\n if self.mode == Qad_polygon_maptool_ModeEnum.ASK_FOR_FIRST_EDGE_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.NONE)\n # si richiede il secondo punto dello spigolo\n if self.mode == Qad_polygon_maptool_ModeEnum.FIRST_EDGE_PT_KNOWN_ASK_FOR_SECOND_EDGE_PT:\n self.setDrawMode(QadGetPointDrawModeEnum.ELASTIC_LINE)\n self.setStartPoint(self.firstEdgePt)\n"
},
{
"alpha_fraction": 0.7207578420639038,
"alphanum_fraction": 0.7364085912704468,
"avg_line_length": 40.86206817626953,
"blob_id": "24687932f091d81dd32811e10274e699394dbb43",
"content_id": "b4b32181bd1e638fec79ada4bc8fd58297f9578e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1214,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 29,
"path": "/help/help_en/3_Workphilosophy.htm",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n<head>\n<meta name=\"generator\" content=\n\"HTML Tidy for Windows (vers 25 March 2009), see www.w3.org\">\n<meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\">\n<meta name=\"Generator\" content=\"Microsoft Word 14 (filtered)\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"embeddedstyles.css\">\n<title>Work philosophy</title>\n<meta name=\"generator\" content=\"chmProcessor\">\n</head>\n<body lang=\"IT\">\n<div class=\"WordSection1\">\n<h2><a name=\"node2\" id=\"node2\"></a><span lang=\"EN\">Work\nphilosophy</span></h2>\n<p class=\"MsoNormal\"><span lang=\"EN\">QAD has a different logic by\nQGIS and closer to popular CAD software.</span></p>\n<p class=\"MsoNormal\"><span lang=\"EN\">To reduce learning time, QAD\nis inspired to the most popular CAD. This manual assumes that you\nhave already the knowledge of the most popular CAD environment and\ncommands. Otherwise use the appropriate documentation (there is a\nlarge amount of manuals) or search the command on\ninternet.</span></p>\n<p class=\"MsoNormal\"><span lang=\"EN\">The current reference system\nof the project must be a projected coordinate system and not a\ngeographic system.</span></p>\n</div>\n</body>\n</html>\n"
},
{
"alpha_fraction": 0.5629863739013672,
"alphanum_fraction": 0.5661478638648987,
"avg_line_length": 39.71287155151367,
"blob_id": "58a4912fa8c9924b7cc37def03a604709ef4983f",
"content_id": "de701eab0ffc20b5a65b285b97b4d6dd9d623d14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4112,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 101,
"path": "/qad_dimstyle_new_dlg.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire la dialog per DIMSTYLE\n \n -------------------\n begin : 2015-05-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\nfrom qgis.utils import *\n\nimport qad_dimstyle_new_ui\nfrom qad_dimstyle_details_dlg import QadDIMSTYLE_DETAILS_Dialog\n\nfrom qad_variables import *\nfrom qad_dim import *\nfrom qad_msg import QadMsg, qadShowPluginHelp\nimport qad_utils\n\n\n#######################################################################################\n# Classe che gestisce l'interfaccia grafica della funzione di creazione nuovo stile\nclass QadDIMSTYLE_NEW_Dialog(QDialog, QObject, qad_dimstyle_new_ui.Ui_DimStyle_New_Dialog):\n def __init__(self, plugIn, fromDimStyleName = None):\n self.plugIn = plugIn\n self.iface = self.plugIn.iface.mainWindow()\n QDialog.__init__(self, self.iface)\n \n self.newDimStyle = QadDimStyle()\n self.newDimStyleNameChanged = False\n \n self.setupUi(self)\n \n self.dimNameList = []\n for dimStyle in QadDimStyles.dimStyleList: # lista degli stili di quotatura caricati\n self.DimStyleNameFrom.addItem(dimStyle.name, dimStyle)\n self.dimNameList.append(dimStyle.name)\n \n # sort\n self.DimStyleNameFrom.model().sort(0)\n\n # seleziono un elemento della lista\n if fromDimStyleName is not None:\n index = self.DimStyleNameFrom.findText(fromDimStyleName)\n self.DimStyleNameFrom.setCurrentIndex(index)\n self.DimStyleNameFromChanged(index)\n \n def DimStyleNameFromChanged(self, index):\n # leggo l'elemento selezionato\n dimStyle = self.DimStyleNameFrom.itemData(index)\n if dimStyle is not None:\n self.newDimStyle.set(dimStyle)\n if self.newDimStyleNameChanged == False:\n newName = qad_utils.checkUniqueNewName(dimStyle.name, self.dimNameList, QadMsg.translate(\"QAD\", \"Copy of \"))\n if newName is not None:\n self.newDimStyleName.setText(newName)\n\n def newStyleNameChanged(self, text):\n self.newDimStyleNameChanged = True\n \n def ButtonBOX_continue(self):\n if self.newDimStyleName.text() in self.dimNameList:\n QMessageBox.critical(self, QadMsg.translate(\"QAD\", \"QAD\"), \\\n QadMsg.translate(\"DimStyle_Dialog\", \"Dimension style name already existing. Specify a different name.\"))\n return False\n self.newDimStyle.name = self.newDimStyleName.text()\n self.newDimStyle.description = self.newDimStyleDescr.text()\n Form = QadDIMSTYLE_DETAILS_Dialog(self.plugIn, self.newDimStyle)\n title = QadMsg.translate(\"DimStyle_Dialog\", \"New dimension style: \") + self.newDimStyle.name\n Form.setWindowTitle(title)\n \n if Form.exec_() == QDialog.Accepted:\n self.dimStyle = Form.dimStyle\n QDialog.accept(self)\n else:\n self.dimStyle = None\n QDialog.reject(self) \n\n def ButtonHELP_Pressed(self):\n qadShowPluginHelp(QadMsg.translate(\"Help\", \"Dimensioning\"))\n"
},
{
"alpha_fraction": 0.5925443768501282,
"alphanum_fraction": 0.6078106760978699,
"avg_line_length": 37.91244125366211,
"blob_id": "1a032372928247043de649f16be1b8d4bf1e151c",
"content_id": "22f6356dac5e3eddf6c20db7abb871fc866ec398",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8450,
"license_type": "no_license",
"max_line_length": 119,
"num_lines": 217,
"path": "/qad_dimstyle_diff_dlg.py",
"repo_name": "resistor4u/QAD",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\n QAD Quantum Aided Design plugin\n\n classe per gestire la dialog per DIMSTYLE\n \n -------------------\n begin : 2015-05-19\n copyright : iiiii\n email : hhhhh\n developers : bbbbb aaaaa ggggg\n ***************************************************************************/\n\n/***************************************************************************\n * *\n * This program 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 2 of the License, or *\n * (at your option) any later version. *\n * *\n ***************************************************************************/\n\"\"\"\n\n\n# Import the PyQt and QGIS libraries\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom qgis.core import *\nfrom qgis.core import QgsApplication\nfrom qgis.utils import *\n\nimport qad_dimstyle_diff_ui\n\nfrom qad_dim import *\nfrom qad_msg import QadMsg, qadShowPluginHelp\nimport qad_utils\n\n\n#######################################################################################\n# Classe che gestisce l'interfaccia grafica della funzione di comparazione tra stili di quotatura\nclass QadDIMSTYLE_DIFF_Dialog(QDialog, QObject, qad_dimstyle_diff_ui.Ui_DimStyle_Diff_Dialog):\n def __init__(self, plugIn, dimStyleName1 = None, dimStyleName2 = None):\n self.plugIn = plugIn\n self.iface = self.plugIn.iface.mainWindow()\n QDialog.__init__(self, self.iface)\n \n self.setupUi(self)\n \n self.dimNameList = []\n for dimStyle in QadDimStyles.dimStyleList: # lista degli stili di quotatura caricati\n self.dimStyle1.addItem(dimStyle.name, dimStyle)\n self.dimStyle2.addItem(dimStyle.name, dimStyle)\n \n # sort\n self.dimStyle1.model().sort(0)\n self.dimStyle2.model().sort(0)\n\n # seleziono un elemento della lista\n if dimStyleName1 is not None:\n index = self.dimStyle1.findText(dimStyleName1)\n self.dimStyle1.setCurrentIndex(index)\n else:\n self.dimStyle1.setCurrentIndex(0)\n \n # seleziono un elemento della lista\n if dimStyleName2 is not None:\n index = self.dimStyle2.findText(dimStyleName2)\n self.dimStyle2.setCurrentIndex(index)\n self.DimStyleName2Changed(index)\n else:\n self.dimStyle2.setCurrentIndex(0)\n \n def DimStyleName1Changed(self, index):\n # leggo l'elemento selezionato\n dimStyle1 = self.dimStyle1.itemData(index)\n index = self.dimStyle2.currentIndex()\n dimStyle2 = self.dimStyle2.itemData(index) if index >= 0 else None\n self.showProps(dimStyle1, dimStyle2)\n\n def DimStyleName2Changed(self, index):\n # leggo l'elemento selezionato\n dimStyle2 = self.dimStyle2.itemData(index)\n index = self.dimStyle1.currentIndex()\n dimStyle1 = self.dimStyle1.itemData(index) if index >= 0 else None\n self.showProps(dimStyle1, dimStyle2)\n\n def showProps(self, dimStyle1, dimStyle2):\n self.tableWidget.clear()\n if dimStyle1 is None:\n return\n \n if dimStyle2 is None or dimStyle1.name == dimStyle2.name:\n self.showAllProps(dimStyle1)\n else: \n self.showDiffProps(dimStyle1, dimStyle2)\n \n def showAllProps(self, dimStyle):\n if self.tableWidget.model() is not None:\n # Pulisce la tabella\n self.tableWidget.model().reset()\n self.tableWidget.setRowCount(0)\n \n self.tableWidget.setColumnCount(2)\n headerLabels = []\n headerLabels.append(QadMsg.translate(\"DimStyle_Diff_Dialog\", \"Description\"))\n headerLabels.append(dimStyle.name)\n self.tableWidget.setHorizontalHeaderLabels(headerLabels)\n self.tableWidget.horizontalHeader().show()\n\n self.count = 0\n propsDict = dimStyle.getPropList().items()\n for prop in propsDict:\n propName = prop[0]\n propDescr = prop[1][0]\n propValue = prop[1][1]\n self.insertProp(propDescr, propValue)\n\n self.tableWidget.sortItems(0)\n\n self.tableWidget.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)\n self.tableWidget.horizontalHeader().setResizeMode(1, QHeaderView.Interactive)\n \n self.msg.setText(QadMsg.translate(\"DimStyle_Diff_Dialog\", \"All properties of dimension style: \") + dimStyle.name)\n\n\n def showDiffProps(self, dimStyle1, dimStyle2):\n if self.tableWidget.model() is not None:\n # Pulisce la tabella\n self.tableWidget.model().reset()\n self.tableWidget.setRowCount(0)\n \n self.tableWidget.setColumnCount(3)\n headerLabels = []\n headerLabels.append(QadMsg.translate(\"DimStyle_Diff_Dialog\", \"Description\"))\n headerLabels.append(dimStyle1.name)\n headerLabels.append(dimStyle2.name)\n self.tableWidget.setHorizontalHeaderLabels(headerLabels)\n self.tableWidget.horizontalHeader().show()\n\n self.count = 0\n prop1Items = dimStyle1.getPropList().items() # lista di nome con lista [descrizione, valore]\n props2Dict = dimStyle2.getPropList() # dizionario di nome con lista [descrizione, valore]\n for prop1 in prop1Items:\n propName = prop1[0]\n propDescr = prop1[1][0]\n prop1Value = prop1[1][1]\n prop2 = props2Dict[propName]\n prop2Value = prop2[1]\n if prop1Value is None:\n prop1Value = \"\"\n if prop2Value is None:\n prop2Value = \"\"\n if unicode(prop1Value) != unicode(prop2Value):\n self.insertProp(propDescr, prop1Value, prop2Value)\n\n self.tableWidget.sortItems(0)\n\n self.tableWidget.horizontalHeader().setResizeMode(0, QHeaderView.ResizeToContents)\n self.tableWidget.horizontalHeader().setResizeMode(2, QHeaderView.Interactive)\n self.tableWidget.horizontalHeader().setResizeMode(3, QHeaderView.Interactive)\n \n self.msg.setText(QadMsg.translate(\"DimStyle_Diff_Dialog\", \"Found {0} differences: \").format(str(self.count)))\n\n\n def insertProp(self, description, val1, val2 = None):\n self.tableWidget.insertRow(self.count)\n \n item = QTableWidgetItem(unicode(description))\n item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n self.tableWidget.setItem(self.count, 0, item)\n \n item = QTableWidgetItem(unicode(val1))\n item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n self.tableWidget.setItem(self.count, 1, item)\n \n if val2 is not None:\n item = QTableWidgetItem(unicode(val2))\n item.setFlags(Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsSelectable)\n self.tableWidget.setItem(self.count, 2, item)\n self.count += 1\n \n \n def ButtonHELP_Pressed(self):\n qadShowPluginHelp(QadMsg.translate(\"Help\", \"Dimensioning\"))\n\n def resizeEvent(self, event):\n QDialog.resizeEvent(self, event)\n if event.oldSize().width() == -1: # non c'era una dimensione precedente\n return\n tableWidgetSize = self.tableWidget.size()\n newWidth = tableWidgetSize.width() + event.size().width() - event.oldSize().width()\n newHeight = tableWidgetSize.height() + event.size().height() - event.oldSize().height()\n tableWidgetSize.setWidth(newWidth)\n tableWidgetSize.setHeight(newHeight) \n self.tableWidget.resize(tableWidgetSize)\n \n \n def copyToClipboard(self):\n buffer = \"\"\n \n # intestazione\n for col in xrange(0, self.tableWidget.columnCount(), 1):\n if col > 0:\n buffer += '\\t' # aggiungo un TAB\n buffer += self.tableWidget.horizontalHeaderItem(col).text()\n buffer += '\\n' # vado a capo\n \n # valori delle righe\n for row in xrange(0, self.tableWidget.rowCount(), 1):\n for col in xrange(0, self.tableWidget.columnCount(), 1):\n if col > 0:\n buffer += '\\t' # aggiungo un TAB\n buffer += self.tableWidget.item(row, col).text()\n buffer += '\\n' # vado a capo\n\n QApplication.clipboard().setText(buffer)\n "
}
] | 54 |
asshu1763/air_quality
|
https://github.com/asshu1763/air_quality
|
92c78f00eb1b892f86faee1776163a23ac2df3e9
|
6ac8376b3a26fe02230f5b63669dd18865ee59d9
|
a574ab4b3ab094a2870b523ef0b176d9c52ce486
|
refs/heads/master
| 2023-05-13T03:26:53.958011 | 2021-05-23T13:35:42 | 2021-05-23T13:35:42 | 370,037,938 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.585561215877533,
"alphanum_fraction": 0.6314062476158142,
"avg_line_length": 20.310699462890625,
"blob_id": "35b9563e0ffbe4026642d7e7f6f218a26f71572b",
"content_id": "ed0a908216d7ee38bb25d0471cb7c96f9ad9cfc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10361,
"license_type": "no_license",
"max_line_length": 170,
"num_lines": 486,
"path": "/model.py",
"repo_name": "asshu1763/air_quality",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\n# # AIR QUALITY PREDICTION FOR SMART CITIES USING MACHINE LEARNING\n\n# # DATA COLLECTION\n\n# In[4]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nfrom datetime import datetime\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n# In[5]:\n\n\ncity = pd.read_csv('new.csv')\ncity.drop(['AQI_Bucket'],axis=1,inplace=True)\n\n\n# In[6]:\n\n\ncity.describe().T\n\n\n# In[7]:\n\n\ncity.info()\n\n\n# In[8]:\n\n\ncity=city.fillna(0)\n\n\n# # Checking for Missing Values in the data\n# \n\n# In[9]:\n\n\ndef getMissingValues(data):\n missing_val = data.isnull().sum()\n missing_val_percentage = 100 * data.isnull().sum() / len(data)\n missin_values_array = pd.concat([missing_val, missing_val_percentage], axis=1)\n missin_values_array = missin_values_array.rename(columns = \n {0 : 'Missing Values', 1 : '% of Total Values'})\n missin_values_array = missin_values_array[\n missin_values_array.iloc[:,1] != 0].sort_values('% of Total Values', ascending=False).round(1)\n return missin_values_array\n\n\n# In[10]:\n\n\ndef mergeColumns(data):\n data['Date'] = pd.to_datetime(data['Date'])\n data['BTX'] = data['Benzene'] + data['Toluene'] + data['Xylene']\n data.drop(['Benzene','Toluene','Xylene'], axis=1)\n data['Particulate_Matter'] = data['PM2.5'] + data['PM10']\n return data\n\n\n# In[11]:\n\n\ndef subsetColumns(data):\n pollutants = ['Particulate_Matter', 'NO2', 'CO','SO2', 'O3', 'BTX']\n columns = ['Date', 'City', 'AQI'] + pollutants\n data = data[columns]\n return data, pollutants\n\n\n# In[12]:\n\n\ndef handleMissingValues(data):\n missing_values = getMissingValues(data)\n updatedCityData = mergeColumns(data)\n updatedCityData, pollutants = subsetColumns(updatedCityData)\n return updatedCityData, pollutants\n\n\n# In[13]:\n\n\nupdatedCityData, newColumns = handleMissingValues(city)\n\n\n# In[14]:\n\n\nupdatedCityData.fillna(0)\n\n\n# In[15]:\n\n\ndef visualisePollutants(udata, columns):\n data = udata.copy()\n data.set_index('Date',inplace=True)\n axes = data[columns].plot(marker='.', linestyle='None', figsize=(15, 15), subplots=True)\n for ax in axes:\n ax.set_xlabel('Years')\n ax.set_ylabel('ug/m3')\n\n\n# In[16]:\n\n\nvisualisePollutants(city, newColumns)\n\n\n# In[17]:\n\n\nupdatedCityData.groupby('City')[['Particulate_Matter','NO2','CO','SO2','O3','BTX']].mean()\n\n\n# # CALCULATION OF AQI INDEX BASED ON THE POLLUTANT LEVELS\n\n# In[18]:\n\n\ndef cal_aqi(SO2,NO2,Particulate_Matter,CO,O3,BTX):\n aqi=0\n if(SO2>NO2 and SO2>Particulate_Matter and SO2>CO and SO2>O3 and SO2>BTX):\n aqi=SO2\n if(NO2>SO2 and NO2>Particulate_Matter and NO2>CO and NO2>O3 and NO2>BTX):\n aqi=NO2\n if(Particulate_Matter>SO2 and Particulate_Matter>NO2 and Particulate_Matter>CO and Particulate_Matter>O3 and Particulate_Matter>BTX ):\n aqi=Particulate_Matter\n if(CO>SO2 and CO>NO2 and CO>Particulate_Matter and CO>O3 and CO>BTX):\n aqi=CO\n if(O3>SO2 and O3>NO2 and O3>Particulate_Matter and O3>CO and O3>BTX):\n aqi=O3\n if(BTX>SO2 and BTX>NO2 and BTX>Particulate_Matter and BTX>O3 and BTX>CO):\n aqi=BTX\n return aqi\n\nupdatedCityData['AQI_INDEX']=updatedCityData.apply(lambda x:cal_aqi(x['SO2'],x['NO2'],x['Particulate_Matter'],x['CO'],x['O3'],x['BTX']),axis=1)\ncity_data=updatedCityData[['City','Date','SO2','NO2','Particulate_Matter','CO','O3','BTX','AQI_INDEX']]\ncity_data\n\n\n# # CALCULATION OF AQI_RANGE BASED ON THE AQI INDEX\n\n# In[19]:\n\n\ndef AQI_Range(x):\n if x<=50:\n return \"Good\"\n elif x>50 and x<=100:\n return \"Moderate\"\n elif x>100 and x<=150:\n return \"Unhealthy for Kids\"\n elif x>150 and x<=200:\n return \"Unhealthy\"\n elif x>200 and x<=300: #what is SPMI an dRSPMI SOI why do we need it what is AQI and itsrange\n return \"Very Unhealthy\"\n elif x>300:\n return \"Hazardous\"\n\ncity_data['AQI_RANGE'] = city_data['AQI_INDEX'] .apply(AQI_Range)\ncity_data.head(150)\n\n\n# # Effect of Lockdown on AQI\n# \n\n# # a. AQI in the year 2020 - City-wise\n\n# In[20]:\n\n\ncities = ['Delhi','Lucknow','Bengaluru','Hyderabad']\nfiltered_city_day = city_data[city_data['Date'] <= '2020-12-31']\nAQI_INDEX = filtered_city_day[filtered_city_day.City.isin(cities)][['Date','City','AQI_INDEX','AQI_RANGE']]\n\n\n# In[21]:\n\n\nAQI_pivot = AQI_INDEX.pivot(index='Date', columns='City', values='AQI_INDEX')\nAQI_pivot.fillna(method='bfill',inplace=True)\n\n\n# In[22]:\n\n\nAQI_2020 = AQI_pivot[AQI_pivot.index <'2020-12-31']\nAQI_2020 = AQI_2020.resample('M').mean()\n# AQI_2020.set_index('Date')\n# aqi = aqi.to_numpy()\n\ndef getColorBar(city):\n col = []\n for val in AQI_2020[city]:\n if val < 50:\n col.append('royalblue')\n elif val > 50 and val < 101:\n col.append('lightskyblue') #cornflowerblue\n elif val > 100 and val < 201:\n col.append('lightsteelblue')\n elif val > 200 and val < 301:\n col.append('peachpuff')\n elif val > 300 and val < 401:\n col.append('lightcoral')\n else:\n col.append('firebrick')\n return col\n\nfor i in range(0, 4, 2):\n city_1 = cities[i]\n city_2 = cities[i+1]\n fig, ((ax1, ax2)) = plt.subplots(1, 2, sharex='col', sharey='row', figsize=(15,3))\n# ax = fig.add_axes([0,0,1,1])\n ax1.bar(AQI_2020.index, AQI_2020[city_1], width = 25, color=getColorBar(city_1))\n ax1.title.set_text(city_1)\n ax1.set_ylabel('AQI_INDEX')\n \n colors = {'Good':'royalblue', 'Satisfactory':'lightskyblue', 'Moderate':'lightsteelblue', 'Poor':'peachpuff', 'Very Poor':'lightcoral', 'Severe':'firebrick'} \n labels = list(colors.keys())\n handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]\n ax1.legend(handles, labels, loc='upper right')\n \n ax2.bar(AQI_2020.index, AQI_2020[city_2], width = 25, color=getColorBar(city_2))\n ax2.title.set_text(city_2)\n ax2.set_ylabel('AQI_INDEX')\n colors = {'Good':'royalblue', 'Satisfactory':'lightskyblue', 'Moderate':'lightsteelblue', 'Poor':'peachpuff', 'Very Poor':'lightcoral', 'Severe':'firebrick'} \n labels = list(colors.keys())\n handles = [plt.Rectangle((0,0),1,1, color=colors[label]) for label in labels]\n ax2.legend(handles, labels, loc='upper right')\n \n\n\n# # b.AQI before and after LOCKDOWN\n\n# In[23]:\n\n\nAQI_beforeLockdown = AQI_pivot['2015-01-01':'2020-03-25']\nAQI_afterLockdown = AQI_pivot['2020-03-26':'2020-05-01']\nlimits = [50, 100, 200, 300, 400, 510]\n# palette = sns.light_palette(\"Spectral\", len(limits), reverse = True)\npalette = sns.color_palette(\"coolwarm\", len(limits))\nfor city in cities:\n aqi_before = AQI_beforeLockdown[city].mean()\n aqi_after = AQI_afterLockdown[city].mean()\n fig, (ax1, ax2) = plt.subplots(1,2,figsize=(27, 2))\n ax1.set_yticks([1])\n ax1.set_yticklabels([city])\n ax1.spines['bottom'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.spines['right'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n\n prev_limit = 0\n for idx, lim in enumerate(limits):\n ax1.barh([1], lim-prev_limit, left=prev_limit, height=15, color=palette[idx])\n prev_limit = lim\n\n ax1.barh([1], aqi_before, color='black', height=5)\n \n # after lockdown\n ax2.set_yticks([1])\n ax2.set_yticklabels([city])\n ax2.spines['bottom'].set_visible(False)\n ax2.spines['top'].set_visible(False)\n ax2.spines['right'].set_visible(False)\n ax2.spines['left'].set_visible(False)\n\n prev_limit = 0\n for idx, lim in enumerate(limits):\n ax2.barh([1], lim-prev_limit, left=prev_limit, height=15, color=palette[idx])\n prev_limit = lim\n\n ax2.barh([1], aqi_after, color='black', height=5)\n \n ax1.set_title('Before Lockdown')\n ax2.set_title('After Lockdown')\n \n rects = ax1.patches\n labels=[\"Good\", \"Satisfactory\", \"Moderate\", \"Poor\", 'Very Poor', 'Severe']\n \n for rect, label in zip(rects, labels):\n height = rect.get_height()\n ax1.text(\n rect.get_x() + rect.get_width()/2 ,\n -height * .4,\n label,\n ha='center',\n va='bottom',\n color='black')\n ax2.text(\n rect.get_x() + rect.get_width() / 2,\n -height * .7,\n label,\n ha='center',\n va='bottom',\n color='black')\n\n\n# # Perform Feature Scaling using Min-Max Scaler\n# Min-Max Scaling Feature for normalizing the data to a range of (a-b)\n# \n\n# In[24]:\n\n\nindep_var=city_data[['SO2','NO2','Particulate_Matter','CO','O3','BTX']]\ndepend_var= city_data['AQI_RANGE']\n\n\n# In[25]:\n\n\nfrom sklearn.preprocessing import MinMaxScaler\nscale1=MinMaxScaler()\nXminmax=scale1.fit_transform(indep_var)\nXminmax\n\n\n# # PREDICTION OF AIR QUALITY USING SVM,KNN,RANDOM FOREST ALGORITHM\n\n# # RANDOM FOREST ALGORITHM\n\n# In[26]:\n\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# In[27]:\n\n\nX_train, X_test, y_train, y_test = train_test_split(indep_var,depend_var, test_size=0.33, random_state=42)\n\n\n# In[28]:\n\n\nX_train\n\n\n# In[29]:\n\n\ny_train\n\n\n# In[30]:\n\n\nmodel1 = RandomForestClassifier()\nmodel1.fit(X_train,y_train)\n\n\n# In[31]:\n\n\nprediction = model1.predict(X_test)\nprediction\n\n\n# In[32]:\n\n\nmodel1.score(X_test,y_test)\n\n\n# In[33]:\n\n\nresult=model1.predict([[123,45.6,56,78.9,44,9.5]])\nresult\n\n\n# # SVM (SUPPORT VECTOR MACHINE) ALGORITHM\n\n# In[34]:\n\n\nfrom sklearn.svm import SVC\n\n\n# In[35]:\n\n\nmodel3=SVC(kernel=\"rbf\",random_state=0)\n\n\n# In[36]:\n\n\nmodel3.fit(X_train,y_train)\n\n\n# In[37]:\n\n\nmodel3.score(X_test,y_test)\n\n\n# In[38]:\n\n\nmodel3.predict([[1.9,5.3,33.3,1.45,7.6,15]])\n\n\n# # KNN (K-NEAREST NEIGHBOURS) ALGORITHM\n\n# In[39]:\n\n\nfrom sklearn.neighbors import KNeighborsClassifier\nmodel2=KNeighborsClassifier()\n\n\n# In[40]:\n\n\nmodel2.fit(X_train,y_train)\n\n\n# In[41]:\n\n\nmodel2.score(X_test,y_test)\n\n\n# In[42]:\n\n\nanswer = model2.predict([[96.8,31.2,541,205,4.1,7.25]])\n\n\n# In[43]:\n\n\nprint(\"The air quality is {}\".format(answer[0]))\n\n\n# In[ ]:\n\n\n\n\n\n# In[44]:\n\n\nimport pickle\n\nfile = open('majorproject.pkl', 'wb')\n\npickle.dump(model1, file)\n\n\n# In[45]:\n\n\nX_test\n\n\n# In[46]:\n\n\nX_test.columns\n\n\n# In[ ]:\n\n\n\n\n"
},
{
"alpha_fraction": 0.6353591084480286,
"alphanum_fraction": 0.6454880237579346,
"avg_line_length": 30.909090042114258,
"blob_id": "52bd7f9769c18116737f2b1d30c3aa1955000068",
"content_id": "b47901579950094e26fb2abbfa1950e8415382fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1086,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 33,
"path": "/app.py",
"repo_name": "asshu1763/air_quality",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request\r\nimport jsonify\r\nimport requests\r\nimport pickle\r\nimport numpy as np\r\nimport sklearn\r\nfrom sklearn.preprocessing import StandardScaler\r\napp = Flask(__name__)\r\nmodel = pickle.load(open('majorproject.pkl', 'rb'))\r\[email protected]('/',methods=['GET'])\r\ndef Home():\r\n return render_template('index.html')\r\n\r\n\r\nstandard_to = StandardScaler()\r\[email protected](\"/predict\", methods=['POST'])\r\ndef predict():\r\n Fuel_Type_Diesel=0\r\n if request.method == 'POST':\r\n SO2 = float(request.form['SO2'])\r\n NO2=float(request.form['NO2'])\r\n Particulate_Matter=float(request.form['Particulate_Matter'])\r\n CO=float(request.form['CO'])\r\n O3=float(request.form['O3'])\r\n BTX=float(request.form['BTX'])\r\n prediction=model.predict([[SO2,NO2,Particulate_Matter,CO,O3,BTX]])\r\n output=prediction\r\n return render_template('index.html',prediction_text=\"The Air Quality is {}\".format(output[0]))\r\n else:\r\n return render_template('index.html')\r\n\r\nif __name__==\"__main__\":\r\n app.run(debug=True)\r\n"
}
] | 2 |
DDMAL/xml-parse-glyph-img
|
https://github.com/DDMAL/xml-parse-glyph-img
|
51ecd33812367fbb4ad96a9e31723bcacd057cc8
|
bcb80526c6ba3e16b709105d5e283f0e6fd51b64
|
8054ca3461462697873529d8d4414740128f4344
|
refs/heads/main
| 2021-06-12T15:19:03.294375 | 2021-04-28T10:27:52 | 2021-04-28T10:27:52 | 186,055,303 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.755620002746582,
"alphanum_fraction": 0.7645032405853271,
"avg_line_length": 148.05404663085938,
"blob_id": "fe7f84497f76047cfc24c3fd314df9e1e83367ba",
"content_id": "9b1435dffa203202d132088c88688ea0ed413a23",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5516,
"license_type": "permissive",
"max_line_length": 709,
"num_lines": 37,
"path": "/README.md",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "# XML Parser to Dataset Image Extraction\n\nThis repository is being used to extract individual images of neumes and neume components in a staff. The images will then be passed into a model for training simultaneously on neume and pitch classification. Model training will be performed in another repository: omr-position-classification.\n\n## Current Worklow\n\nThe *Interactive Classifier* job on Rodan is useful for quickly adding labels to neumes and neume components. It is usually used to manually classify a few neume types and automatically assess the rest based on a deep learning process. For the dataset extraction envisioned in this repository, I am using the *Interactive Classifier* to instead classify on neume position. The model cannot classify neume position automatically, though the workflow will be extended in the future to encompass automatic pitch classification and encode it in an xml format. I delete any glyphs that are not neumes, but are caught by the classifier. \n\nAfter exporting the xml file containing all the neume coordinates and position labels, I use a python script **bounding-box-extraction.py** to parse the xml file and save individual images of each neume component from the original image of the manuscript page. Y-coordinates are extended above and below the original bounding box to encapsulate a portion of the staff lines found around the neume. Then, each image is interpolated and resized to 30 x 120 pixels for standardization purposes in the dataset. Below are a few examples of images found in the dataset.\n\ns5 | s1 | s3 | l4\n:----------------------------:|:----------------------------:|:----------------------------:|:----------------------------:\n | ||\n\nThe tags above each image correspond to their position classification in the staff. There are nine possible positions (4 lines, 5 spaces) for neume components in square notation, designated by the classification set: \n\n[l1, l2, l3, l4, s1, s2, s3, s4, s5]\n\nThe third image, featuring a *podatus*, is classified by the position that the lower neume component is in, hence 's3.' The *oblique* in the fourth image is classified by its starting position on 'l4.' \n\nFor each image, the neume component is centered, leaving parts of the staff lines out in extreme position cases such as 's1' and 's5.' This is intentional, as the model should be robust enough to handle more difficult corner cases of classification. Even though some staff lines are missing, one can still usually assess which position the neume is in, and the model is likely able to as well with enough examples provided. \n\nThe CLI from **bounding-box-extraction.py** asks for a training or testing dataset output, making it convenient for data organization. Another simple script, **zip-datasets.py**, does what the title suggests. Datasets are uploaded to Google Colabs for testing and training, and it is expected in a zip file format. \n\nFinally, I wrote the **remove-data.py** script which allows the user to specify whether they want to clean the training, testing, or all data in one go. The three scripts mentioned are used in coordination with one another to iterate through different training and testing scenarios for the data. \n\n## {Deprecated Workflow}\n\nInitially, I am taking an image of a score with the staves isolated (no lyrics or neumes), and I am passing it into the Rodan \"Miyao Staff Finding\" workflow to receive the bounding boxes for each stave on the page. The file is output as a JSOMR file, and I am currently using <https://codebeautify.org/jsontoxml> to convert it to XML since the JSOMR2MEI job on rodan is not generalized to files that do not have \"glyph\" tags. I realize JSOMR can also be parsed, MEI is more standardized in our general software programs. All of the current MEI (XML) information on the Salzinnes pages is included in this repository using the method described.\n\nNext, **stave-parser.py** asks for a numerical input from the Salzinnes images (10-18) to use for stave isolation. Using the XML coordinates from above, the respective page is split into images of each of the individual staves. Additionally, the same cooridnates are used to extract bounding boxes of the staves from the isolated layers of the Salzinnes pages, particularly the glyphs and staves layers. Respectively, these splits are saved in three folders not included in the repo due to size concerns:\n\n* stave_boxes (full color image from original size to individual stave)\n* stave_boxes_glyphs (same size as stave boxes, only glyphs in image)\n* stave_boxes_lines (same size as stave boxes, only respective stave in image)\n\n**image-extraction.py** is then used to extract the images of each individual neume and neume component in the staff. Taking a few user input parameters, you specify which staff to parse, and a few parameters pertaining to erosion and line finding processes using the opencv library. Erosion is used on a greyscale of the original stave image, reducing the now whitespace of each neume to a point where neume components are consistently (little errors) isolated from one another successfully, allowing for their coordinates to be used for writing images of their position in the original image. Each image is also resized to the same dimensions with the intention of passing them into the model down the road. \n"
},
{
"alpha_fraction": 0.4859437644481659,
"alphanum_fraction": 0.5118250846862793,
"avg_line_length": 35.1370964050293,
"blob_id": "116346424eaa5347940f8ab686b8dcf45eb6110e",
"content_id": "589a386ab20f95e4dafbab908115760f7c555084",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4482,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 124,
"path": "/stave-parser.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "\nimport numpy as np\nimport cv2\nimport xml.etree.ElementTree as ET\nimport os\n\n# ------------------------------------------------------------------------------\n\nprint('Which manuscript (CF or Ein) should be considered:')\nmanu = input().strip()\n\nif manu == 'CF':\n print('Which Calvo file number (09-20, 24-27 currently) should be parsed: ')\nelif manu == 'Ein':\n print('Which Ein file number (01v-05v, 02r-05r currently) should be parsed: ')\nelse:\n print('Please try again.')\n exit()\n\nfile = input().strip()\n\n# ------------------------------------------------------------------------------\n\nimg = cv2.imread(f'./originals/{ manu }/{ manu }-0{ file }.png', 1)\nimg_line = cv2.imread(f'./layer/{ manu }/{ manu }-0{ file }/{ manu }-0{ file }_2.png')\nimg_glyphs = cv2.imread(f'./layer/{ manu }/{ manu }-0{ file }/{ manu }-0{ file }_1.png')\n\nif img is not None:\n os.system('rm -f ./stave_boxes/*')\n os.system('rm -f ./stave_boxes_glyphs/*')\n os.system('rm -f ./stave_boxes_lines/*')\n\nif not os.path.isdir('./stave_boxes'):\n os.system('mkdir stave_boxes')\nif not os.path.isdir('./stave_boxes_lines'):\n os.system('mkdir stave_boxes_lines')\nif not os.path.isdir('./stave_boxes_glyphs'):\n os.system('mkdir stave_boxes_glyphs')\n\n# ------------------------------------------------------------------------------\n\ndef parse_xml(manuscript, file):\n stave_coords = []\n stave_tree = ET.parse(f'./xml/{ manu }/{ manu }-0{ file }-stave.xml')\n stave_root = stave_tree.getroot()\n for stave in stave_root.findall('staves'):\n bounding_box = stave.find('bounding_box')\n stave_coords.append([\n 0,\n int(bounding_box.find('uly').text),\n int(bounding_box.find('nrows').text),\n int(bounding_box.find('ulx').text),\n int(bounding_box.find('ncols').text)\n ])\n stave_coords = np.array(stave_coords)\n stave_coords = stave_coords[np.argsort(stave_coords[:,1])]\n return stave_coords\n\n\ndef get_final_coordinates(stave_coordinates):\n x_start = 10**20\n x_end = 0\n index = 0\n final_coordinates = []\n # Loop for numbering stave fractions into the same vertical orientation\n for y_dim in stave_coordinates:\n print(y_dim[0])\n if y_dim[3] < x_start:\n x_start = y_dim[3]\n if y_dim[3] + y_dim[4] > x_end:\n x_end = y_dim[3] + y_dim[4]\n if y_dim[0] == 0:\n y_dim[0] = index + 1\n for y_dim_next in stave_coordinates[index+1:]:\n if y_dim[1] <= y_dim_next[1] <= y_dim[1] + y_dim[2]:\n y_dim_next[0] = index + 1\n index += 1\n print(stave_coords)\n index = 1\n for dim in stave_coordinates:\n if dim[0] == index:\n final_coordinates.append([\n dim[1],\n dim[1]+dim[2],\n dim[3],\n dim[3]+dim[4]\n ])\n for dim_next in stave_coordinates[index:]:\n if dim_next[0] == index:\n final_coordinates[index-1][1] = dim_next[1] + dim_next[2]\n if dim_next[3] < dim[3]:\n final_coordinates[index-1][2] = dim_next[3]\n if dim_next[3] + dim_next[4] > dim[3] + dim[4]:\n final_coordinates[index-1][3] = dim_next[3] + dim_next[4]\n index += 1\n return final_coordinates, x_start, x_end\n\n\ndef write_stave_images(stave_coordinates, x_start, x_end, original, lines, glyphs):\n for index, stave_coord in enumerate(stave_coordinates):\n cv2.imwrite(f'./stave_boxes/{ manu }_{ file }_stave_{ index }_bb.png',\n original[\n stave_coord[0]-60:stave_coord[1]+60,\n x_start-30:x_end+30\n ])\n cv2.imwrite(f'./stave_boxes_lines/{ manu }_{ file }_stave_lines_{ index }_bb.png',\n lines[\n stave_coord[0]-60:stave_coord[1]+60,\n x_start-30:x_end+30\n ])\n cv2.imwrite(f'./stave_boxes_glyphs/{ manu }_{ file }_stave_glyphs_{ index }_bb.png',\n glyphs[\n stave_coord[0]-60:stave_coord[1]+60,\n x_start-30:x_end+30\n ])\n\n# ------------------------------------------------------------------------------\n\nstave_coords = parse_xml(manu, file)\n\nfinal_stave_coords, x_start, x_end = get_final_coordinates(stave_coords)\n\nprint(final_stave_coords)\n\nwrite_stave_images(final_stave_coords, x_start, x_end, img, img_line, img_glyphs)\n"
},
{
"alpha_fraction": 0.5487746000289917,
"alphanum_fraction": 0.5732820630073547,
"avg_line_length": 28.309858322143555,
"blob_id": "74741a73cffddc260c42212066be85e381e35726",
"content_id": "65a9cbb614620e695863e6157e1e0d7fb81ce471",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2081,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 71,
"path": "/type-write.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "import xml.etree.ElementTree as ET\nimport fileinput\nimport os\nimport cv2 as cv\nimport xmlformatter\n\nprint('Which manuscript (CF or Ein) should be considered:')\nmanu = input().strip()\n\nif manu == 'CF':\n print('Which Calvo file number (09-20, 24-27 currently) should be parsed: ')\nelif manu == 'Ein':\n print('Which Ein file number (01v-05v, 02r-05r currently) should be parsed: ')\nelse:\n print('Please try again.')\n exit()\n\nfile = input().strip()\n\nstave_tree = ET.parse(f'./xml/{ manu }-0{ file }-position-updated.xml')\nstave_root = stave_tree.getroot()\n\nimage = cv.imread(f'./originals/{ manu }/{ manu }-0{ file }.png')\ninc = 0\nfor glyph in stave_root.find('glyphs'):\n uly = int(glyph.get('uly'))\n ulx = int(glyph.get('ulx'))\n nrows = int(glyph.get('nrows'))\n ncols = int(glyph.get('ncols'))\n\n type_class = glyph.find('ids').find('id')\n\n cv.imshow('image', image[uly-100:uly+nrows+100,ulx-20:ulx+ncols+20])\n cv.waitKey(2)\n print('Type: ')\n type = str(input().strip())\n if type == '':\n type_class.set('name', 'punctum')\n elif type == 'i':\n type_class.set('name', 'inclinatum')\n elif type == 'v':\n type_class.set('name', 'virga')\n elif type == 'c':\n type_class.set('name', 'custos')\n elif type == 'cc':\n type_class.set('name', 'c_clef')\n elif type == 'fc':\n type_class.set('name', 'f_clef')\n elif type == 'p2':\n type_class.set('name', 'podatus2')\n elif type == 'p3':\n type_class.set('name', 'podatus3')\n elif type == 'p4':\n type_class.set('name', 'podatus4')\n elif type == 'p5':\n type_class.set('name', 'podatus5')\n elif type == 'o2':\n type_class.set('name', 'oblique2')\n elif type == 'o3':\n type_class.set('name', 'oblique3')\n elif type == 'o4':\n type_class.set('name', 'oblique4')\n elif type == 'o5':\n type_class.set('name', 'oblique5')\n else:\n type_class.set('name', type)\n # if inc == 20:\n # break\n # inc += 1\n\nstave_tree.write(f'./xml/{ manu }-0{ file }-position-updated.xml')\n"
},
{
"alpha_fraction": 0.502173662185669,
"alphanum_fraction": 0.535574197769165,
"avg_line_length": 32.44326400756836,
"blob_id": "79ffe770bf4816b4ff9553a760504238e78c8037",
"content_id": "2ef8da31f3ea7e40ecdd53f3189f354164386185",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9431,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 282,
"path": "/image-extraction.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "##########################################################\n#\n# CURRENT FUNCTIONING PARAMETER VALUES\n# (In and around these values tends to work pretty well)\n# ------------------------------------------------------\n#\n# Erosion dimensions: 3 3\n# Erosion iterations: 5\n# Max line gap: 25\n#\n# PAST VALUES\n# ------------------------------------------------------\n#\n# (4,4), 3, 25 |\n\n# ------------------------------------------------------------------------------\n\nimport cv2 as cv\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport os\n\n# ------------------------------------------------------------------------------\n\nprint(\"Enter stave number: \")\nstave_num = input().strip()\nprint(\"Erosion dimensions: \")\nerode = input()\nerode_list = erode.split()\nprint(\"Erosion iterations: \")\niter = int(input().strip())\nprint(\"Gray val (0-255): \")\ngray = int(input().strip())\n# print(\"Max line gap: \")\n# gap = int(input().strip())\n\n# ------------------------------------------------------------------------------\n\ndef open_manuscript_bb_image(manuscript, page_number, stave_number, layer):\n if layer == 'main':\n image = cv.imread('./stave_boxes/' +\n f'{ manuscript }_{ page_number }_stave_{ stave_number }_bb.png')\n else:\n image = cv.imread(f'./stave_boxes_{ layer }/' +\n f'{ manuscript }_{ page_number }' +\n f'_stave_{ layer }_{ stave_number }_bb.png')\n return image\n\n\ndef grayscale_img(image):\n return cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n\n\ndef threshold_img(grayscale_image, low, high):\n ret, threshold = cv.threshold(\n grayscale_image,\n low, high,\n cv.THRESH_BINARY_INV)\n\n return ret, threshold\n\n\ndef line_detection(grayscale_image, display_image, write_image, line_gap):\n skew = 0\n edges = cv.Canny(grayscale_image, 50, 150, apertureSize = 3)\n lines = cv.HoughLinesP(edges, 1, np.pi/180, 100,\n minLineLength = 100, maxLineGap = line_gap)\n lines = np.array(lines)\n lines = lines[np.argsort(lines[:,0,2])]\n avg_slope = np.mean(\n (lines[:,0,3] - lines[:,0,1]) / (lines[:,0,2]-lines[:,0,0]))\n if avg_slope > 0.001:\n print('downward skew')\n skew = -1\n elif avg_slope < -0.001:\n print('upward skew')\n skew = 1\n else:\n print('close to level')\n skew = 0\n ends = lines[-16:]\n ends = ends[np.argsort(ends[:,0,3])]\n new_line = 1\n i = 0\n temp = 0\n while i < len(ends):\n line = ends[i]\n x1,y1,x2,y2 = line[0]\n if temp == 0 or y2 - temp > 30:\n m = (y2-y1) / (x2 - x1)\n b = m * (-1 * x1) + y1\n if -0.2 <= (y2-y1) / (x2 - x1) <= 0.2:\n # cv.line(display_image, (x1,y1), (int(x2*1.2),int(m*x2*1.2+b)), (80,90,110),6)\n cv.line(write_image, (x1,y1), (int(x2*1.2),int(m*x2*1.2+b)), (80,90,110),6)\n temp = y2\n i += 1\n return 0\n\n\ndef erode_image(image, erode_dimensions, erode_iterations):\n kernel = np.ones(\n (int(erode_dimensions[0]), int(erode_dimensions[1])),np.uint8)\n erosion = cv.erode(image, kernel, iterations = erode_iterations)\n kernel_final = np.ones((2,2), np.uint8)\n erosion = cv.erode(erosion, kernel_final, iterations = 1)\n return erosion\n\ndef dilate_image(image, erode_dimensions, dilate_iterations):\n # kernel = np.ones(\n # (int(erode_dimensions[0]), int(erode_dimensions[1])),np.uint8)\n # dilation = cv.dilate(image, kernel, iterations = dilate_iterations)\n kernel_final = np.ones((3,3), np.uint8)\n dilation = cv.dilate(image, kernel_final, iterations = 5)\n return dilation\n\ndef draw_filter_contours(image, comparison_image, draw_image):\n contour_count = 0\n contours_filtered = []\n contours, hierarchy = cv.findContours(\n image.copy(), cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE)\n for index, c in enumerate(contours):\n x,y,w,h=cv.boundingRect(c)\n if h > 10:\n epsilon = 0.01*cv.arcLength(c,True)\n approx = cv.approxPolyDP(c,epsilon,True)\n white_count = 0\n for point in approx:\n if comparison_image[point[0][1],point[0][0]] != 0:\n white_count += 1\n if white_count > 1:\n cv.drawContours(draw_image, [approx], -1,\n (\n random.randint(120,255),\n random.randint(120,255),\n random.randint(120,255)\n ), 2)\n contours_filtered.append((x,y,w,h))\n contours_filtered = np.array(contours_filtered)\n contours_filtered = contours_filtered[np.lexsort((contours_filtered[:,1],\n contours_filtered[:,0]))]\n return contours_filtered\n\n\ndef contour_overlap(contours):\n overlap = np.zeros(len(contours))\n overlap_filter = []\n remove = np.zeros(len(contours))\n remove_index = 0\n contours_filtered = []\n for i, c in enumerate(contours):\n j = i\n for c_n in contours[i+1:]:\n j += 1\n if (c[0] < c_n[0] + 4 < c[0] + c[2] or\n c_n[0] < c[0] + 4 < c_n[0] + c_n[2]):\n if c[1] < c_n[1]:\n overlap[i] = 1\n remove_index = j\n else:\n overlap[j] = 1\n remove_index = i\n remove[remove_index] = 1\n print('overlap: ',\n c[0], c[0]+c[2], ' | ', c_n[0], c_n[0]+c_n[2])\n for i, c in enumerate(contours):\n if remove[i] != 1:\n contours_filtered.append(c)\n overlap_filter.append(overlap[i])\n contours_filtered = np.array(contours_filtered)\n return contours_filtered, overlap_filter\n\n# c[0] = (x,y,w,h)\n\ndef clef_finder(contours, overlap):\n contours_filtered = []\n clef_check_counter = 0\n matches = []\n i = 0\n for c in contours[:-1]:\n if i >= len(contours) - 1:\n break\n if overlap[i] == 0 and overlap[i+1] == 1:\n clef_check_counter += 1\n if clef_check_counter == 1 and (contours[i][1] < contours[i+1][1] + 4 < contours[i][1] + contours[i][3] or\n contours[i+1][1] < contours[i][1] + 4 < contours[i+1][1] + contours[i+1][3]):\n clef_check_counter += 1\n if clef_check_counter == 2 and (contours[i+1][0]-contours[i][0] <= 60):\n clef_check_counter += 1\n if clef_check_counter == 3:\n if (i != 0 and contours[i][0] - contours[i-1][0] > 400) or i == 0:\n clef_check_counter += 1\n if clef_check_counter == 4:\n contours_filtered.append(\n (\n contours[i][0],\n contours[i][1],\n contours[i+1][2] + contours[i+1][0] - contours[i][0] + 2,\n max(contours[i][3], contours[i+1][3])\n ))\n i += 2\n else:\n contours_filtered.append(contours[i])\n i += 1\n clef_check_counter = 0\n\n contours_filtered.append(contours[-1])\n contours_filtered = np.array(contours_filtered)\n return contours_filtered, matches\n\ndef write_neume_images(contours, write_image, last_image,\n manuscript, page_number, stave_number):\n neume_index = 0\n for i, c in enumerate(contours):\n # if overlap[i] == 0:\n if c[0] < 5:\n resize = write_image[0:, c[0]:c[0]+c[2]+5]\n else:\n resize = write_image[0:, c[0]-5:c[0]+c[2]+5]\n if i == len(contours) - 1:\n print('yeet')\n resize = last_image[0:, c[0]-5:c[0]+c[2]+5]\n resize = cv.resize(resize, (30, 120), interpolation = cv.INTER_AREA)\n cv.imwrite(f'./dataset/{ manu }' +\n f'_{ page_number }_{ stave_number }' +\n f'_{ neume_index }.png', resize)\n\n neume_index += 1\n return 0\n\n# ------------------------------------------------------------------------------\n\nmanu = os.listdir('./stave_boxes')[0].split('_')[0]\npage_num = os.listdir('./stave_boxes')[0].split('_')[1]\n\nif not os.path.isdir('./dataset'):\n os.system('mkdir dataset')\n\n# Remove previous staff images\nos.system(f'rm -rf ./dataset/{ manu }_{ page_num }_{ stave_num }*')\n\nimage = open_manuscript_bb_image(manu, page_num, stave_num, 'main')\nimg_copy = image.copy()\nimg_clean = image.copy()\nimg_disp = image.copy()\nimg_line = open_manuscript_bb_image(manu, page_num, stave_num, 'lines')\nimg_glyphs = open_manuscript_bb_image(manu, page_num, stave_num, 'glyphs')\n\ngrayscale = grayscale_img(image)\ngray_line = grayscale_img(img_line)\ngray_glyph = grayscale_img(img_glyphs)\n\nret, thresh = threshold_img(grayscale, gray, 255)\nret2, thresh_glyph = threshold_img(gray_glyph, gray, 255)\n\nline_detection(gray_line, img_disp, img_copy, 25)\n\nerosion = erode_image(thresh, erode_list, iter)\n# erosion = dilate_image(erosion, erode_list, iter)\n\ncont_filt = draw_filter_contours(erosion, thresh_glyph, img_disp)\n\ncont_filt, overlap = contour_overlap(cont_filt)\nprint(cont_filt)\nprint(overlap)\ncont_filt, match = clef_finder(cont_filt, overlap)\nprint(cont_filt, match)\nwrite_neume_images(cont_filt, image, img_copy, manu, page_num, stave_num)\nprint('The stave was number', stave_num)\nprint('The gray number was', gray)\n# print(overlap)\n# print(remove)\n\nfig1 = plt.figure(figsize=(20,10))\nfig1 = plt.subplot(3,1,1)\nfig1 = plt.imshow(thresh)\nfig1 = plt.subplot(3,1,2)\nfig1 = plt.imshow(erosion)\nfig1 = plt.subplot(3,1,3)\nfig1 = plt.imshow(img_disp)\n\nplt.show()\n"
},
{
"alpha_fraction": 0.5482581257820129,
"alphanum_fraction": 0.5699599981307983,
"avg_line_length": 28.183332443237305,
"blob_id": "9e5093cfc856f13520c931654c623c94bc94b00e",
"content_id": "ae4a95eb80ffd7ad93f18b196e501b691c02471f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1751,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 60,
"path": "/xml-update.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "import xml.etree.ElementTree as ET\nimport fileinput\nimport os\n\nprint('Which manuscript (CF or Ein) should be considered:')\nmanu = input().strip()\n\nif manu == 'CF':\n print('Which Calvo file number (09-20, 24-27 currently) should be parsed: ')\nelif manu == 'Ein':\n print('Which Ein file number (01v-05v, 02r-05r currently) should be parsed: ')\nelse:\n print('Please try again.')\n exit()\n\nfile = input().strip()\n\nstave_tree = ET.parse(f'./xml/{ manu }-0{ file }-position.xml')\nstave_root = stave_tree.getroot()\n\nf1 = open(f'./xml/{ manu }-0{ file }-position.xml', 'r')\nf2 = open(f'./xml/{ manu }-0{ file }-position-updated.xml', 'w')\n\npositions = []\n\nfor glyph in stave_root.find('glyphs'):\n positions.append(glyph.find('ids').find('id').get('name'))\n\ninc = 0\nfor line in f1:\n if f2.write(line.replace('<glyph ', f'<glyph number=\"{ inc }\" ')) and '<glyph ' in line:\n inc += 1\nf1.close()\nf2.close()\n\n\n\n\nwith open(f'./xml/{ manu }-0{ file }-position-updated.xml', \"r\") as in_file:\n buf = in_file.readlines()\n\ninc = 0\n\nwith open(f'./xml/{ manu }-0{ file }-position-updated.xml', \"w\") as out_file:\n for line in buf:\n # print('yeet')\n if \"</ids>\" in line:\n # print('yeet')\n line = line + \\\n '\\t\\t\\t<type name=\"\"/>\\n' + \\\n '\\t\\t\\t<pitch-estimation>\\n' + \\\n f'\\t\\t\\t\\t<position name=\"{ positions[inc] }\"/>\\n' + \\\n '\\t\\t\\t\\t<pitch name=\"\"/>\\n' + \\\n '\\t\\t\\t</pitch-estimation>\\n'\n\n inc += 1\n out_file.write(line)\n\n# formatter = xmlformatter.Formatter(indent=\"1\", indent_char=\"\\t\", encoding_output=\"ISO-8859-1\", preserve=[\"literal\"])\n# formatter.format_file(f'./xml/{ manu }-0{ file }-position-copy.xml')\n"
},
{
"alpha_fraction": 0.752136766910553,
"alphanum_fraction": 0.752136766910553,
"avg_line_length": 28.25,
"blob_id": "5eb76a145f559f3f96669fdc5b66d379c0ca78b3",
"content_id": "cf837ec65c650cf44b4a94f8b6a38f495bbf3e0d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 117,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 4,
"path": "/zip-datasets.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "import os\n\nos.system('zip -r position_test.zip position_test')\nos.system('zip -r position_train.zip position_train')\n"
},
{
"alpha_fraction": 0.6973094344139099,
"alphanum_fraction": 0.7107623219490051,
"avg_line_length": 39.54545593261719,
"blob_id": "a5d69003b30da3430bf4929461bedbcfc92133cb",
"content_id": "7825895f73b519b2eb439af027c8c37e79383c27",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 446,
"license_type": "permissive",
"max_line_length": 126,
"num_lines": 11,
"path": "/remove-data.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "import os\n\nprint('What data should be removed? Training (0), Testing (1), All (2) ')\nchoice = int(input().strip())\n\nif choice == 0:\n os.system('rm -rf position_train position_train.zip position_train.txt')\nelif choice == 1:\n os.system('rm -rf position_test position_test.zip position_test.txt')\nelif choice == 2:\n os.system('rm -rf position_test position_train position_test.zip position_train.zip position_test.txt position_train.txt')\n"
},
{
"alpha_fraction": 0.5383695960044861,
"alphanum_fraction": 0.5641883611679077,
"avg_line_length": 30.21641731262207,
"blob_id": "d3820b6757f4c6d1ebffa0a3f244bbd6e17c5df5",
"content_id": "ad55066e0d84c866c262f39b7202ceef15fbba46",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4183,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 134,
"path": "/bounding-box-extraction.py",
"repo_name": "DDMAL/xml-parse-glyph-img",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport cv2 as cv\nimport xml.etree.ElementTree as ET\nimport os\nimport subprocess\nimport statistics\n\n# ------------------------------------------------------------------------------\n\nprint('Which manuscript (CF or Ein) should be considered:')\nmanu = input().strip()\n\nif manu == 'CF':\n print('Which Calvo file number (09-20, 24-27 currently) should be parsed: ')\nelif manu == 'Ein':\n print('Which Ein file number (01v-05v, 02r-05r currently) should be parsed: ')\nelse:\n print('Please try again.')\n exit()\n\nfile = input().strip()\n\nprint('Is this for the training (0) or testing (1) dataset?')\nchoice = int(input().strip())\n\nset = ''\nif choice == 1:\n set = 'test'\nelif choice == 0:\n set = 'train'\n\nif not os.path.isdir(f'./position_{ set }'):\n os.system(f'mkdir position_{ set }')\n\n\n\nos.system(f'rm -rf ./position_{ set }/{ manu }_{ file }_*')\n\n# ------------------------------------------------------------------------------\n\norig_img = cv.imread(f'./originals/{ manu }/{ manu }-0{ file }.png')\n# neume_layer = cv.imread(f'./layer/{ manu }/'\n# + f'{ manu }-0{ file }/{ manu }-0{ file }_1.png')\n# stave_layer = cv.imread(f'./layer/{ manu }/'\n# + f'{ manu }-0{ file }/{ manu }-0{ file }_2.png')\n\n# ------------------------------------------------------------------------------\n# Functions\n\nglyph_coords = []\n# glyph_types = []\nstave_tree = ET.parse(f'./xml/{ manu }-0{ file }-position-updated.xml')\nstave_root = stave_tree.getroot()\nglyph_count = 0\nsum = 0\nlabel_dict = {}\nlabels = ['l1', 'l2', 'l3', 'l4', 's1', 's2', 's3', 's4', 's5']\n# types = ['punctum', 'virga', 'inclinatum', 'custos', 'c_clef', 'f_clef',\n# 'oblique2', 'oblique3', 'oblique4',\n# 'podatus2', 'podatus3', 'podatus4', 'podatus5']\n\ntypes = ['c_clef', 'custos', 'f_clef', 'inclinatum',\n 'oblique2', 'oblique3', 'oblique4',\n 'podatus2', 'podatus3', 'podatus4', 'podatus5', 'punctum', 'virga', ]\n\nfor glyph in stave_root.find('glyphs'):\n uly = int(glyph.get('uly'))\n ulx = int(glyph.get('ulx'))\n nrows = int(glyph.get('nrows'))\n ncols = int(glyph.get('ncols'))\n # print(uly, ulx, nrows, ncols)\n label = glyph.find('pitch-estimation').find('position').get('name')\n type = glyph.find('ids').find('id').get('name')\n # print(type, types.index(type))\n # print(label)\n glyph_count += 1\n sum += nrows\n glyph_coords.append([uly, ulx, nrows, ncols, labels.index(label), types.index(type), 0])\n # glyph_types.append(type)\n\navg_neume_height = int(sum/glyph_count)\n\nanh = avg_neume_height\nglyph_coords = np.array(glyph_coords)\navg_neume_y = np.mean(glyph_coords, axis=0)\nglyph_coords = glyph_coords[np.lexsort((glyph_coords[:,1], glyph_coords[:,0]))]\n\ntemp = [0,0,0,0,0,0]\nstaves = 0\nfor c in glyph_coords:\n if c[0] - temp[0] > 100:\n staves += 1\n c[6] = staves\n temp = c\n\nglyph_coords = glyph_coords[np.lexsort((glyph_coords[:,1], glyph_coords[:,6]))]\n\n# print(staves, avg_neume_y)\n\nos.system(f'sed -i \\'\\' \\'/{ manu }_{ file }_/d\\' position_{ set }.txt')\n\npic_count = 0\nlabel_file = open(f'position_{ set }.txt', 'a+')\nzeros = ''\n\nfor c in glyph_coords:\n # print(c)\n bounding_box = orig_img[\n c[0]-2*avg_neume_height:c[0]+c[2]+2*avg_neume_height,\n c[1]:c[1]+c[3]]\n resize = cv.resize(bounding_box, (30,120), interpolation = cv.INTER_AREA)\n if pic_count < 1000:\n zeros = ''\n if pic_count < 100:\n zeros = '0'\n if pic_count < 10:\n zeros = '00'\n file_name = f'{ manu }_{ file }_' + zeros + f'{ pic_count }.png'\n cv.imwrite(f'./position_{ set }/' + file_name, resize)\n # print(types[c[5]])\n label_file.write(file_name + '\\t' + labels[c[4]] + '\\t' + types[c[5]] + '\\n')\n\n pic_count += 1\n\nlabel_file.close()\n\nos.system(f'sort -k3 -n position_{ set }.txt -o position_{ set }.txt')\n# os.system('sort -u position_labels.txt -o position_labels.txt')\n\n# sort = subprocess.Popen(['sort', '-k3', '-n', 'position_labels.txt', '-o', 'position_labels.txt'], stdout=subprocess.PIPE)\n# sort = subprocess.Popen(['sort', '-k3', '-n', 'position_labels.txt'], stdout=subprocess.PIPE)\n# filter = subprocess.Popen(['uniq', '-u'], stdin=sort.stdout)\n#\n# filter.communicate()\n"
}
] | 8 |
AdlerHu/Massive_pictures_download_with_thread
|
https://github.com/AdlerHu/Massive_pictures_download_with_thread
|
503f41ad0c6eb27ad816b9dd786f40de56a72552
|
bf339691d8347bb67e5086aadfdbce97b0fed276
|
4270dd127430df4881c711f679102bd61adae09f
|
refs/heads/master
| 2022-03-29T04:07:54.318856 | 2019-12-22T01:43:00 | 2019-12-22T01:43:00 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5126243233680725,
"alphanum_fraction": 0.5271614193916321,
"avg_line_length": 27.727272033691406,
"blob_id": "f1330b7a40288c31c0f2db8cff4683f31cfb8020",
"content_id": "3c35cd4836f8155945479d0782d37c4a956b67c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2818,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 88,
"path": "/photo_module.py",
"repo_name": "AdlerHu/Massive_pictures_download_with_thread",
"src_encoding": "UTF-8",
"text": "import requests\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\nimport threading\r\n\r\ndef download_pic(url, path):\r\n pic = requests.get(url)\r\n # 將路徑加上圖片的副檔名\r\n path += url[url.rfind('.'):]\r\n f = open(path,'wb')\r\n f.write(pic.content)\r\n f.close()\r\n\r\n\r\ndef get_photolist(photo_name,download_num):\r\n page = 1\r\n photo_list = []\r\n\r\n while True:\r\n url = \"https://pixabay.com/zh/photos/\" + photo_name + \"/?&page=\" + str(page)\r\n\r\n html = requests.get(url)\r\n html.encoding = \"utf-8\"\r\n bs = BeautifulSoup(html.text,\"lxml\")\r\n # 尋找所有標籤為 div 且 class 為 item 的內容\r\n photo_item = bs.find_all(\"div\" , {\"class\" : \"item\"})\r\n\r\n if len(photo_item) == 0:\r\n return None\r\n\r\n for i in range(len(photo_item)):\r\n # 尋找 img 標籤並取出src中的內容\r\n photo = photo_item[i].find(\"img\")[\"src\"]\r\n\r\n if photo in photo_list:\r\n return photo_list\r\n if photo == \"/static/img/blank.gif\":\r\n photo = photo_item[i].find(\"img\")[\"data-lazy\"]\r\n\r\n photo_list.append(photo)\r\n if len(photo_list) >= download_num:\r\n return photo_list\r\n page += 1\r\n\r\n\r\ndef create_folder(photo_name):\r\n folder_name = input(\"請輸入要儲存的資料夾名稱:\")\r\n\r\n if not os.path.exists(folder_name):\r\n os.mkdir(folder_name)\r\n print(\"資料夾不存在,建立資料夾:\" + folder_name)\r\n else:\r\n print(\"找到資料夾:\" + photo_name)\r\n\r\n if not os.path.exists(folder_name + os.sep + photo_name):\r\n os.mkdir(folder_name + os.sep + photo_name)\r\n print(\"建立資料夾:\" + photo_name)\r\n else:\r\n print(photo_name + \"資料夾已存在\")\r\n\r\n return folder_name\r\n\r\n\r\ndef get_photobythread(folder_name, photo_name, photo_list):\r\n download_num = len(photo_list) # 設定下載數量為圖片連結串列的長度\r\n Q = int(download_num / 100) # 取商數\r\n R = download_num % 100 # 取餘數\r\n\r\n for i in range(Q):\r\n threads = []\r\n for j in range(100):\r\n threads.append(threading.Thread(\r\n target=download_pic,\r\n args=(photo_list[i * 100 + j], folder_name + os.sep + photo_name + os.sep + str(i * 100 + j + 1))))\r\n threads[j].start()\r\n for j in threads:\r\n j.join()\r\n print(int((i + 1) * 100 / download_num * 100), '%') # 顯示當前進度\r\n\r\n threads = []\r\n for i in range(R):\r\n threads.append(threading.Thread(\r\n target=download_pic,\r\n args=(photo_list[Q * 100 + i], folder_name + os.sep + photo_name + os.sep + str(Q * 100 + i + 1))))\r\n threads[i].start()\r\n for i in threads:\r\n i.join()\r\n print(\"100%\")"
},
{
"alpha_fraction": 0.7789473533630371,
"alphanum_fraction": 0.7789473533630371,
"avg_line_length": 30.66666603088379,
"blob_id": "6562c3148cd0b52972eddbe42b7c5690bca0719e",
"content_id": "c70cf60d06507e6155e4c8a617b2842352d0fcdc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 117,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 3,
"path": "/README.md",
"repo_name": "AdlerHu/Massive_pictures_download_with_thread",
"src_encoding": "UTF-8",
"text": "# Massive-pictures-download-with-thread\n\n使用線程從 pixabay : https://pixabay.com/zh/photos/ 批量下載圖片\n"
}
] | 2 |
akashpalrecha/privatelib
|
https://github.com/akashpalrecha/privatelib
|
e5f9b58969dadc238bd454ae6bf38e68ae8fffc1
|
b0aa33588f1b7af241665e32acc76cdb94972896
|
4230b3618a398ee8b25113800b44c5472b9d3704
|
refs/heads/main
| 2023-07-08T11:26:28.541118 | 2021-08-09T17:04:52 | 2021-08-09T17:04:52 | 387,382,746 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.567989706993103,
"alphanum_fraction": 0.573577880859375,
"avg_line_length": 41.04819107055664,
"blob_id": "9e5569a1df46fded337cbf6b94cf714be216a7b0",
"content_id": "1ca205e6424e39decf983eb3b3d670ff3d1b3092",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6979,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 166,
"path": "/privatelib/preprocessing/satellite/splits.py",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "from privatelib.basic import *\nfrom PIL import Image\ntry:\n import tifffile\nexcept:\n print(\"`tifffile` not available\")\n\nSPLIT = Namespace(list=1, save_to_dir=2, generator=3)\n\ndef split_image_to_grid(im, chunk_height=None, chunk_width=None, rows=None, cols=None, results=SPLIT.list, out_dir=None, \n pad=False, verbose=True, save_as_rgb=True, bands=[0,1,2], prefix=None, suffix=None, mask=False):\n \"\"\"\n splits `im` into a grid according to specifications and returns results according to `results` param\n im: image [numpy array: h x w x c] to split\n chunk_height: height of resultant splits in pixels. if only `chunk_height` is provided, `chunk_width` takes the same value\n `chunk_height` takes precedence over `rows` and `cols`\n chunk_width: width of resultant splits in pixels.\n rows: number of rows to divide the image into. if only `rows` is provided, `cols` takes the same value\n cols: number of columns to divide image into\n results: set to SPLIT.list to get the function to return a list of the resultant grid items\n set to SPLIT.save_to_dir to save the outputs to `out_dir`\n set to SPLIT.generator to return a generator for the resultant items. The generator returns (im_split, top, left, height, width) for each item\n out_dir: output directory in case SPLIT.save_to_dir is passed\n pad: whether to pad incomplete / edge tiles with 0s for consistent size\n verbose: prints status messages if set to True\n save_as_rgb: save 3 band RGB imagery in PNG format\n bands: bands to use when saving as RGB imagery\n prefix: prefix for saved chunks\n suffix: suffix for saved chunks\n mask: save image as a single channel uint8 mask\n #TODO: generator, better band selection, merge function\n \"\"\"\n if len(im.shape) == 2: \n im = im[:,:,np.newaxis]\n if prefix is None: \n prefix = \"img\"\n if suffix is None: \n suffix = \"\"\n else:\n suffix = f\"_{suffix}\"\n if chunk_height is not None:\n if chunk_width is not None: pass\n else: chunk_width = chunk_height\n split_h = chunk_height\n split_w = chunk_width\n elif rows is not None:\n if cols is not None: pass\n else: cols = rows\n split_h = im.shape[0] // rows\n split_w = im.shape[1] // cols\n out_shape = (split_h, split_w, im.shape[-1])\n h_idx = 0\n w_idx = 0\n vertical_splits = int(np.ceil(im.shape[0] / split_h))\n horizontal_splits = int(np.ceil(im.shape[1] / split_w))\n \n if results == SPLIT.save_to_dir:\n out_dir = Path(out_dir)\n out_dir.mkdir(parents=True, exist_ok=True)\n info = {\n \"height\": int(im.shape[1]),\n \"width\": int(im.shape[0]),\n \"chunk_height\": split_h,\n \"chunk_width\": split_w,\n \"vertical_splits\": vertical_splits,\n \"horizontal_splits\": horizontal_splits,\n \"padded\": pad,\n \"save_as_rgb\": save_as_rgb,\n \"bands\": bands\n }\n out_f = out_dir/\"info.json\"\n with out_f.open(\"w\") as f:\n json.dump(info, f)\n \n out_list = []\n \n while h_idx < im.shape[0]:\n cur_list = []\n w_idx = 0\n while w_idx < im.shape[1]:\n res = im[h_idx:h_idx+split_h, w_idx:w_idx+split_w, :]\n h, w = res.shape[:2]\n if pad:\n if res.shape != out_shape:\n tmp = np.zeros_like(res, shape=out_shape)\n tmp[:res.shape[0], :res.shape[1], :] = res\n res = tmp\n if results == SPLIT.list:\n if verbose: print(f\"processed {h_idx // split_h}_{w_idx // split_w} image\")\n cur_list.append(res)\n elif results == SPLIT.save_to_dir:\n if save_as_rgb:\n out_f = out_dir/f\"{prefix}_{h_idx // split_h}_{w_idx // split_w}{suffix}.png\"\n if mask:\n mask = Image.fromarray(res[:,:,0].astype(np.uint8))\n mask.save(str(out_f))\n else:\n plt.imsave(out_f, res[:,:,bands])\n else:\n out_f = out_dir/f\"{prefix}_{h_idx // split_h}_{w_idx // split_w}{suffix}.tif\"\n tifffile.imsave(out_f, res)\n if verbose: print(f\"Saved split to: {out_f}\")\n elif results == SPLIT.generator:\n raise NotImplementedError(\"Not that straightforward. Will do later\")\n # yield (res, h_idx, w_idx, h, w)\n w_idx += split_w\n h_idx += split_h\n if results == SPLIT.list:\n out_list.append(cur_list)\n \n if results == SPLIT.list:\n return out_list\n \n \ndef merge_images(path:Path, out=\"output.png\", result=SPLIT.save_to_dir, ext=None, debug=False):\n \"\"\"\n path: path containing images with naming convention of split using split_image_to_grid function\n out: output file path\n result: SPLIT.save_to_dir will save merge result to `out`\n SPLIT.list will return merged image #TODO: change this\n ext: extension of images to look for. if not provided, function will infer ext from files\n debug: run set_trace at the start of function\n \"\"\"\n if debug: set_trace()\n path = Path(path)\n if ext is None:\n images = sorted(filter(lambda x: is_image(x), \n path.ls()))\n else:\n images = sorted(list(get_files_by_ext(path, ext)))\n \n suffix = images[0].stem.split(\"_\")[-1]\n try:\n int(suffix) # if this is possible, then there is no suffix\n # adding trailing `_` to image paths\n images = [image.parent/f\"{image.stem}_{image.suffix}\" for image in images]\n suffix = \"\"\n except:\n suffix = f\"_{suffix}\"\n prefix = \"_\".join(images[0].stem.split(\"_\")[:-3])\n ext = images[0].suffix\n stems = [tuple(map(int, img.stem.split(\"_\")[-3:-1])) for img in images] # last split after _ is suffix\n rows = set([stem[0] for stem in stems])\n cols = set([stem[1] for stem in stems])\n row_ims = []\n if 'tifffile' in dir() and ext.lower().endswith('tif'):\n open_func = lambda x: tifffile.imread(str(x))\n def save_func(fname, arr): tifffile.imsave(fname, arr)\n else:\n open_func = lambda x: plt.imread(str(x))\n def save_func(fname, arr): plt.imsave(fname, arr)\n output = \"\".join(str(out).split(\".\")[:-1]) + ext\n image_rows = []\n for row in rows:\n images = []\n gc.collect()\n for col in cols:\n images.append(open_func(path/f\"{prefix}_{row}_{col}{suffix}{ext}\"))\n image_rows.append(np.concatenate(images, axis=1))\n image = np.concatenate(image_rows, axis=0)\n if result == SPLIT.save_to_dir:\n save_func(output, image)\n elif result == SPLIT.list:\n return image\n else:\n raise NotImplementedError(f\"No implementation for provided result format: {result}\")"
},
{
"alpha_fraction": 0.6201550364494324,
"alphanum_fraction": 0.6335917115211487,
"avg_line_length": 26.657142639160156,
"blob_id": "e5d7d745fa917bc5728d372a2ff39111d3215f94",
"content_id": "543cf7e0aed34db8b9631cee00ec18022ed9a633",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1935,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 70,
"path": "/privatelib/basic.py",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "from argparse import Namespace\nfrom pathlib import Path\nimport zipfile\nimport os\nimport json\nimport mimetypes\nfrom pdb import set_trace\nimport gc\n\ntry:\n import numpy as np\nexcept:\n print(\"NumPy not available.\")\n pass\ntry:\n import matplotlib.pyplot as plt\nexcept:\n print(\"Matplotlib not available.\")\n pass\n\n\nPath.ls = lambda x: list(x.iterdir())\nPath.str = lambda x: str(x)\n\ndef get_files_by_ext(path:Path, ext:str, check_if_valid_file:bool=True, size_thresh=5):\n \"\"\"\n gets all the files in a `path` ending in `ext`\n path: Path to folder containing files\n ext: extension to filter files by\n \"\"\"\n path = Path(path)\n return filter(lambda x: x.suffix.lower().endswith(ext) and (is_valid_file(x, thresh=size_thresh) if check_if_valid_file else True), \n path.iterdir())\n \n\ndef zipdir(path, zipname):\n \"\"\"\n adds files in `path` to a compressed zip `zipname`\n path: path containing files to add to zip\n zipname: path to output zip file\n \"\"\"\n path = str(path)\n zipf = zipfile.ZipFile(str(zipname), 'w', zipfile.ZIP_DEFLATED)\n for root, dirs, files in os.walk(path):\n for file in files:\n zipf.write(os.path.join(root, file))\n zipf.close()\n \n\ndef is_image(path:Path):\n res = mimetypes.guess_type(str(path))[0]\n return res is not None and 'image' in res\n\ndef is_valid_file(path:Path, thresh=5):\n \"\"\"\n Checks if file at `path` exists and has minimum size of `thresh`\n \"\"\"\n path = Path(path)\n if path.exists() and path.lstat().st_size > thresh:\n return True\n else: return False\n\ndef get_file_type(x):\n return mimetypes.guess_type(str(x))[0]\n\ndef describe_array(x:np.ndarray):\n print(\"Shape:\", x.shape)\n print(f\"(min, max): {x.min(), x.max()}\")\n print(f\"(mean, std, var): {x.mean(), x.std(), x.var()}\")\n print(f\"Quartiles -- (0, 0.25, 0.5, 0.75, 1.0): {np.quantile(x, [0, 0.25, 0.5, 0.75, 1.0])}\")"
},
{
"alpha_fraction": 0.58203125,
"alphanum_fraction": 0.59375,
"avg_line_length": 23.03125,
"blob_id": "1afa223164e94ce8876f2eeb2aeeec0ad7e51d2f",
"content_id": "5e8b007fb9c6678c6612eadad80ff88b87ee2766",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 768,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 32,
"path": "/privatelib/preprocessing/satellite/conversions.py",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "from privatelib.basic import *\nfrom PIL import Image\ntry:\n import tifffile\nexcept:\n print(\"`tifffile` not available\")\ntry: \n import rasterio\nexcept:\n print(\"`rasterio` not available\")\ntry:\n import cv2\nexcept:\n print(\"`opencv` not available\")\n \ndef project_mask_to_tif(mask:Path, tiff:Path, output_file:Path=\"./output.tif\"):\n mask = cv2.imread(mask, cv2.IMREAD_GRAYSCALE)\n if len(mask.shape) == 3:\n mask = mask[:,:,0]\n tile = rasterio.open(tiff)\n with rasterio.open(\n output_file,\n 'w',\n driver='GTiff',\n height=tile.shape[0],\n width=tile.shape[1],\n count=1,\n dtype=mask.dtype,\n crs=tile.crs,\n transform=tile.transform,\n ) as dst:\n dst.write(mask, 1)"
},
{
"alpha_fraction": 0.7708333134651184,
"alphanum_fraction": 0.7708333134651184,
"avg_line_length": 23.5,
"blob_id": "ed9d6a971c6d176608fb4bb328e2c97e67194da8",
"content_id": "f03aa56a563a4a74dd809057dc6a47db5ac25b60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 48,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 2,
"path": "/privatelib/preprocessing/satellite/__init__.py",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "from .splits import *\nfrom .conversions import *"
},
{
"alpha_fraction": 0.8088235259056091,
"alphanum_fraction": 0.8088235259056091,
"avg_line_length": 33.5,
"blob_id": "4f9ecf4080ad4799e6e22c8ee4af87c9f01d27a1",
"content_id": "4dba5a533b16b4e0d13f91a8c977216a8d1d859c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 2,
"path": "/privatelib/preprocessing/__init__.py",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "from .satellite.splits import *\nfrom .satellite.conversions import *"
},
{
"alpha_fraction": 0.7816901206970215,
"alphanum_fraction": 0.7816901206970215,
"avg_line_length": 21.421052932739258,
"blob_id": "2da5ee914cc6cf9770bcf04d60f77b86ac1c7843",
"content_id": "131f6909520ff97bb0f883757cc14aca29db70fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 426,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 19,
"path": "/README.md",
"repo_name": "akashpalrecha/privatelib",
"src_encoding": "UTF-8",
"text": "# privatelib\n\nContains code I frequently use\n\n# Installation:\n\n`pip install git+https://github.com/akashpalrecha/privatelib.git#egg=privatelib`\n\nOR\n\n`pip install git+ssh://[email protected]/akashpalrecha/privatelib#egg=privatelib`\n\n# Upgrade:\n\n`pip install git+https://github.com/akashpalrecha/privatelib.git#egg=privatelib --upgrade`\n\nOR\n\n`pip install git+ssh://[email protected]/akashpalrecha/privatelib#egg=privatelib --upgrade`\n"
}
] | 6 |
Joyer0099/MarkSystem
|
https://github.com/Joyer0099/MarkSystem
|
4ef443426479599c7602751ffd31b725c1b414b1
|
9592b17a1567d69592f596b44777bfc916b1b193
|
9342dff8734bb024f1fec09f22d4091f108c50b5
|
refs/heads/master
| 2020-04-29T21:26:06.995340 | 2019-05-23T00:21:22 | 2019-05-23T00:21:22 | 176,412,387 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.683351457118988,
"alphanum_fraction": 0.7279651761054993,
"avg_line_length": 46.3684196472168,
"blob_id": "1f6ddf1aef48d6208347aee5032d6822db30a5b8",
"content_id": "bf25982f9af36f9bc15a3bfb1e4369f3c5c35729",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 919,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 19,
"path": "/apps/MarkManagement/algorithm/network.py",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\r\nimport xgboost as xgb\r\nimport lightgbm as lgb\r\nfrom sklearn.model_selection import KFold, cross_val_score, train_test_split\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import ShuffleSplit\r\nfrom sklearn.metrics import fbeta_score, make_scorer\r\nfrom sklearn.metrics import r2_score\r\nfrom sklearn.model_selection import GridSearchCV\r\n\r\ndef getXGBmodel():\r\n xgb_regressor = xgb.XGBRegressor(seed=2018, nthread=16)\r\n cv_sets_xgb = ShuffleSplit(random_state=10)\r\n parameters_xgb = {'n_estimators': [500, 1000, 2000, 5000], 'learning_rate': [\r\n 0.01, 0.05, 0.07], 'max_depth': [5, 6, 7], 'min_child_weight': [1, 1.5, 2]}\r\n scorer_xgb = make_scorer(r2_score)\r\n grid_obj_xgb = GridSearchCV(\r\n xgb_regressor, parameters_xgb, scoring=scorer_xgb, cv=cv_sets_xgb)\r\n return grid_obj_xgb\r\n"
},
{
"alpha_fraction": 0.5504499673843384,
"alphanum_fraction": 0.5609709620475769,
"avg_line_length": 37.11111068725586,
"blob_id": "68d16bd5faa4bd093c29ce0bca54534ca4a7f38a",
"content_id": "c0181c5e5787e91bcaf41e49008be5365848ef24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 16958,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 414,
"path": "/apps/MarkManagement/view/ClassInfoView.py",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis file is for the operation of t_ClassInfo table.\n\nHere are operations:\nget_classInfo_full_message_all: GET http://localhost:8000/api/v1/table/class_info/detail/all\n get_classInfo_full_message: GET http://localhost:8000/api/v1/table/class_info/detail/some\n query: GET http://localhost:8000/api/v1/table/class_info/format\n insert: POST http://localhost:8000/api/v1/table/class_info/format\n update: PUT http://localhost:8000/api/v1/table/class_info/format\n remove: DELETE http://localhost:8000/api/v1/table/class_info/format\n\"\"\"\nfrom apps.MarkManagement.view.common import *\n\n\nclass ClassInfoViewSet(viewsets.ViewSet):\n\n def get_classInfo_full_message_all(self, request):\n \"\"\"\n 管理员获取符合参数条件的已有课程信息\n :param request: the request from browser. 用来获取access_token\n :return: JSON response. 包括code, message, subjects(opt), count(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果所有参数为空,即Params中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试查询\n 查询失败,返回query_failed的JSON response\n 查询成功,返回JSON response包括code, message, subjects, count,状态码2000\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n teacher_set = Teacher.objects.filter(token__token_text=access_token)\n teacher = teacher_set[0]\n if not teacher.is_manager:\n return manager_check_failed()\n\n result = []\n\n classInfo_set = ClassInfo.objects.all()\n for classInfo in classInfo_set:\n classInfo_dict = model_to_dict(classInfo)\n\n classInfo_dict['teacher_id'] = classInfo_dict['teacher']\n del classInfo_dict['teacher']\n teacher_dict = model_to_dict(classInfo.teacher)\n classInfo_dict['teacher_message'] = teacher_dict\n\n classInfo_dict['lesson_id'] = classInfo_dict['lesson']\n del classInfo_dict['lesson']\n lesson_dict = model_to_dict(classInfo.lesson)\n classInfo_dict['lesson_message'] = lesson_dict\n\n lesson_dict['college_id'] = lesson_dict['college']\n del lesson_dict['college']\n\n classInfo_dict['student_count'] = len(Student.objects.filter(class__classInfo__id=classInfo.id))\n classInfo_dict['current_semester'] = current_semester\n\n result.append(classInfo_dict)\n\n if len(result) == 0:\n return JsonResponse({\n 'current_semester': current_semester,\n 'code': '4036',\n 'message': status_code['4036']},\n safe=False)\n\n code_number = '2000'\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': result,\n 'count': len(result),\n }\n\n return JsonResponse(result, safe=False)\n\n def get_classInfo_full_message(self, request):\n \"\"\"\n 任课教师获取符合参数条件的已有课程信息\n :param request: the request from browser. 用来获取access_token和查询条件\n :return: JSON response. 包括code, message, subjects(opt), count(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果所有参数为空,即Params中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试查询\n 查询失败,返回query_failed的JSON response\n 查询成功,返回JSON response包括code, message, subjects, count,状态码2000\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n\n if not token_verify(access_token):\n return token_invalid()\n\n id = request.GET.get('id')\n name = request.GET.get('name')\n cid = request.GET.get('cid')\n lesson_id = request.GET.get('lesson_id')\n teacher_id = request.GET.get('teacher_id')\n semester = request.GET.get('semester')\n week = request.GET.get('week')\n room = request.GET.get('room')\n\n if id is None and name is None and cid is None and teacher_id is None \\\n and semester is None and week is None and room is None and lesson_id is None:\n return JsonResponse({\"code\": '4032', \"message\": status_code['4032']})\n\n # 此处待优化,all()\n classInfo_set = ClassInfo.objects.all()\n if id is not None:\n classInfo_set = classInfo_set.filter(id=id)\n if name is not None:\n classInfo_set = classInfo_set.filter(name__contains=name)\n if cid is not None:\n classInfo_set = classInfo_set.filter(cid=cid)\n if lesson_id is not None:\n classInfo_set = classInfo_set.filter(lesson_id=lesson_id)\n if teacher_id is not None:\n classInfo_set = classInfo_set.filter(teacher_id=teacher_id)\n if semester is not None:\n classInfo_set = classInfo_set.filter(semester__contains=semester)\n if week is not None:\n classInfo_set = classInfo_set.filter(week__contains=week)\n if room is not None:\n classInfo_set = classInfo_set.filter(room__contains=room)\n\n result = []\n for classInfo in classInfo_set:\n classInfo_dict = model_to_dict(classInfo)\n classInfo_dict['teacher_id'] = classInfo_dict['teacher']\n del classInfo_dict['teacher']\n teacher_dict = model_to_dict(classInfo.teacher)\n\n classInfo_dict['lesson_id'] = classInfo_dict['lesson']\n del classInfo_dict['lesson']\n lesson_dict = model_to_dict(classInfo.lesson)\n lesson_dict['college_id'] = lesson_dict['college']\n del lesson_dict['college']\n\n classInfo_dict['student_count'] = len(Student.objects.filter(class__classInfo__id=classInfo.id))\n classInfo_dict['lesson_message'] = lesson_dict\n classInfo_dict['teacher_message'] = teacher_dict\n classInfo_dict['current_semester'] = current_semester\n\n result.append(classInfo_dict)\n\n if len(result) == 0:\n return JsonResponse(\n {'current_semester': current_semester,\n 'code': '4036',\n 'message': status_code['4036']}, safe=False)\n\n code_number = '2000'\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': result,\n 'count': len(result),\n }\n\n return JsonResponse(result, safe=False)\n\n def query(self, request):\n \"\"\"\n 获取符合参数条件的已有课程信息\n :param request: the request from browser. 用来获取access_token和查询条件\n :return: JSON response. 包括code, message, subjects(opt), count(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果所有参数为空,即Params中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试查询\n 查询失败,返回query_failed的JSON response\n 查询成功,返回JSON response包括code, message, subjects, count,状态码2000\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n id = request.GET.get('id')\n name = request.GET.get('name')\n cid = request.GET.get('cid')\n teacher_id = request.GET.get('teacher_id')\n lesson_id = request.GET.get('lesson_id')\n semester = request.GET.get('semester')\n week = request.GET.get('week')\n room = request.GET.get('room')\n\n if id is None and name is None and cid is None and teacher_id is None \\\n and semester is None and week is None and room is None and lesson_id is None:\n return JsonResponse({\"code\": '4032', \"message\": status_code['4032']})\n\n # 此处待优化,all()\n classInfo_set = ClassInfo.objects.all()\n if id is not None:\n classInfo_set = classInfo_set.filter(id=id)\n if name is not None:\n classInfo_set = classInfo_set.filter(name__icontains=name)\n if cid is not None:\n classInfo_set = classInfo_set.filter(cid=cid)\n if teacher_id is not None:\n classInfo_set = classInfo_set.filter(teacher_id=teacher_id)\n if lesson_id is not None:\n classInfo_set = classInfo_set.filter(lesson_id=lesson_id)\n if semester is not None:\n classInfo_set = classInfo_set.filter(semester__contains=semester)\n if week is not None:\n classInfo_set = classInfo_set.filter(week__contains=week)\n if room is not None:\n classInfo_set = classInfo_set.filter(room__contains=room)\n\n classInfo_set = classInfo_set.values()\n result = []\n for classInfo in classInfo_set:\n classInfo['current_semester'] = current_semester\n result.append(classInfo)\n\n if len(result) == 0:\n return JsonResponse(\n {'current_semester': current_semester,\n 'code': '4036',\n 'message': status_code['4036']}, safe=False)\n\n code_number = '2000'\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': result,\n 'count': len(result),\n }\n\n return JsonResponse(result, safe=False)\n\n def insert(self, request):\n \"\"\"\n 插入新的课程信息\n :param request: the request from browser. 用来获取access_token和插入参数\n :return: JSON response. 包括code, message, subjects(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试插入\n 插入失败,返回insert_failed的JSON response\n 插入成功,返回JSON response包括code, message, subjects,状态码2001\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n post_data = request.data\n subjects = post_data.get('subjects')\n\n if subjects is None:\n return JsonResponse({'code': '4032', 'message': status_code['4032']}, safe=False)\n\n # 传入参数为字典数组\n tag = False\n insertID = []\n\n for subjectsDict in subjects:\n name = subjectsDict.get('name', None)\n teacher_id = subjectsDict.get('teacher_id', None)\n semester = subjectsDict.get('semester', None)\n week = subjectsDict.get('week', None)\n room = subjectsDict.get('room', None)\n lesson_id = subjectsDict.get('lesson_id', None)\n cid = subjectsDict.get('cid', None)\n\n if name is None or teacher_id is None or lesson_id is None:\n continue\n\n classInfo = ClassInfo()\n if name is not None:\n classInfo.name = name\n if teacher_id:\n classInfo.teacher_id = teacher_id\n if lesson_id:\n classInfo.lesson_id = lesson_id\n if semester is not None:\n classInfo.semester = semester\n if week is not None:\n classInfo.week = week\n if room is not None:\n classInfo.room = room\n if cid is not None:\n classInfo.cid = cid\n\n try:\n classInfo.save()\n insertID.append({'id': classInfo.id})\n tag = True\n except Exception as e:\n continue\n\n if tag:\n result = {\n 'subjects': insertID,\n 'code': '2001',\n 'message': status_code['2001']\n }\n return JsonResponse(result, safe=False)\n else:\n return insert_failed()\n\n def update(self, request):\n \"\"\"\n 更新已有课程信息\n :param request: the request from browser. 用来获取access_token和更新条件\n :return: JSON response. 包括code, message, subjects(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试更新\n 更新失败,返回update_failed的JSON response\n 更新成功,返回JSON reponse包括code, message, subjects,状态码2005\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n put_data = request.data\n subjects = put_data.get('subjects')\n\n if subjects is None:\n return JsonResponse({'code': '4032', 'message': status_code['4032']}, safe=False)\n\n tag = False\n ids = []\n\n for subjectDict in subjects:\n id = subjectDict.get('id')\n name = subjectDict.get('name')\n teacher_id = subjectDict.get('teacher_id')\n lesson_id = subjectDict.get('lesson_id')\n semester = subjectDict.get('semester')\n week = subjectDict.get('week')\n room = subjectDict.get('room')\n cid = subjectDict.get('cid')\n\n if id is None and name is None and teacher_id is None \\\n and semester is None and week is None and cid is None:\n continue\n\n classInfo_set = ClassInfo.objects.filter(id=id)\n for classInfo in classInfo_set:\n if name:\n classInfo.name = name\n if teacher_id:\n classInfo.teacher_id = teacher_id\n if lesson_id:\n classInfo.lesson_id = lesson_id\n if semester:\n classInfo.semester = semester\n if week:\n classInfo.week = week\n if room:\n classInfo.room = room\n if cid:\n classInfo.cid = cid\n\n try:\n classInfo.save()\n ids.append({'id': id})\n tag = True\n except Exception as e:\n continue\n\n if tag:\n return JsonResponse(\n {'subjects': ids,\n 'code': '2005',\n 'message': status_code['2005']}, safe=False)\n else:\n return update_failed()\n\n def remove(self, request):\n \"\"\"\n 删除符合参数条件的已有课程信息\n :param request: the request from browser. 用来获取access_token和删除条件\n :return: JSON response. 包括code, message\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试删除\n 删除失败,返回delete_failed的JSON response\n 删除成功,返回delete_succeed的JSON response\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n delete_data = request.data\n subjects = delete_data.get('subjects')\n\n if subjects is None:\n return JsonResponse({'code': '4032', 'message': status_code['4032']}, safe=False)\n\n tag = False\n\n for subjectDict in subjects:\n id = subjectDict.get('id')\n if id is None:\n continue\n classInfo_set = ClassInfo.objects.filter(id=id)\n if not classInfo_set.exists():\n continue\n\n try:\n classInfo_set.delete()\n tag = True\n except Exception as e:\n continue\n\n if tag:\n return delete_succeed()\n else:\n return delete_failed()\n"
},
{
"alpha_fraction": 0.5328947305679321,
"alphanum_fraction": 0.540381133556366,
"avg_line_length": 32.47848129272461,
"blob_id": "1e66f686760cb223b8bd2fb611e83f96b54359cb",
"content_id": "9f5ed567179f210a6860035420dc2c39b65bb1f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14180,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 395,
"path": "/apps/MarkManagement/view/PointView.py",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis file is for the operation of t_Point table.\n\nHere are operations:\nget_point_list: GET http://localhost:8000/api/v1/point/display\n query: GET http://localhost:8000/api/v1/point/format\n insert: POST http://localhost:8000/api/v1/point/format\n update: PUT http://localhost:8000/api/v1/point/format\n remove: DELETE http://localhost:8000/api/v1/point/format\n\"\"\"\n\nfrom apps.MarkManagement.view.common import *\n\n\nclass PointViewSet(viewsets.ViewSet):\n\n def get_point_list(self, request):\n \"\"\"\n 获取符合参数条件的已有分数详细信息\n :param request: the request from browser. 用来获取access_token和查询条件\n :return: JSON response. 包括code, message, subjects(opt), count(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果所有参数为空,即Params中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试查询\n 查询失败,返回query_failed的JSON response\n 查询成功,返回JSON response包括code, message, subjects, count,状态码2000\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n id = request.GET.get('id')\n classInfo_id = request.GET.get('classInfo_id')\n student_id = request.GET.get('student_id')\n title_id = request.GET.get('title_id')\n date = request.GET.get('date')\n note = request.GET.get('note')\n\n if id is None and classInfo_id is None and student_id is None \\\n and title_id is None and date is None and note is None:\n return parameter_missed()\n\n point_set = Point.objects.all()\n if id is not None:\n point_set = point_set.filter(id=id)\n if student_id is not None:\n point_set = point_set.filter(student_id=student_id)\n if title_id is not None:\n point_set = point_set.filter(title_id=title_id)\n if date is not None:\n point_set = point_set.filter(date=date)\n if note is not None:\n point_set = point_set.filter(note=note)\n if classInfo_id:\n point_set = point_set.filter(classInfo_id=classInfo_id)\n\n result = []\n\n for point in point_set:\n pointDict = model_to_dict(point)\n\n student_dict = model_to_dict(point.student)\n title_dict = model_to_dict(point.title)\n classInfo_dict = model_to_dict(point.classInfo)\n\n pointDict['student_id'] = pointDict['student']\n del pointDict['student']\n\n pointDict['title_id'] = pointDict['title']\n del pointDict['title']\n\n pointDict['classInfo_id'] = pointDict['classInfo']\n del pointDict['classInfo']\n\n pointDict['student_message'] = student_dict\n pointDict['title_message'] = title_dict\n pointDict['classInfo_message'] = classInfo_dict\n\n result.append(pointDict)\n\n if len(result) == 0:\n return query_failed()\n\n code_number = '2000'\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': result,\n 'count': len(result),\n }\n\n return JsonResponse(result, safe=False)\n\n def query(self, request):\n \"\"\"\n 获取符合参数条件的已有分数信息\n :param request: the request from browser. 用来获取access_token和查询条件\n :return: JSON response. 包括code, message, subjects(opt), count(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果所有参数为空,即Params中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试查询\n 查询失败,返回query_failed的JSON response\n 查询成功,返回JSON response包括code, message, subjects, count,状态码2000\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n id = request.GET.get('id')\n classInfo_id = request.GET.get('classInfo_id')\n student_id = request.GET.get('student_id')\n title_id = request.GET.get('title_id')\n date = request.GET.get('date')\n note = request.GET.get('note')\n\n if id is None and classInfo_id is None and student_id is None \\\n and title_id is None and date is None and note is None:\n return parameter_missed()\n\n point_set = Point.objects.filter(classInfo_id=classInfo_id)\n if id is not None:\n point_set = point_set.filter(id=id)\n if student_id is not None:\n point_set = point_set.filter(student_id=student_id)\n if title_id is not None:\n point_set = point_set.filter(title_id=title_id)\n if date is not None:\n point_set = point_set.filter(date=date)\n if note is not None:\n point_set = point_set.filter(note=note)\n if classInfo_id:\n point_set = point_set.filter(classInfo_id=classInfo_id)\n\n # 对象取字典\n point_set = point_set.values()\n result = []\n\n for point in point_set:\n result.append(point)\n\n if len(result) == 0:\n return query_failed()\n\n code_number = '2000'\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': result,\n 'count': len(result),\n }\n\n return JsonResponse(result, safe=False)\n\n def insert(self, request):\n \"\"\"\n 插入新的分数信息\n :param request: the request from browser. 用来获取access_token和插入参数\n :return: JSON response. 包括code, message, subjects(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试插入\n 插入失败,返回insert_failed的JSON response\n 插入成功,返回JSON response包括code, message, subjects,状态码2001\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n post_data = request.data\n subjects = post_data.get('subjects')\n\n if subjects is None:\n return parameter_missed()\n\n tag = False\n ids = []\n\n succeed_ids = []\n failed_message = []\n repeated_ids = []\n\n for subjectDict in subjects:\n classInfo_id = subjectDict.get('classInfo_id')\n student_id = subjectDict.get('student_id')\n title_id = subjectDict.get('title_id')\n date = subjectDict.get('date')\n note = subjectDict.get('note')\n pointNumber = subjectDict.get('pointNumber')\n\n if classInfo_id is None or student_id is None or title_id is None or pointNumber is None:\n continue\n\n exist_point_set = Point.objects.filter(Q(student_id=student_id) & Q(title_id=title_id))\n\n if exist_point_set.exists():\n repeated_ids.append({'id': exist_point_set[0].id})\n continue\n\n point = Point()\n\n if classInfo_id:\n classInfo_set = ClassInfo.objects.filter(id=classInfo_id)\n\n if not classInfo_set.exists():\n continue\n\n point.classInfo = classInfo_set[0]\n\n if student_id:\n student_set = Student.objects.filter(id=student_id)\n\n if not student_set.exists():\n continue\n\n point.student = student_set[0]\n\n if title_id:\n title_set = Title.objects.filter(id=title_id)\n\n if title_set.exists() == 0:\n continue\n\n point.title = title_set[0]\n\n if date:\n point.date = date\n if note:\n point.note = note\n if pointNumber:\n point.pointNumber = pointNumber\n\n try:\n point.save()\n succeed_ids.append({'id': point.id})\n tag = True\n except Exception as e:\n failed_message.append({'student_id': student_id, 'title_id': title_id})\n continue\n\n subjects = {\n \"succeed_ids\": succeed_ids,\n \"failed_message\": failed_message,\n \"repeated_ids\": repeated_ids\n }\n\n if tag:\n return JsonResponse(\n {'subjects': subjects,\n 'code': '2001',\n 'message': status_code['2001']}, safe=False)\n else:\n return JsonResponse(\n {'subjects': subjects,\n 'code': '4037',\n 'message': status_code['4037']}, safe=False)\n\n def update(self, request):\n \"\"\"\n 更新已有分数信息\n :param request: the request from browser. 用来获取access_token和更新条件\n :return: JSON response. 包括code, message, subjects(opt)\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试更新\n 更新失败,返回update_failed的JSON response\n 更新成功,返回JSON reponse包括code, message, subjects,状态码2005\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n put_data = request.data\n subjects = put_data.get('subjects')\n\n if subjects is None:\n return parameter_missed()\n\n tag = False\n ids = []\n\n for subjectDict in subjects:\n id = subjectDict.get('id')\n classInfo_id = subjectDict.get('classInfo_id')\n student_id = subjectDict.get('student_id')\n title_id = subjectDict.get('title_id')\n date = subjectDict.get('date')\n note = subjectDict.get('note')\n pointNumber = subjectDict.get('pointNumber')\n\n if id is None and classInfo_id is None and student_id is None and title_id is None:\n continue\n\n point_set = Point.objects.filter(id=id)\n if classInfo_id:\n point_set = point_set.filter(classInfo_id=classInfo_id)\n if student_id:\n point_set = point_set.filter(student_id=student_id)\n if title_id:\n point_set = point_set.filter(title_id=title_id)\n\n for point in point_set:\n if classInfo_id:\n classInfo_set = ClassInfo.objects.filter(id=classInfo_id)\n\n if not classInfo_set.exists():\n continue\n\n point.classInfo = classInfo_set[0]\n\n if student_id:\n student_set = Student.objects.filter(id=student_id)\n\n if not student_set.exists():\n continue\n\n point.student = student_set[0]\n\n if title_id:\n\n title_set = Title.objects.filter(id=title_id)\n\n if not title_set.exists():\n continue\n\n point.title = title_set[0]\n\n if date:\n point.date = date\n if note:\n point.note = note\n if pointNumber is not None:\n point.pointNumber = pointNumber\n\n try:\n point.save()\n ids.append({'id': point.id})\n tag = True\n except Exception as e:\n continue\n\n if tag:\n return JsonResponse(\n {'subjects': ids,\n 'code': '2005',\n 'message': status_code['2005']}, safe=False)\n else:\n return update_failed()\n\n def remove(self, request):\n \"\"\"\n 删除符合参数条件的已有分数信息\n :param request: the request from browser. 用来获取access_token和删除条件\n :return: JSON response. 包括code, message\n 1、如果token无效,即token不存在于数据库中,返回token_invalid的JSON response\n 2、如果request中的subjects参数为空,即Body-raw-json中没有内容,返回parameter_missed的JSON response\n 3、如果符合条件,尝试删除\n 删除失败,返回delete_failed的JSON response\n 删除成功,返回delete_succeed的JSON response\n \"\"\"\n access_token = request.META.get(\"HTTP_TOKEN\")\n if not token_verify(access_token):\n return token_invalid()\n\n delete_data = request.data\n subjects = delete_data.get('subjects')\n\n if subjects is None:\n return parameter_missed()\n\n tag = False\n\n for subjectDict in subjects:\n id = subjectDict.get('id')\n\n if id is None:\n continue\n\n point_set = Point.objects.filter(id=id)\n\n if not point_set.exists():\n continue\n\n try:\n point_set.delete()\n tag = True\n except Exception as e:\n continue\n\n if tag:\n return delete_succeed()\n else:\n return delete_failed()\n"
},
{
"alpha_fraction": 0.4498477876186371,
"alphanum_fraction": 0.46423134207725525,
"avg_line_length": 37.99109649658203,
"blob_id": "b6784c90fed7976ba159db0add5d033641e2eb91",
"content_id": "89e4f8d72632fbf74113f18f66aeaa6ac64840aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14212,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 337,
"path": "/apps/MarkManagement/view/predictView.py",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\n\"\"\"\n This file is for the performance prediction.\n\"\"\"\n\nimport xgboost as xgb\nfrom apps.MarkManagement.view.common import *\nfrom pandas.core.frame import DataFrame\nfrom keras.layers import Dense, Dropout\nfrom keras.models import Sequential\nfrom sklearn.externals.joblib import load\nimport pandas as pd\nimport keras\nimport time\nimport numpy as np\n\n\nclass PredictViewSet(viewsets.ViewSet):\n def predictScore(self, request):\n \"\"\"\n 预测学位英语成绩\n 使用期中客观分、期中主观分、期中总分、期末客观分、期末主观分和期末总分来预测研究生学位英语成绩\n :param request:\n :return:\n \"\"\"\n\n def getScoreListMapBySidList(id_list):\n \"\"\"\n 该函数用于,根据sidList获得sidList中所包含的学生的入学第一学年秋季的期中客观分、期中主观分、期中总分、期末客观分、期末主观分和期末总分\n :param id_list: sidList是sid列表,形如['2019001','2019002',……]\n :return:result是一个ListMap,形如[map1,map2,……],一个具体map格式如下\n 客观分, 主观分, 总分, 词汇, 听力, 翻译, 写作, 细节, 客观分m, 主观分m, 总分m, 总分1\n map={\n 'sid':'2019001', //学号\n 'score_zk':70, //期中客观分\n 'score_zz':18, //期中主观分\n 'score_zs':88, //期中总分\n 'vocabulary':20, //期中客观单词分\n 'hearing': 10, //期中客观听力分\n 'translate': 10, //期中客观翻译分\n 'writing': 10, //期中客观写作分\n 'details': 10, //期中客观细节分\n 'score_mk':47, //期末客观分\n 'score_mz':10, //期末主观分\n 'score_ms':57, //期末总分\n }\n \"\"\"\n\n point_set = Point.objects.filter(student_id__in=id_list) \\\n .values('pointNumber', 'student__sid', 'title__name', 'title__titleGroup__name')\n\n # print('length of point_set=', len(point_set))\n\n temps = []\n dicts = {}\n results = []\n\n for point in point_set:\n point['sid'] = point['student__sid']\n if point['title__titleGroup__name'] == '期中客观分':\n point['score_zk'] = point['pointNumber']\n if point['title__name'] == '期中词汇':\n point['vocabulary'] = point['pointNumber']\n if point['title__name'] == '期中听力':\n point['hearing'] = point['pointNumber']\n if point['title__name'] == '期中翻译':\n point['translate'] = point['pointNumber']\n if point['title__name'] == '期中写作':\n point['writing'] = point['pointNumber']\n if point['title__name'] == '期中细节':\n point['details'] = point['pointNumber']\n if point['title__titleGroup__name'] == '期中主观分':\n point['score_zs'] = point['pointNumber']\n point['score_zz'] = point['pointNumber']\n if point['title__titleGroup__name'] == '期末客观分':\n point['score_ms'] = point['pointNumber']\n point['score_mk'] = point['pointNumber']\n if point['title__titleGroup__name'] == '期末主观分':\n point['score_ms'] = point['pointNumber']\n point['score_mz'] = point['pointNumber']\n\n del point['pointNumber']\n del point['student__sid']\n del point['title__name']\n del point['title__titleGroup__name']\n temps.append(point)\n\n for temp in temps:\n if temp['sid'] in dicts:\n if 'score_zk' in dicts[temp['sid']] and 'score_zk' in temp:\n dicts[temp['sid']]['score_zk'] += temp['score_zk']\n del temp['score_zk']\n elif 'score_zs' in dicts[temp['sid']] and 'score_zs' in temp:\n dicts[temp['sid']]['score_zs'] += temp['score_zs']\n del temp['score_zs']\n elif 'score_ms' in dicts[temp['sid']] and 'score_ms' in temp:\n dicts[temp['sid']]['score_ms'] += temp['score_ms']\n del temp['score_ms']\n dicts[temp['sid']].update(temp)\n else:\n dicts[temp['sid']] = temp\n\n for value in dicts.values():\n if value != {}:\n if 'score_zk' not in value:\n value['score_zk'] = 0\n if 'score_zz' not in value:\n value['score_zz'] = 0\n if 'score_zs' not in value:\n value['score_zs'] = 0\n if 'score_mk' not in value:\n value['score_mk'] = 0\n if 'score_mz' not in value:\n value['score_mz'] = 0\n if 'score_ms' not in value:\n value['score_ms'] = 0\n if 'vocabulary' not in value:\n value['vocabulary'] = 0\n if 'hearing' not in value:\n value['hearing'] = 0\n if 'translate' not in value:\n value['translate'] = 0\n if 'writing' not in value:\n value['writing'] = 0\n if 'details' not in value:\n value['details'] = 0\n\n results.append(value)\n\n return results\n\n def getNameListBySidList(id_list):\n \"\"\"\n 根据sidList得到nameList\n :param id_list:\n :return:\n \"\"\"\n # print(\"idList=\", id_list)\n\n student_set = Student.objects.filter(id__in=id_list)\n\n name_list = []\n\n for student in student_set:\n student_dict = model_to_dict(student)\n name_list.append(student_dict['name'])\n\n return name_list\n\n # *********************v2_新增1_start *********************#\n # ann预测\n def annpredict(model_file, testData, inputdim):\n model = Sequential()\n model.add(Dense(16, kernel_initializer='normal', input_dim=inputdim, activation='relu'))\n model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n model.add(Dropout(0.01))\n model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n model.add(Dense(units=1))\n model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])\n model.summary()\n model.load_weights(model_file)\n model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])\n\n preds = model.predict(testData)\n keras.backend.clear_session()\n # y_test = list(y_test)\n # score = 0.0\n # for i in range(len(preds)):\n # # print(\"preds[i]=\",preds[i],\"y_test[i]=\",y_test[i])\n # # if(preds[i]<60.0 and y_test[i]<60.0) or (preds[i]>=60.0 and y_test[i]>=60.0):\n # # if preds[i]==y_test[i]<60.0 :\n # if (np.abs(preds[i] - y_test[i]) < 5.0):\n # score += 1\n # print(score / len(y_test))\n return preds\n\n def xgbpredict(model_file, testData):\n tar = load(model_file)\n # dtest = xgb.DMatrix(testData)\n preds = tar.predict(testData)\n # score = 0.0\n # for i in range(len(preds)):\n # if (preds[i] < 60.0 and y_test[i] < 60.0) or (preds[i] >= 60.0 and y_test[i] >= 60.0):\n # # if(np.abs(preds[i]-y_test[i])<5.0):\n # print(\"preds[i]=\", preds[i], \"y_test[i]=\", y_test[i])\n # score += 1\n # print(score / len(y_test))\n return preds\n\n # *********************v2_新增1_end *********************#\n\n # 获得要预测的学生的sidlist\n sidList = []\n # 从前端读到数据\n # print(type(request.data))\n # print(request.data)\n start=time.time()\n # sidList = request.data['sidList']\n sidList =request.data['sidList']\n # sidList = request.data.get('idList')\n end = time.time()\n # print(\"从前台读取数据花费时间=\", end-start)\n # print('sidList=', sidList)\n # request.data['sidList']['param']\n\n # 获得学生姓名列表\n nameList = []\n start = time.time()\n nameList = getNameListBySidList(sidList)\n end = time.time()\n # print(\"获得学生姓名列表花费时间=\", end - start)\n # print('nameList=', nameList)\n\n # 根据sidList获得入学第一学年秋季的期中客观分、期中主观分、期中总分、期末客观分、期末主观分和期末总分\n start = time.time()\n dataset = getScoreListMapBySidList(sidList)\n end = time.time()\n # print(\"取各项分数花费时间=\", end - start)\n\n # 转换数据格式\n dataset = DataFrame(dataset)\n # print(\"dataset=\", dataset)\n\n sidList = list(dataset['sid'])\n dataset.drop('sid', axis=1, inplace=True)\n\n # 将数据列顺序调好\n order = ['score_zk', 'score_zz', 'score_zs', 'vocabulary', 'hearing', 'translate', 'writing', 'details',\n 'score_mk', 'score_mz', 'score_ms']\n dataset = dataset[order]\n\n # /*******测试数据**********/\n # 获取csv文件数据\n # def getdata_csv(fileName):\n # f = open(fileName, encoding='utf-8')\n # data = pd.read_csv(f, encoding='utf-8')\n # f.close()\n # return data\n #\n # dataset = getdata_csv(\"./apps/ScoreAnalysis/data/dataset.csv\")\n # /*******测试数据**********/\n # *********************v2_新增2_start *********************#\n\n # ann预测结果\n start = time.time()\n annpre = annpredict(\"./apps/static/model/Weights-2955--5.23046.hdf5\", dataset, 11)\n annpre = list(annpre.reshape((1, annpre.shape[0]))[0])\n # print(\"annpre=\", annpre)\n # xgb预测结果\n xgbpre = list(xgbpredict(\"./apps/static/model/xgboost.model\", dataset))\n # print(\"xgbpre=\", xgbpre)\n c = {\"annpre\": annpre, \"xgbpre\": xgbpre}\n dataset = DataFrame(c)\n # 融合模型预测结果\n preds = xgbpredict(\"./apps/static/model/xgb_impro.model\", dataset)\n # print(\"preds=\", preds)\n end = time.time()\n # print(\"预测花费时间=\", end - start)\n\n # *********************v2_新增2_end *********************#\n\n # *********************v1_注释1_start *********************#\n # # 导入xgb模型\n # tar = xgb.Booster(model_file=\"./apps/static/model/xgb.model\")\n #\n # # 构建神经网络\n # keras.backend.clear_session()\n # model = Sequential()\n # model.add(Dense(16, kernel_initializer='normal', input_dim=dataset.shape[1], activation='relu'))\n # model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n # model.add(Dropout(0.01))\n # model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n # model.add(Dense(32, kernel_initializer='normal', activation='relu'))\n #\n # model.add(Dense(units=1))\n #\n # model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])\n #\n # model.summary()\n #\n # # 导入ann模型\n # wights = './apps/static/model/Weights-311--7.01484.hdf5' # choose the best checkpoint\n #\n # model.load_weights(wights)\n # model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])\n #\n # # 使用xgb读取数据\n # dataInput = xgb.DMatrix(dataset)\n #\n # # xgb模型获得预测结果\n # preds1 = tar.predict(dataInput)\n #\n # # ann神经网络预测结果\n # preds2 = list(model.predict(dataset).reshape(-1))\n #\n # # 模型融合算法\n #\n # # 不同模型赋予不同权重\n # preds1 = [i * 1 / 4 for i in preds1]\n # preds2 = [i * 3 / 4 for i in preds2]\n # preds = np.sum([preds1, preds2], axis=0)\n\n # *********************v1_注释1_end *********************#\n # 返回结果\n predictListMap = []\n\n for i in range(len(sidList)):\n if preds[i] < 60.0:\n ps = \"0\"\n else:\n ps = '1'\n mp = {\n 'sid': sidList[i],\n 'name': nameList[i],\n 'pass': ps\n }\n predictListMap.append(mp)\n # ******************************预测部分结束******************************\n\n # 如果没有结果返回\n if len(preds) == 0:\n # #########具体应该是什么code_number、返回什么错误信息需要修改#########\n code_number = 4000\n return JsonResponse({'code': code_number, 'message': status_code[code_number]}, safe=False)\n code_number = '2000'\n # 返回结果\n # print(\"predictListMap=\",predictListMap)\n result = {\n 'code': code_number,\n 'message': status_code[code_number],\n 'subjects': predictListMap,\n 'count': len(predictListMap),\n }\n return JsonResponse(result, safe=False)\n"
},
{
"alpha_fraction": 0.8068181872367859,
"alphanum_fraction": 0.8068181872367859,
"avg_line_length": 43,
"blob_id": "eb5b00bb6018ed8cd5a6600e7f03882afb7e883c",
"content_id": "4af2f1e80e3e0f77de0688134c8e50c30f6d20d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 88,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 2,
"path": "/README.md",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "# MarkSystem\nThis is a project of the server of English course score management system.\n"
},
{
"alpha_fraction": 0.43747755885124207,
"alphanum_fraction": 0.47235989570617676,
"avg_line_length": 14.504825592041016,
"blob_id": "b3d186ad446ef488e85167253a73fbc1f403cef5",
"content_id": "c0a07f9c12598762c95d7c4ab96ca82e6992ba4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 50393,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 2694,
"path": "/APIDocument.md",
"repo_name": "Joyer0099/MarkSystem",
"src_encoding": "UTF-8",
"text": "# API design\n[TOC]\n# API STD\n+ GET (SELECT):从服务器检索特定资源,或资源列表。\n+ POST (CREATE):在服务器上创建一个新的资源。\n+ PUT (UPDATE):更新服务器上的资源,提供整个资源。\n+ PATCH (UPDATE):更新服务器上的资源,仅提供更改的属性。\n+ DELETE (DELETE):从服务器删除资源。\n# API follow STD\n+ 所有 url 应当被**小写**\n+ 禁止使用动词作为 url\n+ 如果未加任何筛选条件(通常为参数,即未携带任何参数),默认不返回任何项。\n+ 用户主体为网页客户端和智能手机客户端。\n\n# URL head\n```\nxxx.xxxxxxx.xx/api/v1/\n```\n\n# 版本号\n1.0 实现网站所需基本功能\n\n1.1 增加修改个人信息功能,以及部分数据分析端功能\n\n# 服务器返回状态码\n`英文状态码(正式运行时启用)`\n\n```\n2--- 表示成功\n\n'2000': 'OK, with Response',\n'2001': 'OK, Add new resrource',\n'2002': 'OK, Request accepted',\n'2004': 'OK, No Response content',\n'2005': 'OK, And need to Refresh',\n\n\n4--- 表示失败\n-01- 表示用户 token 认证失败\n'4010': 'Error, Require token',\n'4011': 'Error, Bad token',\n'4012': 'Error, Token out of date',\n'4014': 'Error, Forbidden token',\n'4018': 'Error, Too much connections',\n\n-02- 表示用户身份认证失败\n'4020': 'Error, User is not exist',\n'4021': 'Error, Username or password is incurrent',\n'4022': 'Error, User out of date',\n'4024': 'Error, Forbidden user',\n'4027': 'Error, No authorized permissions',\n\n-03- 表示请求本身错误\n'4030': 'Error, No match API',\n'4031': 'Error, No match Request Type',\n'4032': 'Error, Missing parameters',\n'4033': 'Error, Not Allowed',\n'4035': 'Error, Gone',\n'40329': 'Error, Too Many Requests',\n\n\n5--- 表示服务器失败\n'5001': 'Server is outline',\n'5003': 'Can not access database',\n'5004': 'Gateway Forbidden',\n'5101': 'Server is updating',\n'5201': 'Service Stopped'\n```\n\n`中文状态码(调试时启用)` \n\n``` \n2--- 表示成功\n\n'2000': '成功,服务器已响应',\n'2001': '成功,服务器添加新资源',\n'2002': '成功,请求被接收',\n'2004': '成功,无响应内容',\n'2005': '成功,资源需要被刷新',\n\n\n4--- 表示失败\n-01- 表示用户 token 认证失败\n'4010': '错误,需要token验证',\n'4011': '错误,无效的token',\n'4012': '错误,过期的token',\n'4014': '错误,被禁止的token',\n'4018': '错误,连接次数过多',\n\n-02- 表示用户身份认证失败\n'4020': '错误,用户不存在',\n'4021': '错误,用户名或密码错误',\n'4022': '错误,用户登录已过期',\n'4024': '错误,用户被禁止访问',\n'4027': '错误,权限认证不通过',\n\n-03- 表示请求本身错误\n'4030': '错误,没有符合的API',\n'4031': '错误,没有符合的请求类型',\n'4032': '错误,参数缺失',\n'4033': '错误,请求被拒绝',\n'4035': '错误,已走远',\n'40329': '错误,请求次数过多',\n\n\n5--- 表示服务器失败\n'5001': '服务器已离线',\n'5003': '无法连接数据库',\n'5004': '网管禁止',\n'5101': '服务器更新中',\n'5201': '服务已停止'\n```\n\n\n# Tree View\n```bash\nv1\n|- /table\n| |- /lesson\n| |- /format\n| \n| |- /class_field\n| |- /wrapper\n| |- /format\n| \n| |- /class_info\n| |- /detail\n| |- /all\n| |- /some\n| |- /format\n|\n|- /user\n| |- /info \n| |- /display\n| |- /format\n| |- /manage\n| \n| |- /login\n| |- /logout\n| |- /logon\n|\n|- /student\n| |- /display\n| |- /format\n|\n|- /university\n| |- /format\n|\n|- /college\n| |- /display\n| |- /format\n|\n|- /major\n| |- /format\n|\n|- /point\n| |- /display\n| |- /format\n| |- /import_data\n|\n|- /title\n| |- /display\n| |- /format\n|\n|- /titleGroup\n| |- /format\n|\n|- /analysis\n| |- /student\n| |- /name\n| |- /score\n| /- format\n| /- all\n|\n\n```\n# API Lists \n\n`display只支持GET方法,请求方式与format一致`\n\n---\n\n## `/table/lesson`(todo)\n\n---\n\n## `/table/lesson/format`\n`GET` `POST` `PUT` `DELETE`\n教学班所属的课程组\n\n### `GET` 查询课程组 (如「英语听说课」)\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n| **all** | boolean | optional, 是否返回所有的课程组, 会忽略(id,name和college_id)筛选项 |\n\n###### Response\n\n```json\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 1,\n \"name\": \"英语学术听说\",\n \"college_id\": 1\n },\n {\n \"id\": 2,\n \"name\": \"英语电影视听说\",\n \"college_id\": 1\n }\n ],\n \"count\": 2,\n \"all\": \"1\"\n}\n```\n\n### `PUT` 更改课程组\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n+ 示例 \n\n```json\n{\n \"subjects\":[\n {\n \"id\":1,\n \"name\":\"不实用英语会话\",\n \"college_id\":1\n }\n ...\n ]\n}\n```\n\n###### Response\n成功返回 \n\n```\n{\n \"subjects\": [\n {\n \"id\": 1\n }\n ],\n \"code\": \"2005\",\n \"message\": \"OK, And need to Refresh\"\n} \n\n```\n无任何更改返回\n```\n2004 \n```\n其它失败时返回\n```\n4032\n```\n\n### `POST` 添加新课程组\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Body\n\n| params | 类型 | 说明 |\n| --- | --- | --- |\n| **name** | string | required |\n| **college_id** | integer | required |\n+ 示例 \n\n```json\n{\n\t\"subjects\":[\n\t\t{\n\t\t\t\"id\":1,\n\t\t\t\"name\":\"英语学术视听说\",\n\t\t\t\"college_id\":1\n\t\t}\t\n\t\t\n\t]\n\t\n\t\n}\n```\n\n###### Response\n成功返回 \n\n``` \n{ \n \"subjects\": [ \n { \n \"id\": 3 \n } \n ], \n \"code\": \"2001\",\n \"message\": \"OK, Add new resrource\"\n} \n\n```\n失败时返回\n```\n2004\n```\n\n### `DELETE` 删除课程组\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required\n+ 示例 \n\n```json\n{\n \"subjects\":[\n {\n \"id\":1,\n }\n ...\n ]\n}\n```\n\n###### Response\n成功返回 \n\n```\n{\n \"code\": \"2005\",\n \"message\": \"OK, And need to Refresh\"\n} \n```\n没有成功删除则返回\n```\n2004 \n```\n其它失败时返回\n```\n4032 \n```\n\n---\n\n## `/table/class_field/` (todo)\n\n---\n\n## `/table/class_field/wrapper`\n`GET`\n\n返回教学班组织信息(即教学班和学生的多对多关系)\n\n### `GET` 根据筛选选项获取教学班拥有学生数及学生的id\n\n###### Head\n\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Params\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,以教学班的数据库主键编号为筛选项\n| **classInfo_id** | integer | optional,以课程所属的课程组为筛选项\n| **student_id** | integer | optional,以学生的数据库主键编号为筛选项查找(该学生参加的)课程\n\n###### Response\n```json\n200 OK\n\nJSON\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 293,\n \"student_id\": 315,\n \"classInfo_id\": 39\n }\n ],\n \"count\": 1\n}\n```\n具体的返回值包含所有满足筛选项的查询结果在 Class 表中的内容,具体字段参见数据库相关文档。\n\n若查询失败返回 `400 Bad Request`,若查询结果为空,返回`204 No Content`\n\n## `/table/class_field/format`\n`GET` `POST` `DELETE`\n教学班和学生的关系不应该被修改,如果注册了错误的学生,应该将其删除并另行添加。\n\n### `GET` 根据筛选项获取教学班组织信息(即教学班与学生的多对多关系)\n再次强调,在无筛选项时不会返回任何班级的信息。\n\n+ 对学生信息的修改会触发本接口对应的表额外的修改。 \n\n###### Head \n\n需要 `X-Access-Token`,携带内容为用户 token \n\n###### Params \n\n获取教学班组织信息(即教学班和学生的多对多关系)。若筛选项为空,不返回任何课程。 \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,以教学班的数据库主键编号为筛选项\n| **classInfo_id** | integer | optional,以课程所属的课程组为筛选项\n| **student_id** | integer | optional,以学生的数据库主键编号为筛选项查找(该学生参加的)课程\n\n###### Response\n```json\n200 OK\n\nJSON\n{\n ...\n \"subjects\":[\n {\n \"id\":112,\n \"lesson\":1,\n \"student\":1334124,\n \"sid\":\"2018211511\",\n \"sname\": \"赵茶茶\",\n \"index\": \"01\",\n },\n {\n \"id\":113,\n \"lesson\":1,\n \"student\":1334125,\n \"sid\":\"2018211512\",\n \"sname\": \"钱叶叶\",\n \"index\": \"02\",\n },\n {\n \"id\":114,\n \"lesson\":1,\n \"student\":1334126,\n \"sid\":\"2018211513\",\n \"sname\": \"孙树树\",\n \"index\": \"03\",\n },\n ...\n ],\n \"count\":32\n}\n```\n具体的返回值包含所有满足筛选项的查询结果在 Class 表中的内容,具体字段参见数据库相关文档。\n\n若查询失败返回 `400 Bad Request`,若查询结果为空,返回`204 No Content`\n\n### `POST` 添加新的返回教学班组织信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Body\n提交时对象必须包含「必须」的字段。\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required, 教学班在数据库中的主键编号 |\n| **classInfo_id** | integer | required, 教学班id |\n| **student_id** | integer | required, 学生id |\n| **index** | string | optional, 学生在教学班班内编号 |\n\n+ 示例 \n\n```json\n\nJSON\n{\n \"subjects\": [\n {\n \"classInfo_id\":1,\n \"student_id\":1,\n }\n\n ]\n ...\n}\n```\n\n###### Response\n若成功添加资源,返回\n```\n205 Reset Content\n```\n若失败,返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除教学班组织信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required\n\n+ 示例 \n\n```json\n{\n \"subjects\":[\n {\n \"id\":1,\n }\n ...\n ]\n}\n```\n###### Response\n成功返回 \n\n```\n{\n \"code\": \"2005\",\n \"message\": \"OK, And need to Refresh\"\n} \n```\n没有成功删除则返回\n```\n2004 \n```\n其它失败时返回\n```\n4032 \n```\n\n---\n\n## `/table/class_info`(todo)\n\n---\n\n## `/table/class_info/detail/all`\n`GET`\n\n管理员获取到所有课程信息\n\n###### Head\n需要 `X-Access-Token`,携带内容为用户 token,用于验证身份信息以及寻找到当前教师及其对应角色\n\n###### Response\n```json\n200 OK\n\nJSON\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 1,\n \"name\": \"英语学术听说1班\",\n \"semester\": \"2018秋季\",\n \"week\": \"4-18单周\",\n \"room\": \"3-319\",\n \"cid\": \"001\",\n \"teacher_id\": 1,\n \"teacher_message\": {\n \"id\": 1,\n \"tid\": \"20182018\",\n \"password\": \"password1\",\n \"name\": \"Mr zero\",\n \"college\": 1,\n \"is_manager\": true,\n \"email\": \"\",\n \"mobile\": \"\"\n },\n }\n ......\n ],\n \"count\": 26\n}\n```\n\n若查询失败返回 `400 Bad Request`,若查询结果为空,返回`204 No Content`\n\n\n## `/table/class_info/detail/some`\n`GET`\n\n任课教师获取到个人课程信息\n\n###### Head\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,以 class(教学班)的数据库主键为筛选项筛选课程 |\n| **name** | string | optional,以 name 为搜索项进行模糊匹配 |\n| **cid** | string | optional,以课程代号为筛选项筛选课程 |\n| **lesson_id** | integer | optional,以课程id为搜索项进行匹配 |\n| **teacher_id** | integer | optional,以教师(或管理员)数据库主键为查询条件查询教师所执教的所有课程 |\n| **semester** | string | optional,以 semester 为搜索项进行模糊匹配 |\n| **week** | string | optional,以 week 为搜索项进行模糊匹配 |\n| **room** | string | optional,以 room 为搜索项进行模糊匹配 |\n\n###### Response\n```json\n200 OK\n\nJSON\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 2,\n \"name\": \"英语学术听说1班\",\n \"semester\": \"2018秋季\",\n \"week\": \"4-18单周\",\n \"room\": \"3-319\",\n \"cid\": \"002\",\n \"teacher_id\": 1,\n \"teacher_message\": {\n \"id\": 1,\n \"tid\": \"20182018\",\n \"name\": \"Mr Joe\",\n \"college\": 1,\n \"is_manager\": false,\n \"email\": \"\",\n \"mobile\": \"\"\n },\n }\n ......\n ],\n \"count\": 3\n}\n```\n\n若查询失败返回 `400 Bad Request`,若查询结果为空,返回`204 No Content`\n\n## `/table/class_info/format`\n`GET` `PUT` `POST` `DELETE`\n\n教学班的辅助信息。\n\n### `GET` 获取课程的全部辅助信息\n###### Head\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n获取课程的具体信息,包括 core 部分和 support 部分。若筛选项为空,不返回任何课程。 \n\n \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,以 class(教学班)的数据库主键为筛选项筛选课程 |\n| **name** | string | optional,以 name 为搜索项进行模糊匹配 |\n| **cid** | string | optional,以课程代号为筛选项筛选课程 |\n| **teacher_id** | integer | optional,以教师(或管理员)数据库主键为查询条件查询教师所执教的所有课程 |\n| **semester** | string | optional,以 semester 为搜索项进行模糊匹配 |\n| **week** | string | optional,以 week 为搜索项进行模糊匹配 |\n| **room** | string | optional,以 room 为搜索项进行模糊匹配 |\n| **lesson_id** | integer | optional,以课程id为搜索项进行匹配 |\n\n###### Response\n```json\n200 OK\n\nJSON\n{\n \"subjects\": [\n {\n \"id\":1,\n \"name\":\"英语口语听说311班\",\n \"teacher\":12314,\n \"year\": \"2014\",\n \"month\": \"09\",\n \"date\": \"Friday,11-18 week \",\n \"room\": \"base 3 502\",\n }\n ]\n ...\n}\n```\n若查询失败返回 `400 Bad Request`,若查询结果为空,返回`204 No Content`\n### `POST` 添加新的返回教学班辅助信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Body\n提交时对象必须包含「必须」的字段。\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | string | required |\n| **teacher_id** | integer | required |\n| **lesson_id** | integer | required |\n| **semester** | string | optional |\n| **week** | string | optional |\n| **room** | string | optional |\n| **cid** | string | optional |\n\n+ 示例 \n\n\n```json\n\nJSON\n{\n \"subjects\": [\n {\n \"classInfo_id\":1,\n \"student_id\":1,\n }\n\n ]\n ...\n}\n```\n\n###### Response\n若成功添加资源,返回\n```\n205 Reset Content\n```\n若失败,返回\n```\n400 Bad Request\n```\n### `PUT` 更改课程辅助信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n所添加的课程的授课教师不一定必须为提交 post 的用户。\n\n###### Params\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **teacher_id** | integer | optional |\n| **semester** | string | optional |\n| **week** | string | optional |\n| **room** | string | optional |\n| **lesson_id** | integer | optional |\n\n+ 示例 \n\n```json\nPUT\n{\n\"subjects\": [\n {\n \"id\":1,\n \"name\":\"英语口语听说311班\",\n \"teacher\":12315,\n \"date\": \"Friday,11-18 week\",\n \"room\": \"base 3 504\",\n },\n {\n \"id\":2,\n \"name\":\"英语口语听说312班\",\n \"teacher\":12315,\n \"room\": \"base 3 504\",\n \"_i_m_comment_\": \"比如修改了教师和教室\"\n }]\n}\n```\n\n\n\n###### Response\n成功创建时返回创建/修改的课程信息的 id \n\n```json\n201 Created / 205 Reset Content\n\njson\n{\n \"subjects\":[\n {\n \"id\":[1,2]\n }\n ],\n \"id\":[1,2]\n}\n```\n\n若创建失败,或若请求非法,未通过校验,返回 400\n```\n400 Bad Request\n```\n\n\n### `DELETE` 删除已有的课程信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Body\n提交时对象必须包含正确的 id 字段。\n其余选项不会被读入,没有必要包含。\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例 \n\n```json\n\njson\n{\n\"total\": 1,\n\"subjects\": [\n {\n \"id\": 15,\n \"_this_is_another_comment\":\"下面这些都可以不要\",\n \"room\": \"教3 504\",\n \"name\":\"英语口语听说311班\",\n \"teacher\":12314,\n \"year\": \"2014\",\n \"month\": \"09\",\n \"date\": \"Friday,11-18 week \",\n \"room\": \"base 3 502\",\n }\n],\n...\n}\n```\n\n\n###### Response\n若成功删除资源,返回\n```\n205 Reset Content\n```\n若失败,返回\n```\n400 Bad Request\n```\n\n---\n\n## `/user`(todo)\n\n---\n\n## `/user/info`(todo)\n\n---\n\n## `/user/info/display`\n`GET`\n\n### `GET` 获取用户所有信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n字段类型与数据库字段相同,注意 is_manager 字段返回值为 0,1。 \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional |\n| **tid** | string | optional |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional |\n\n###### Response\n返回时将不会返回 password (密码)字段\n\n```json\n200 OK\n\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 1,\n \"tid\": \"20182018\",\n \"name\": \"Mr zero\",\n \"is_manager\": true,\n \"email\": \"\",\n \"mobile\": \"\",\n \"college_id\": 1,\n \"college_message\": {\n \"id\": 1,\n \"name\": \"语言与传播学院\",\n \"shortname\": \"yycb\",\n \"university_id\": 1\n },\n \"university_message\": {\n \"id\": 1,\n \"name\": \"北京交通大学\",\n \"shortname\": \"BJTU\"\n }\n }\n ],\n \"count\": 1\n}\n```\n\n请求失败时返回 `400 Bad Request`\n\n查询失败时返回`204 No Content`\n\n## `/user/info/format`\n`GET`\n\n### `GET` 获取用户的信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n字段类型与数据库字段相同,注意 is_manager 字段返回值为 0,1。 \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional |\n| **tid** | string | optional |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional |\n\n###### Response\n返回时将不会返回 password (密码)字段 \n\n```json\n200 OK\n\njson\n{\n \"subjects\":[\n {\n \"id\": 14424,\n \"tid\": \"314123\",\n \"name\": \"冯天佑\",\n \"collage\": 502,\n \"manager\": false,\n \"email\": \"\",\n \"mobile\": null,\n }\n ]\n} \n\n```\n请求失败时返回\n```\n400 Bad Request\n```\n查询失败时返回\n```\n204 No Content\n```\n\n### `PUT` 更改当前登录用户信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **old_password** | string | required |\n| **new_password** | string | optional |\n\n+ 示例\n\n```json\nPUT\n{\n \"subjects\": [\n {\n \"id\": 8,\n \"name\": \"张云龙\",\n \"college_id\": 2,\n \"email\": \"[email protected]\",\n \"mobile\": \"13813801380\",\n \"old_password\": \"123456\"\n \"new_password\": \"654321\"\n }\n ]\n}\n\n```\n\n###### Resonpse\n\n成功时返回\n\n```\n{\n \"code\": \"2005\",\n \"message\": \"OK, And need to Refresh\"\n} \n```\n\n更新失败则返回\n```\n{\n \"code\": \"4038\",\n \"message\": \"Error, Data Update Failed\"\n} \n```\n\n密码验证失败则返回\n```\n{\n\t'code': 4021, \n\t'message': \"Error, Username or password is incorrect\"\n}\n```\n\n## `/user/info/manage`\n`GET` `PUT` `POST` `DELETE`\n用户的全部信息。需要管理员权限。\n***仅在该url下才可以进行用户的添加/修改/删除\n\n\n### `GET` 获取用户的信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n字段类型与数据库字段相同,注意 manager 字段返回值为 0,1。 \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional |\n| **tid** | string | optional |\n| **name** | string | optional |\n| **college_id** | integer | optional |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional |\n\n###### Response\n返回时将会包括 password (密码)字段 \n\n```json\n200 OK\n\njson\n{\n \"subjects\":[\n {\n \"id\": 14424,\n \"tid\": \"314123\",\n \"name\": \"冯天佑\",\n \"collage\": 502,\n \"password\": \"123456\",\n \"manager\": false,\n \"email\": \"\",\n \"mobile\": null,\n }\n ]\n} \n\n```\n请求失败时返回\n```\n400 Bad Request\n```\n查询失败时返回\n```\n204 No Content\n```\n\n### `POST` 创建新用户\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **tid** | string | required |\n| **name** | string | required |\n| **password** | string | required |\n| **college_id** | integer | required |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional, 默认为否 |\n\n+ 示例 \n\n```json\njson\n{\n \"subjects\":[\n {\n \"tid\": \"314123\",\n \"name\": \"冯天佑\",\n \"collage\": 502,\n \"password\": \"123456\",\n \"manager\": false,\n \"email\": \"\",\n \"mobile\": null,\n \"password\":123456\n }\n ]\n}\n```\n\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n\n### `PUT` 更改用户信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **tid** | string | optional |\n| **name** | string | optional |\n| **password** | string | optional |\n| **college_id** | integer | optional |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional, 默认为否 |\n\n+ 示例 \n\n```json\njson\n{\n \"subjects\":[\n {\n \t\"id\": \"1\",\n \"tid\": \"314123\",\n \"name\": \"冯天佑\",\n \"collage\": 502,\n \"password\": \"123456\",\n \"manager\": false,\n \"email\": \"\",\n \"mobile\": null,\n \"password\":123456\n }\n ]\n}\n```\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n### `DELETE` 删除指定的用户\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required 筛选指定 id 的用户/学生 |\n\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n\n---\n\n## `/user/login`\n`POST`\n### `POST` 用户登陆\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **tid** | string | required |\n| **password** | string | required |\n+ 示例 \n\n```\n{\n\t\"tid\": \"admin\",\n\t\"password\": \"admin\"\n}\n```\n\n\n\n###### Response\n回应内容为 token,是一串包含注明了用户 id (即token拥有者)的字符串\n```\n200 OK\n{\n \"token\": \"userid:2313 sasdasdzxasx\"\n}\n```\n失败时返回\n```\n400 Bad Request\n```\n\n---\n\n## `/user/logout`\n`POST`\n### `POST` 登出用户\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Body\n```\n{}\n```\n`注销时无需在请求体中包含任何参数`\n###### Response\n```\n205 Reset Content\n```\n\n---\n\n## `/user/logon`\n`POST`\n### `POST` 注册用户\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **tid** | string | required |\n| **name** | string | required |\n| **password** | string | required |\n| **college_id** | integer | required |\n| **email** | string | optional |\n| **mobile** | string | optional |\n| **is_manager** | boolean | optional, 默认为否 |\n\n+ 示例 \n\n```json\njson\n{\n \"subjects\":[\n {\n \"tid\": \"314123\",\n \"name\": \"冯天佑\",\n \"collage\": 502,\n \"password\": \"123456\",\n \"manager\": false,\n \"email\": \"\",\n \"mobile\": null,\n \"password\":123456\n }\n ]\n}\n```\n\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n---\n\n## `/student/`(todo)\n\n---\n## `/student/display`\n`GET`\n\n### `GET` 获取学生的完整信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定 id 的学生 |\n| **sid** | string | optional 筛选指定学号的学生 |\n| **name** | string | optional 筛选指定姓名的学生 |\n| **major_id** | integer | optional 筛选指定专业的学生 |\n| **year** | string | optional 筛选指定学年的学生 |\n| **classInfo_id** | integer | optional 筛选指定教学班的学生 |\n\n以classInfo_id 进行查询,返回该课程下的所有学生,忽略其他参数\n\n\n###### Response\n```json\n200 OK\n\njson\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 350,\n \"sid\": \"17127471\",\n \"name\": \"应德辉\",\n \"year\": \"2019\",\n \"major_id\": 1,\n \"major_message\": {\n \"id\": 1,\n \"name\": \"英语\",\n \"shortname\": \"\",\n \"college_id\": 1\n },\n \"college_message\": {\n \"id\": 1,\n \"name\": \"语言与传播学院\",\n \"shortname\": \"yycb\",\n \"university_id\": 1\n }\n }\n ],\n \"count\": 1\n}\n```\n请求失败时返回\n```\n400 Bad Request\n```\n查询失败时返回\n```\n204 No Content\n```\n\n\n## `/student/format`\n`GET` `PUT` `POST` `DELETE`\n### `GET` 获取学生的基本信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token\n###### Params\n\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定 id 的学生 |\n| **sid** | string | optional 筛选指定学号的学生 |\n| **name** | string | optional 筛选指定姓名的学生 |\n| **major_id** | integer | optional 筛选指定专业的学生 |\n| **year** | string | optional 筛选指定学年的学生 |\n| **classInfo_id** | integer | optional 筛选指定教学班的学生 |\n\n以classInfo_id 进行查询,返回该课程下的所有学生,忽略其他参数\n\n\n###### Response\n```json\n200 OK\n\njson\n{\n \"subjects\":[\n {\n \"id\": 131,\n \"sid\": \"2018141202\",\n \"name\": \"敦迟乌\",\n \"name\": \"2018\",\n \"major\": 155,\n }\n ]\n}\n```\n请求失败时返回\n```\n400 Bad Request\n```\n查询失败时返回\n```\n204 No Content\n```\n\n### `PUT` 更改学生的基本信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params \n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required 筛选指定 id 的用户/学生 |\n| **sid** | string | optional |\n| **name** | string | optional |\n| **major_id** | integer | optional |\n| **year** | string | optional |\n\n###### Body\n此处的 id 应与 Params 中的相吻合。\n\n未包含的字段将不会进行更改。\n\n```json\njson\n{\n \"subjects\":[\n {\n \"id\": 4,\n \"name\": \"萨大成\",\n \"sid\": \"2014123113\",\n \"major\": 155,\n \"year\": null,\n }\n ]\n}\n```\n\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n\n### `POST` 创建新用户/学生\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n注意:若请求中包含 id 将会被忽略。\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **sid** | string | required |\n| **name** | string | required |\n| **major_id** | integer | required |\n| **year** | string | optional |\n\n+ 示例 \n\n```json\njson\n{\n \"subjects\":[\n {\n \"id\": 14,\n \"name\": \"冯天佑\",\n \"password\": \"12345678\",\n \"collage\": 1,\n \"year\": null,\n \"class_field\": \"502\",\n \"group\": 1,\n \"status\": null,\n \"manager\": 0,\n \"postion\": \"班长\",\n \"avatar\": \"https://avatar.hahaha.com\",\n \"email\": \"[email protected]\"\n }\n ]\n}\n```\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n\n### `DELETE` 删除指定的用户/学生\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n必须用 id 指定试图删除的学生。若包含其余的参数将会被忽略。 \n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required 筛选指定 id 的用户/学生 |\n\n###### Response\n成功时返回\n```\n200 OK\n```\n\n请求失败时返回\n```\n400 Bad Request\n```\n\n查询失败时返回\n```\n204 No Content\nNo match student(s)\n```\n\n---\n\n## `/university`(todo)\n\n---\n\n## `/university/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取大学相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定 id 的大学 |\n| **name** | string | optional 通过名称筛选 |\n| **shortname** | string | optional 通过昵称筛选 |\n\n###### Response\n```json\n200 OK\n\n{\n\t\"subjects\":[\n {\n \"id\": 2,\n \"name\": \"University of Chinese Academy of Sciences\",\n \"shortname\": \"UCAS\"\n }\n\t],\n\t\"count\":1,\n\t\"total\":1,\n\t\"title\":\"university\"\n}\n```\n\n\n### `PUT` 更新大学相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **shortname** | string | optional |\n\n+ 示例 \n\n```json\n{\n\t\"subjects\":[\n {\n \"id\": 2,\n \"name\": \"University of Chinese Academy of Sciences\",\n \"shortname\": \"UCAS\"\n }\n\t]\n}\n```\n\n\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `POST` 创建新的大学信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | string | required |\n| **shortname** | string | optional |\n\n+ 示例 \n\n```json\n{\n\t\"subjects\":[\n {\n \"id\": 2,\n \"name\": \"University of Chinese Academy of Sciences\",\n \"shortname\": \"UCAS\"\n }\n\t]\n}\n```\n\n\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除已有的大学信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例 \n\n```json\n{\n subjects:[{\"id\":2},{\"id\":3}]\n}\n```\n\n\n###### Response\n```\n205 Reset Content\n```\n\n---\n\n## `/college`(todo)\n\n---\n\n## `/college/display`\n`GET`\n### `GET` 获取院系全部相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定的院系 |\n| **name** | string | optional 通过名称进行字符串模糊匹配,会同时查询 `name` 和 `shortname` 字段 |\n| **university_id** | integer | optional 查询大学所有的院系 \n\n###### Response\n```json\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 1,\n \"name\": \"语言与传播学院\",\n \"shortname\": \"yycb\",\n \"university_id\": 1,\n \"university_message\": {\n \"id\": 1,\n \"name\": \"北京交通大学\",\n \"shortname\": \"BJTU\"\n }\n }\n ],\n \"count\": 1\n}\n```\n\n\n## `/college/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取院系相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定的院系 |\n| **name** | string | optional 通过名称进行字符串模糊匹配,会同时查询 `name` 和 `shortname` 字段 |\n| **university_id** | integer | optional 查询大学所有的院系 \n\n###### Response\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"university\": \"1\"\n },\n {\n \"id\": \"3\",\n \"name\": \"Art\",\n \"shortname\": \"Art\",\n \"university\": \"2\"\n }\n ]\n}\n```\n\n### `PUT` 更新院系相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **shortname** | string | optional |\n| **university_id** | integer | optional |\n\n+ 示例 \n\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"university\": \"1\"\n },\n ]\n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `POST` 创建新的院系信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | string | required |\n| **shortname** | string | optional |\n| **university_id** | integer | required |\n\n+ 示例 \n\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"university\": \"1\"\n },\n ]\n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除已有的院系信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例 \n\n```json\n{\n subjects:[{\"id\":2},{\"id\":3}]\n}\n```\n\n\n###### Response\n```\n205 Reset Content\n```\n\n\n\n---\n\n\n\n\n\n## `/major`(todo)\n---\n\n## `/major/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取专业相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 筛选指定的专业\n| **name** | string | optional 通过名称进行字符串模糊匹配,会同时查询 `name` 和 `shortname` 字段\n| **college_id** | integer | optional 查询院系所有的专业\n###### Response\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"college\": 1,\n },\n {\n \"id\": \"3\",\n \"name\": \"Modern Art\",\n \"shortname\": \"MA\",\n \"college\": 155,\n }\n ]\n}\n```\n\n### `PUT` 更新专业相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **shortname** | string | optional |\n| **college_id** | integer | optional |\n\n+ 示例 \n\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"college\": \"1\"\n },\n ]\n}\n```\n\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `POST` 创建新的专业信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | string | required |\n| **shortname** | string | optional |\n| **college_id** | integer | required |\n\n+ 示例 \n\n```json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"name\": \"Software Engine\",\n \"shortname\": \"SE\",\n \"college\": \"1\"\n },\n ]\n}\n```\n\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除已有的专业信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例\n\n```json\n{\n subjects:[{\"id\":2},{\"id\":3}]\n}\n```\n\n###### Response\n```\n205 Reset Content\n```\n\n\n\n---\n\n## `/point`\n\n---\n\n## `/point/display`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取所有符合条件分数信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,对id进行查询\n| **classInfo_id** |integer| required,任何分数查询仅限于一科目内\n| **student_id** |integer| optional,以加分对象(学生)进行查询\n| **title_id** |integer| optional,以列名进行查询\n| **date** |datetime| optional,以时间戳进行筛选\n| **note** |string| optional,以备注进行字符串模糊匹配\n\n返回 student_id 为 350 的学生所有成绩信息\n```\n@/point?leeson=2&type=0\n```\n\n###### Response\n```\n200 OK\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 579,\n \"pointNumber\": 52,\n \"note\": \"\",\n \"student_id\": 350,\n \"title_id\": 116,\n \"classInfo_id\": 39,\n \"student_message\": {\n \"id\": 350,\n \"sid\": \"17127471\",\n \"name\": \"应德辉\",\n \"year\": \"2019\",\n \"major\": 1\n },\n \"title_message\": {\n \"id\": 116,\n \"name\": \"客观分\",\n \"titleGroup\": 23,\n \"weight\": 100,\n \"classInfo\": 39\n },\n \"classInfo_message\": {\n \"id\": 39,\n \"name\": \"MBA5班\",\n \"teacher\": 30,\n \"semester\": \"2019年秋季\",\n \"week\": \"1-19周\",\n \"room\": \"2教学楼\",\n \"cid\": \"\",\n \"lesson\": 22\n }\n },\n ......\n ],\n \"count\": 2\n}\n```\n\n## `/point/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取分数条目\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional,对id进行查询\n| **classInfo_id** |integer| required,任何分数查询仅限于一科目内\n| **student_id** |integer| optional,以加分对象(学生)进行查询\n| **title_id** |integer| optional,以列名进行查询\n| **date** |datetime| optional,以时间戳进行筛选\n| **note** |string| optional,以备注进行字符串模糊匹配\n\n返回 id 为 2 的课程所有加分类型为 0.出席 的加分项\n```\n@/point?leeson=2&type=0\n```\n\n###### Response\n```\n200 OK\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"class\": 201503,\n \"student\":10,\n \"point\": 3221,\n \"title\": 121,\n \"date\": ...,\n \"note\":null,\n },\n {\n \"id\": \"2\",\n \"class\": 201421,\n \"student\": 81,\n \"point\": 3144,\n \"title\": 1,\n \"date\": ..,\n \"notes\":...,\n }\n ],\n \"title\":\"point\"\n}\n```\n\n### `PUT` 更新分数条目\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Params\n\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **classInfo_id** |integer| optional |\n| **student_id** |integer| optional |\n| **title_id** |integer| optional |\n| **pointNumber** |integer| optional |\n| **date** |datetime| optional |\n| **note** |string | optional |\n\n+ 示例 \n\n``` json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"lesson\": \"2014211503\",\n \"student\": \"8102212004\",\n \"point\": 32,\n \"title\": \"Test 1\"\n },\n {\n \"id\": \"2\",\n \"lesson\": \"2014211503\",\n \"student\": \"8102212001\",\n \"point\": 31,\n \"title\": \"Test 1\"\n }\n ],\n \"title\":\"point\"\n}\n```\n\n###### Response\n```\n205 Rest Content\n```\n### `POST` 创建新的分数条目\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **classInfo_id** |integer| required |\n| **student_id** |integer| required |\n| **title_id** |string| required |\n| **pointNumber** |integer| required |\n| **date** |date| optional |\n| **note** |varchar| optional |\n\n+ 示例\n\n``` json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"lesson\": \"2014211503\",\n \"student\": \"8102212004\",\n \"point\": 32,\n \"title\": \"Test 1\"\n },\n {\n \"id\": \"2\",\n \"lesson\": \"2014211503\",\n \"student\": \"8102212001\",\n \"point\": 31,\n \"title\": \"Test 1\"\n }\n ],\n \"title\":\"point\"\n}\n```\n###### Response \n```\n205 Rest Content\n```\n\n### `DELETE` 删除已有的分数条目\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Params\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required\n\n+ 示例\n\n``` json\n{\n \"subjects\": [\n {\n \"id\": \"1\",\n \"lesson\": \"2014211503\"\n },\n {\n \"id\": \"2\"\n }\n ],\n \"title\":\"point\"\n}\n```\n\n\n###### Response\n```\n205 Rest Content\n```\n\n## `/point/import_data`\n`POST`\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **title_list** | dict list | required |\n| **point_list** | dict list | required |\n| **lesson_id** | integer | required |\n| **sid_list** | integer list | required |\n\n+ 示例\n\n```json\n{\n \n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n---\n\n## `/title`\n\n---\n\n## `/title/display`\n`GET`\n### `GET` 获取小项相关所有信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 列id |\n| **name** | string | optional 列名 |\n| **type** | integer | optional 小列的类别 (所在大列) |\n| **titleGroup_id** | integer | optional 大列id |\n| **classInfo_id** | integer | optional 教学班id|\n###### Response\n```json\n{\n \"code\": \"2000\",\n \"message\": \"OK, with Response\",\n \"subjects\": [\n {\n \"id\": 101,\n \"name\": \"主观分\",\n \"weight\": 1,\n \"titleGroup_id\": 9,\n \"classInfo_id\": 17,\n \"titleGroup_message\": {\n \"id\": 9,\n \"name\": \"化妆\",\n \"lesson\": 18,\n \"weight\": 20\n },\n \"classInfo_message\": {\n \"id\": 17,\n \"name\": \"戏班牙语\",\n \"teacher\": 24,\n \"semester\": \"2018年春季\",\n \"week\": \"123\",\n \"room\": \"4444444\",\n \"cid\": \"\",\n \"lesson\": 18\n }\n },\n ...\n ],\n \"count\": 6\n}\n```\n\n## `/title/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取小项相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 列id |\n| **name** | string | optional 列名 |\n| **type** | integer | optional 小列的类别 (所在大列) |\n| **titleGroup_id** | integer | optional 大列id |\n| **classInfo_id** | integer | optional 教学班id|\n###### Response\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341(means 13.41),\n }\n ]\n}\n```\n\n### `PUT` 更新小项相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **weight** | integer | optional |\n| **titleGroup_id** | integer | optional |\n| **classInfo_id** | integer | optional |\n\n+ 示例\n\n\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341,\n },\n ]\n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `POST` 创建新的小项信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | varchar | required |\n| **weight** | integer | optional |\n| **titleGroup_id** | integer | required |\n| **classInfo_id** | integer | required |\n\n+ 示例\n\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341,\n },\n ]\n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除已有的小项信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例\n\n```json\n{\n subjects:[{\"id\":2},{\"id\":3}]\n}\n```\n\n###### Response\n```\n205 Reset Content\n```\n\n## `/titleGroup`(todo)\n\n---\n\n## `/titleGroup/format`\n`GET` `POST` `PUT` `DELETE`\n### `GET` 获取大项相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | optional 列id |\n| **name** | string | optional,列名\n| **lesson_id** | integer |大列所属课程id |\n| **weight** | integer | optional 权重 |\n###### Response\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341(means 13.41),\n }\n ]\n}\n```\n\n### `PUT` 更新大项相关信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n| **name** | string | optional |\n| **lesson_id** | integer | optional |\n| **weight** | integer | optional |\n\n+ 示例\n\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341,\n },\n ]\n}\n```\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `POST` 创建新的大项信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **name** | varchar | required |\n| **weight** | integer | optional |\n| **lesson_id** | integer | required |\n\n+ 示例\n\n```json\n{\n \"subjects\": [\n {\n \"id\": 12412412,\n \"name\": \"Writing\",\n \"type\": 1241,\n \"weight\": 1341,\n },\n ]\n}\n```\n\n###### Response\n```\n200 OK\n```\n失败时返回\n```\n400 Bad Request\n```\n\n### `DELETE` 删除已有的大项信息\n###### HEAD\n需要 `X-Access-Token`,携带内容为用户 token。\n\n###### Body\n\n| params | 类型 | 说明 |\n|---|---|---|\n| **id** | integer | required |\n\n+ 示例\n\n```\n{\n subjects:[{\"id\":2},{\"id\":3}]\n}\n```\n\n###### Response\n```\n205 Reset Content\n```\n---\n\n## `/semester`(todo)\n`GET` `PUT`\n### `GET` 获取当前学期信息\n### `PUT` 更改学期信息\n\n## `/analysis`(todo)\n数据分析端所需接口\n\n## `/analysis/student` (todo)\n与学生相关的接口\n\n## `/analysis/student/name`\n\n### `GET` 根据学生id列表获取学生姓名列表\n\n###### HEAD\n需要` X-Access-Token`,携带内容为用户 token。\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id_list** | list | required |\n\n###### Response\n```json\n{\n \"subjects\": [张三, 李四]\n}\n```\n\n## `/analysis/score` (todo)\n与成绩相关的接口\n\n## `/analysis/score/format`\n\n### `GET` 根据学生id列表获取学生成绩信息\n\n###### HEAD\n需要` X-Access-Token`,携带内容为用户 token。\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **id_list** | list | required |\n\n###### Response\n```json\n{\n \"subjects\": \n {\n \"sid\": 2019212001,\n \"score_mk\": 79,\n \"score_zz: 85,\n \"score_zk: 77,\n \"score_zs\": 79,\n \"score_ms\": 80\n },\n {\n \"sid\": 2019212002,\n \"score_mk\": 69,\n \"score_zz: 75,\n \"score_zk: 67,\n \"score_zs\": 77,\n \"score_ms\": 70\n },\n ......\n}\n```\n\n## `/analysis/score/all`\n\n### `GET` 获取当前学期所有学生成绩信息\n\n###### HEAD\n需要` X-Access-Token`,携带内容为用户 token。\n\n###### Params\n| params | 类型 | 说明 |\n|---|---|---|\n| **semester** | string | required |\n\n###### Response\n```json\n{\n \"subjects\": \n {\n 'vocabulary':40,\n 'hearing':9,\n 'translate':7,\n 'writing':7,\n 'details':7,\n 'subjective_qz':20,\n 'objective_qm':60,\n 'subjective_qm':20,\n 'xuewei':70\n },\n {\n 'vocabulary':47,\n 'hearing':15,\n 'translate':9,\n 'writing':17,\n 'details':7,\n 'subjective_qz':30,\n 'objective_qm':72,\n 'subjective_qm':30,\n 'xuewei':85\n },\n ......\n}\n```"
}
] | 6 |
javierrcc522/python_script
|
https://github.com/javierrcc522/python_script
|
b2e903c3569ac0ec4faae7bd5adda40afd917eda
|
4463517779aa399dd296d6eba6b62fe095b4f46c
|
1f5524bc8eae975c51360c204a935804a78be60f
|
refs/heads/master
| 2021-09-04T13:03:00.451354 | 2018-01-19T00:26:49 | 2018-01-19T00:26:49 | 117,940,875 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.552971601486206,
"alphanum_fraction": 0.5813953280448914,
"avg_line_length": 20.44444465637207,
"blob_id": "43e756c008adc9ef531f8e1a5626aaab1246fddc",
"content_id": "27277cc97766908fa48c45f51c3d465a193a0b4a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 387,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 18,
"path": "/contact.py",
"repo_name": "javierrcc522/python_script",
"src_encoding": "UTF-8",
"text": "class Contact:\n def __init__(self,name,number,address,note):\n self.name = name\n self.number = number\n self.address = address\n self.note = note\n\n def all(self):\n print(self.name)\n print(self.number)\n print(self.address)\n print(self.note)\n\n\n\njavier = Contact('Javier', '541-490-1234','portland', 'he likes sc2')\n\njavier.all()\n\n"
},
{
"alpha_fraction": 0.6435432434082031,
"alphanum_fraction": 0.6552827954292297,
"avg_line_length": 29.25806427001953,
"blob_id": "80bffcf35a5ce5827414f8a41b055ed851bba4c2",
"content_id": "b3c59963aeadb76b519745b65540ee7bc22d6553",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 937,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 31,
"path": "/phonebook.py",
"repo_name": "javierrcc522/python_script",
"src_encoding": "UTF-8",
"text": "from contact import Contact\n\nname = str(input('Enter your name: '))\nnumber = str(input('Enter your phone number '))\naddress = str(input('Enter your address '))\nnote = str(input('Enter a note '))\n\nall_contacts = [Contact('Javier', '541-490-1234','portland', 'he likes sc2')]\n\ndef add_contact(name, number, address, note):\n new_contact = Contact(name, number, address, note)\n all_contacts.append(new_contact)\n\ndef find_contact(name, all_contacts):\n contact_found = False\n for contact_info in all_contacts:\n if contact_info.name == name:\n print(contact_info.name, contact_info.number, contact_info.address, contact_info.note)\n contact_found = True\n if contact_found == False:\n print('no one found')\n\n\ndef main():\n add_contact(name, number, address, note)\n search_name = str(input('find someone '))\n find_contact(search_name, all_contacts)\n\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.6095238327980042,
"alphanum_fraction": 0.6095238327980042,
"avg_line_length": 17.58823585510254,
"blob_id": "d9c884ede4380d0c753b47a8d2b73499c07bacdc",
"content_id": "aec89b8a63f0a05a5d3c59d0a9411de89e136288",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 315,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 17,
"path": "/test_phonebook.py",
"repo_name": "javierrcc522/python_script",
"src_encoding": "UTF-8",
"text": "import unittest\nimport phonebook\n\nclass TestAddContact(unittest.TestCase):\n\n def test_add(self):\n # Test to see if a new contact was added\n self.assertIs()\n\n def test_find(self):\n self.assert_\n\n def test_main(self):\n self.assert_\n\nif __name__ == '__main__':\n unittest.main()"
},
{
"alpha_fraction": 0.7596439123153687,
"alphanum_fraction": 0.7655786275863647,
"avg_line_length": 23,
"blob_id": "b27f69033789ecd5d710db94b7cec89111cca4a8",
"content_id": "735fa8bc3c133cd9aaa65aa4adf4fb22726d39fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 337,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 14,
"path": "/Dockerfile",
"repo_name": "javierrcc522/python_script",
"src_encoding": "UTF-8",
"text": "# Use an official Python runtime as a parent image\nFROM python:3.6-slim\n\n# Set the working directory to /phonebook\nWORKDIR /phonebook\n\n# Copy the current directory contents into the container at /app\nADD . /phonebook\n\n# Define environment variable\nENV NAME World\n\n# Run app.py when the container launches\nCMD [\"python\", \"phonebook.py\"]\n\n"
},
{
"alpha_fraction": 0.7166666388511658,
"alphanum_fraction": 0.7166666388511658,
"avg_line_length": 16.285715103149414,
"blob_id": "0d515cc289e4245b3e925c95d8e54ba62478c535",
"content_id": "d4f5be45285ccda2e7f172293d233d1c2a5e7296",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 120,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 7,
"path": "/test_contact.py",
"repo_name": "javierrcc522/python_script",
"src_encoding": "UTF-8",
"text": "import unittest\nimport contact\n\nclass TestContact(unittest.TestCase):\n\n def test_init(self):\n self.assertIs()"
}
] | 5 |
shashankarao/reinforcement-learning
|
https://github.com/shashankarao/reinforcement-learning
|
24ba48fa9f135c0cd2beaa3f73ed2f459b6d39c2
|
e340966b7df5e8f8b0ba520267f8aaf4aca08101
|
097ae8d88124591910fca090046f0c7b31411af7
|
refs/heads/master
| 2020-05-02T14:14:09.416771 | 2011-10-19T15:51:05 | 2011-10-19T15:51:05 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4725813567638397,
"alphanum_fraction": 0.5592955946922302,
"avg_line_length": 21.43000030517578,
"blob_id": "e00abe0ba7cf332c771f59d95db4ab6ba73abf82",
"content_id": "ffcb232601a781e2793a420de813a62265f02739",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4486,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 200,
"path": "/rl.py",
"repo_name": "shashankarao/reinforcement-learning",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport pylab\nimport numpy, random\nimport animate\n\n'''\nThis is the transition matrix delta. At state s and action a,\ntrans(s,a) = s' = next state\n'''\ntrans = (\n\t(1 , 3 , 4 , 12) ,\n\t(0 , 2 , 5 , 13) ,\n\t(3 , 1 , 6 , 14) ,\n\t(2 , 0 , 7 , 15) ,\n\t(5 , 7 , 0 , 8) ,\n\t(4 , 6 , 1 , 9) ,\n\t(7 , 5 , 2 , 10) ,\n\t(6 , 4 , 3 , 11) ,\n\t(9 , 11 , 12 , 4) ,\n\t(8 , 10 , 13 , 5) ,\n\t(11 , 9 , 14 , 6) ,\n\t(10 , 8 , 15 , 7) ,\n\t(13 , 15 , 8 , 0) ,\n\t(12 , 14 , 9 , 1) ,\n\t(15 , 13 , 10 , 2) ,\n\t(14 , 12 , 11 , 3)\n)\n\n'''\nReward matrix that makes it walk according to our opinion and view of walking\nThis works better for policy iteration. Is to specific in its reward\n'''\nrew1 = (\n\t(1, 0, 0, 0) , #0\n\t(0, 1, 0, 0) , #1\n\t(1, 0, 0, 0) ,#2\n\t(0, 0, 1, 0) , #3\n\t(0, 0, 0, 0) , #4\n\t(0, 0, 0, 0) ,#5\n\t(0, 0, 0 , 0), #6\n\t(0, 0, 0 , 0), #7\n\t(0, 0, 1, 0), #8\n\t(0, 0, 0, 0), #9\n\t(0, 0 ,0 , 0), #10\n\t(0, 1, 0, 0), #11\n\t(1, 0, 0, 0), #12\n\t(0, 1, 0 , 0), #13\n\t(0, 0, 0 , 1), #14\n\t(0 , 0 , 0, 0), #15\n)\n'''\nThis rewards matrix has negative values for moving its leg\nbackwards when it is in the upright position\n'''\nrew2 = (\n\t(1, 0, 0, 0) , #0\n\t(0, 0, 0, 0) , #1\n\t(0, -1, 0, 0) ,#2\n\t(0, 0, 1, 0) , #3\n\t(0, 0, 0, 0) , #4\n\t(0, 0, 0, 0) ,#5\n\t(0, 0, 0 , 0), #6\n\t(0, 0, 0 , 0), #7\n\t(0, 0, 0, -1), #8\n\t(0, 0, 0, 0), #9\n\t(0, 0 ,0 , 0), #10\n\t(0, 1, 0, 0), #11\n\t(1, 0, 0, 0), #12\n\t(0, 1, 0, 0), #13\n\t(0, 0, 0, 1), #14\n\t(0, 0, 0, 0), #15\n)\n\n'''\nThis is the reward matrix 16x4. For each state s and action a,\nrew(s,a) = r = reward value for doing a in s\n'''\nrew = (\n\t(0, 0, 0, 0) , #0\n\t(0, 1, 0, 0) , #1\n\t(1, 0, 0, 0) ,#2\n\t(0, 0, 0, 0) , #3\n\t(0, 0, 0, 1) , #4\n\t(0, 0, 0, 0) ,#5\n\t(0, 0, 0, 0), #6\n\t(0, 0, 0, 0), #7\n\t(0, 0, 1, 0), #8\n\t(0, 0, 0, 0), #9\n\t(0, 0 ,0 , 0), #10\n\t(0, 0, 0, 0), #11z\n\t(0, 0, 0, 0), #12\n\t(0, 1, 0, 0), #13\n\t(0, 0, 0, 1), #14\n\t(0, 0, 0, 0), #15\n)\n\npolicy = [ None for s in trans ]\nvalue = [ 0 for s in trans ]\ndef policyIteration(rew, gamma, iterations):\n\tglobal policy, value, trans\n\n\tdef argmax(f, args):\n\t\tmi = None\n\t\tm = -1*pow(10,-10)\n\t\tfor i in args:\n\t\t\tv = f(i)\n\t\t\tif v > m:\n\t\t\t\tm = v\n\t\t\t\tmi = i\n\t\treturn mi\n\t\n\t# Policy iteration step\n\tfor p in range(iterations):\t\n\t\tfor s in range(len(policy)):\n\t\t\tpolicy[s] = argmax( lambda a: rew[s][a]+gamma*value[trans[s][a]], range(4))\n\t\tfor s in range(len(value)):\n\t\t\ta = policy[s]\n\t\t\tvalue[s] = rew[s][a]+gamma*value[trans[s][a]]\n\ndef testPolicyIteration(rew, gamma, iterations):\n\tprint '** Testing policy iteration algorithm **'\n\tprint 'Gamma: ', gamma\n\tprint 'Iterations: ', iterations\n\tpolicyIteration(rew, gamma, iterations)\n\n\tprint '\\tOptimal policy: ', policy\n\toptimal_state_map = [ trans[a][policy[a]] for a in range(len(policy)) ] \n\tprint '\\tOptimal state map', optimal_state_map\n\t\n\tcurrent_state = int(random.random()*len(policy))\n\tpath = [current_state]\n\tfor i in range(20):\n\t\tcurrent_state = optimal_state_map[current_state]\n\t\tpath += [current_state]\n\n\tprint '\\t(Hopefully) correct walking path', path\n\t\n\tanimate.draw(path)\n\ngamma = 0.9\niterations = 100\ntestPolicyIteration(rew, gamma, iterations)\n\n################\n## Q-LEARNING ##\n################\n\n\"The transition and rewards are 'hidden' for the Q-learning algorithm\"\nclass Environment():\n\tdef __init__(self, trans, rew, state = 0):\n\t\tself.state = state\n\t\tself.trans = trans\n\t\tself.rew = rew\n\n\tdef go(self, action):\n\t\tr = self.rew[self.state][action]\n\t\tself.state = self.trans[self.state][action]\n\t\treturn self.state, r\n\ndef qLearning(gamma, epsilon, surprise):\n\tglobal state_sequence, trans, rew\n\ts = random.choice(range(16))\n\tenvironment = Environment(trans, rew, s)\n\tQ = [ [random.random()*0.5 for a in range(4)] for s in range(16)]\n\n\tfor step in range(10000):\n\t\taction_list = Q[s]\n\t\tif random.random() < epsilon:\n\t\t\ta = random.choice(range(len(action_list)))\n\t\telse:\n\t\t\ta = action_list.index(max(action_list))\n\t\t\n\t\ts_next, r = environment.go(a)\n\n\t\ta_next_list = Q[s_next]\n\t\ta_next = a_next_list.index(max(a_next_list))\n\n\t\tQ[s][a] = Q[s][a] + surprise*(r + gamma*Q[s_next][a_next] - Q[s][a])\n\t\tstate_sequence += [s]\n\t\ts = s_next\n\ndef testQLearning(gamma, epsilon, surprise):\n\tglobal state_sequence\n\tprint '** Testing Q-Learning algorithm **'\n\tprint 'Gamma: ', gamma\n\tprint 'Epsilon: ', epsilon\n\tprint 'Suprise: ', surprise\n\n\tqLearning(gamma, epsilon, surprise)\n\t\n\tl = len(state_sequence)\n\tprint '\\tState sequence ', state_sequence[l-20:]\n\tanimate.draw(state_sequence[l-20:])\n\ngamma = 0.9\nepsilon = 0.20\nsurprise = 0.9\nstate_sequence = []\ntestQLearning(gamma, epsilon, surprise)\n"
}
] | 1 |
gaon000/telegram_news_bot
|
https://github.com/gaon000/telegram_news_bot
|
a13910ccab76ddb62088d72330861e4d8ac46779
|
684cad2756f23c858405dad85411e211d8327312
|
624c13ea0c596b170847fc7daffba42ab11f75e2
|
refs/heads/master
| 2022-12-02T07:24:50.890184 | 2020-08-05T14:19:46 | 2020-08-05T14:19:46 | 263,953,417 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7560975551605225,
"alphanum_fraction": 0.7560975551605225,
"avg_line_length": 12.666666984558105,
"blob_id": "fb6fb685c3b750d3e0dd6a0a42f7ce9568f33e29",
"content_id": "8a04ee00e0501e092a7361710db7886eefa4a41f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 67,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 3,
"path": "/README.md",
"repo_name": "gaon000/telegram_news_bot",
"src_encoding": "UTF-8",
"text": "# telegram_news_bot\n텔레그램 뉴스 알리미\nNCS 프로젝트\n"
},
{
"alpha_fraction": 0.6650013327598572,
"alphanum_fraction": 0.6889297962188721,
"avg_line_length": 35.56730651855469,
"blob_id": "9d95e1788ae3c6a8fe4c9c7fab7c685b375b111a",
"content_id": "9a6c69b81f1aa51884c7a4f8e926eedffe0653eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4093,
"license_type": "no_license",
"max_line_length": 182,
"num_lines": 104,
"path": "/telegram_bot_command.py",
"repo_name": "gaon000/telegram_news_bot",
"src_encoding": "UTF-8",
"text": "from telegram.ext import Updater, MessageHandler, Filters, CommandHandler\nimport feedparser\nfrom pymongo import MongoClient\n\nclient = MongoClient('localhost', 27017)\ndb = client.ncs\ncollection = db.topic\ncollection_dart = db.dart\n\n#import dart.dart_api as dart\n\nmy_token = '930514973:AAFqVQtB7_igtP85tfAiZY_TVkIjgT0fKn4'\ntopic = \"\"\n\nprint('start telegram chat bot')\n# 중앙, 조선, mk 3분 주기 모니터링\nbreaknews_rss = {\n '머니투데이': 'http://rss.mt.co.kr/mt_news_stock.xml',\n '매일경제':'http://file.mk.co.kr/news/rss/rss_50200011.xml',\n '한국경제':'http://rss.hankyung.com/new/news_stock.xml',\n '이데일리':'http://rss.edaily.co.kr/stock_news.xml',\n 'mk': 'https://www.mk.co.kr/rss/30000001/',\n '중앙일보':'https://rss.joins.com/joins_politics_list.xml',\n '한겨레':'http://www.hani.co.kr/rss/politics/'\n }\ntopic_rss = {\n \n}\n\ndef get_message(bot, update) :\n update.message.reply_text(\"got text\")\n update.message.reply_text(update.message.text)\n\n\ndef help_command(bot, update) :\n update.message.reply_text(\"명령어 목록?\\n1. /subscribe: 구독\\n2. /topic 키워드: 구독할 topic\\n3. /delete 키워드: 삭제할 topic\\n4. /dart_topic 키워드: dart 공시 받을 토픽입력\\n5. /dart_delete 키워드: dart 토픽 삭제\")\n\ndef subscribe_command(bot, update):\n update.message.reply_text(\"구독되었습니다. /topic명령어를 이용하여 topic을 추가하여주세요.\")\n\ndef fss(bot, update, args):\n pass \n\ndef topic_add_command(bot, update, args):\n\ttopics = \"구독한 topic:\"\n\ttopic_list = collection.find_one()['topic']\n\ttopic_list = list(set(topic_list+args))\n\tcollection.replace_one(collection.find_one(), {'topic':topic_list})\n\tfor arg in topic_list:\n\t\ttopics+= '\\n - {}'.format(arg)\n\tbot.send_message(chat_id=944628369, text = topics)\n\ndef topic_sub_command(bot, update, args):\n\ttopic_list = collection.find_one()['topic']\n\tfor i in args:\n\t\ttry:\n\t\t\ttopic_list.remove(i)\n\t\texcept ValueError:\n\t\t\tbot.send_message(chat_id=944628369, text=\"%s은(는) 구독하지 않은 토픽입니다.\"%i)\n\t\t\tcontinue\n\t\tbot.send_message(chat_id=944628369, text=\"%s은(는) 삭제되었습니다.\"%i)\n\tcollection.replace_one(collection.find_one(), {'topic':topic_list})\n\ndef disclosure_topic_add(bot, update, args):\n\tprint(args)\n\ttopics = \"구독한 topic:\"\n\ttopic_list = collection_dart.find_one()['topic']\n\ttopic_list = list(set(topic_list+args))\n\tcollection_dart.replace_one(collection_dart.find_one(), {'topic':topic_list})\n\tfor arg in topic_list:\n\t\ttopics+='\\n - {}'.format(arg)\n\tbot.send_message(chat_id=944628369, text = topics)\n\ndef disclosure_topic_sub(bot, update, args):\n\ttopic_list = collection_dart.find_one()['topic']\n\tfor i in args:\n\t\ttry:\n\t\t\ttopic_list.remove(i)\n\t\texcept ValueError:\n\t\t\tbot.send_message(chat_id=944628369, text=\"%s은(는) 구독하지 않은 토픽입니다.\"%i)\n\t\t\tcontinue\n\t\tbot.send_message(chat_id=944628369, text = \"%s은(는) 삭제되었습니다.\"%i)\n\tcollection_dart.replace_one(collection_dart.find_one(), {'topic':topic_list})\n\t\n\n#def print_news(bot, update, args):\n # for i in topic:\n # if i in RSS:\n # d = feedparser.parse(RSS[i])\n # for j in range(len(d['entries'])):\n # print(d['entries'][j]['title'])\n # print(d['entries'][j]['link'])\n # bot.send_message(chat_id=update.message.chat_id, text = d['entries'][j]['title'])\n # bot.send_message(chat_id=update.message.chat_id, text = d['entries'][j]['title'])\n\nupdater = Updater(my_token)\nupdater.dispatcher.add_handler(CommandHandler('help', help_command))\nupdater.dispatcher.add_handler(CommandHandler('subscribe', subscribe_command))\nupdater.dispatcher.add_handler(CommandHandler('topic', topic_add_command, pass_args=True)) \nupdater.dispatcher.add_handler(CommandHandler('delete', topic_sub_command, pass_args=True))\nupdater.dispatcher.add_handler(CommandHandler('dart_topic', disclosure_topic_add, pass_args=True))\nupdater.dispatcher.add_handler(CommandHandler('dart_delete', disclosure_topic_sub, pass_args=True)) \nupdater.start_polling(timeout=3, clean=True)\nupdater.idle()\n"
},
{
"alpha_fraction": 0.6030751466751099,
"alphanum_fraction": 0.6543279886245728,
"avg_line_length": 29.20689582824707,
"blob_id": "1df09ef78f6b4899359129cba92ed7e50962139f",
"content_id": "8ff585bdda0dc2be218f27745b14614c447e1bc0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1810,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 58,
"path": "/dart/dart_api.py",
"repo_name": "gaon000/telegram_news_bot",
"src_encoding": "UTF-8",
"text": "import dart_fss as dart\nimport requests\nfrom pymongo import MongoClient\nimport datetime\nimport telegram\nimport time\nrecent = {}\nmy_token = '930514973:AAFqVQtB7_igtP85tfAiZY_TVkIjgT0fKn4'\nbot = telegram.Bot(token=my_token)\n\ncli = MongoClient('localhost', 27017)\ndb = cli.ncs\ncollection=db.dart\nnow = datetime.datetime.now()\ntoday = now.strftime('%Y%m%d')\ndetail_link = 'http://m.dart.fss.or.kr/html_mdart/MD1007.html?rcpNo='\napi_key = \"27ed4750893e5a91c18217f817a42059f30499e5\"\ndart.set_api_key(api_key)\nurl = \"https://opendart.fss.or.kr/api/list.xml?crtfc_key={}&corp_code={}\"\ncorp_list=dart.get_corp_list()\n\n#get corp code\ndef get_number(corpname):\n return corp_list.find_by_corp_name(corpname)[0].to_dict()['corp_code']\n\nwhile 1:\n\tfor i in collection.find_one()['topic']:\n\t#\ttry:\n\t\tprint(i)\n\t\tprint(today)\n\t\tcorp_code = get_number(i)\n\t\tapi = f\"https://opendart.fss.or.kr/api/list.json?crtfc_key={api_key}&corp_code={corp_code}&bgn_de={today}\"\n\t\tprint(api)\n\t\tres = requests.get(api).json()\n\t\tstatus = res['status']\n\t\tif status == '013':\n\t\t\tprint('continue')\n\t\t\tcontinue\n\t\telif status == '000':\n\t\t\tif i not in recent:\n\t\t\t\tfor j in reversed(res['list']):\n\t\t\t\t\tbot.send_message(chat_id=944628369 ,text=f\"종목: {i}\\n공시명: {j['report_nm']}\\n공시보기: {detail_link+j['rcept_no']}\")\n\t\t\t\trecent[i] = res['list'][0]['rcept_no']\n\t\t\telse:\n\t\t\t\tif recent[i] == res['list'][0]['rcept_no']:\n\t\t\t\t\tcontinue\n\t\t\t\tfor j in reversed(res['list']):\n\t\t\t\t\tif recent[i] < j['rcept_no']:\n\t\t\t\t\t\tbot.send_message(chat_id=944628369, text=f\"종목: {i}\\n공시명: {j['report_nm']}\\n공시보기: {detail_link+j['rcept_no']}\")\n\t\t\t\trecent[i] = res['list'][0]['rcept_no']\n\t\telse:\n\t\t\tbot.send_message(chat_id=944628369, text=f\"status: {status}\")\n\ttime.sleep(600)\n\t\n\"\"\"\n\t\texcept:\n\t\t\tbot.send_message(chat_id=944628369, text=f'종목 {i}를 확인해주세요.')\n\"\"\"\n\t\t\t\n"
},
{
"alpha_fraction": 0.5864661931991577,
"alphanum_fraction": 0.6140350699424744,
"avg_line_length": 21.16666603088379,
"blob_id": "a6d569dd75bb1a81ba789c700c9c26d0beca2671",
"content_id": "c4a72039acd372f6abedca30bad1c04ecfbf3d98",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 399,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 18,
"path": "/rss_reader/test.py",
"repo_name": "gaon000/telegram_news_bot",
"src_encoding": "UTF-8",
"text": "# from pymongo import MongoClient\n# import schedule\n# import time\n\n# def a():\n# print(bk.find_one()['media']['mk'][0])\n\n# cli = MongoClient('localhost', 27017)\n# db = cli.ncs_db\n# bk = db.topicnews\n# schedule.every(3).minutes.do(a)\n# # while True:\n# # schedule.run_pending()\n# # time.sle\n# bk.insert_one({'a':1})\n# # bk.replace_one(bk.find_one(), {\"media\":{\"mk\":123}})\n#\nimport telegram\n"
},
{
"alpha_fraction": 0.6051374077796936,
"alphanum_fraction": 0.643966555595398,
"avg_line_length": 29.436363220214844,
"blob_id": "4a944e496272e65aec5a1aa058ef4282139893f9",
"content_id": "5c4e6df9985850b06a40c9b6b7048c432a07ca5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1708,
"license_type": "no_license",
"max_line_length": 210,
"num_lines": 55,
"path": "/rss_reader/rss_reader.py",
"repo_name": "gaon000/telegram_news_bot",
"src_encoding": "UTF-8",
"text": "import feedparser\nfrom pymongo import MongoClient\nimport datetime\nfrom dateutil import parser\nimport time\nimport telegram\nmy_token = '930514973:AAFqVQtB7_igtP85tfAiZY_TVkIjgT0fKn4'\nbot = telegram.Bot(token=my_token)\n\n\ncli = MongoClient('localhost', 27017)\ndb = cli.ncs\ncollection_breaknews = db.breaknews\ncollection_topic = db.topic\ncollection_topicnews = db.topicnews\n\na=[]\nb=[]\n# (t-datetime.datetime(1970,1,1)).total_seconds()\nRSS = {\n#'머니투데이': 'http://rss.mt.co.kr/mt_news_stock.xml',\n#'매일경제':'http://file.mk.co.kr/news/rss/rss_50200011.xml',\n#'한국경제':'http://rss.hankyung.com/new/news_stock.xml',\n#'이데일리':'http://rss.edaily.co.kr/stock_news.xml',\n 'mk': 'https://www.mk.co.kr/rss/40300001/'\n }\n# '''\n\nwhile(1):\n\tfor k, v in RSS.items():\n\t\tprint(k)\n\t\td = feedparser.parse(v)\n\t\tfor i in range(len(d['entries'])):\n\t\t\ttry:\n\t\t\t\ta.append(((parser.parse(d['entries'][i]['published']).replace(tzinfo=None) - datetime.datetime(1970,1,1)).total_seconds(), d['entries'][i]['title'], d['entries'][i]['link'], d['entries'][i]['description']))\n\t\t\texcept KeyError:\n\t\t\t\tprint(\"keyerror\")\n\ta.sort(key=lambda element : element[0])\n\t#\tfor i in collection_topic.find_one()['topics']:\n#\t\tfor j in a:\n#\t\t\tif i in j[3]:\n#\tb.append(j)\n \n\tfor i in a:\n\t\tif i[0] > collection_breaknews.find_one()['media']['mk'][0]:\n\t\t\tfor j in collection_topic.find_one()['topic']:\n\t\t\t\tprint(j)\n\t\t\t\tprint(i[3])\n\t\t\t\tif j in i[3]:\n\t\t\t\t\tbot.send_message(chat_id=944628369, text=f'topic is {j}\\n{i[2]}')\n#bot.send_message(chat_id=944628369, text=i)\n\t\t\tif i == a[-1]:\n\t\t\t\tcollection_breaknews.replace_one(collection_breaknews.find_one(), {\"media\":{\"mk\":a[-1]}})\n\ttime.sleep(180)\n# collection_breaknews.insert_one({\"media\":{\"mk\":a[-1]}})\n"
}
] | 5 |
MedusaLeee/py3-machine-learning
|
https://github.com/MedusaLeee/py3-machine-learning
|
149e9f318272ea1efefbed425a7f2eeeab67e662
|
91d60a597d2c241eff2ea7771bedf53aa9687a79
|
3bd9a0695a29e29e1462af12aaee6fc8ac0feed5
|
refs/heads/master
| 2021-01-13T09:06:52.323501 | 2016-09-27T15:11:46 | 2016-09-27T15:11:46 | 69,254,653 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7841306924819946,
"alphanum_fraction": 0.7841306924819946,
"avg_line_length": 24.205883026123047,
"blob_id": "5a976824094921441f184e62c4ae7abcd594d63f",
"content_id": "a892911bee590a97ce842599ce39c36ebf079da1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1119,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 34,
"path": "/tf_idf/test/sklearn_tf_idf_api_test.py",
"repo_name": "MedusaLeee/py3-machine-learning",
"src_encoding": "UTF-8",
"text": "from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer\n\n\"\"\"\nscikit-learn包进行TF-IDF分词权重计算主要用到了两个类:CountVectorizer和TfidfTransformer。其中\nCountVectorizer是通过fit_transform函数将文本中的词语转换为词频矩阵,矩阵元素a[i][j] 表示j词在第i\n个文本下的词频。即各个词语出现的次数,通过get_feature_names()可看到所有文本的关键字,通过toarray()\n可看到词频矩阵的结果。\n\"\"\"\n# 实例化CountVectorizer\ncountVectorizer = CountVectorizer()\n\n# 语料库\ncorpus = [\n 'This is the first document.',\n 'This is the second second document.',\n 'And the third one.',\n 'Is this the first document?',\n ]\n\nterm_matrix = countVectorizer.fit_transform(corpus)\n\n# 打印词频矩阵\nprint(term_matrix.toarray())\n\n# 打印文本关键字\nprint(countVectorizer.get_feature_names())\n\n# TfidfTransformer是统计vectorizer中每个词语的tf-idf值\ntfidfTransformer = TfidfTransformer()\n\ntfidf_matrix = tfidfTransformer.fit_transform(term_matrix)\n\n# 打印tf-idf值矩阵\nprint(tfidf_matrix.toarray())\n"
},
{
"alpha_fraction": 0.7526041865348816,
"alphanum_fraction": 0.7682291865348816,
"avg_line_length": 20.38888931274414,
"blob_id": "60de3d29a2e6f26daf5d8c99c5a15b79d626ec4a",
"content_id": "cd085213ee8e6ab3e62b54b76e3d0e05fed0e8a9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 490,
"license_type": "permissive",
"max_line_length": 137,
"num_lines": 18,
"path": "/README.md",
"repo_name": "MedusaLeee/py3-machine-learning",
"src_encoding": "UTF-8",
"text": "# py3-machine-learning\n自己学习python机器学习的demo。\n\n## 运行环境\n\nPython3\n\n## 余弦相似度\n1. [使用余弦相似度算法计算两个文本的相似度的简单实现](https://github.com/MedusaLeee/py3-machine-learning/tree/master/simple_text_cosine_similarity)\n\n## TF-IDF\n1. [scikit-learn库TF-IDF相关API&Demo](https://github.com/MedusaLeee/py3-machine-learning/blob/master/tf_idf/test/sklearn_tf_idf_api_test.py)\n\nIn coding...\n\n## 朴素贝叶斯分类\n\nComing soon!"
}
] | 2 |
ohwhatafool/Testing
|
https://github.com/ohwhatafool/Testing
|
c70c5232220c4c51b2f7df87ff2c8b37d1cf63bd
|
dde3f301245e76f67749d86709ba0354e318b6b7
|
5e4ef90e58fd6f5a3cb1098720e8b1cc984f3841
|
refs/heads/master
| 2020-06-28T18:23:47.035981 | 2019-08-12T01:11:17 | 2019-08-12T01:11:17 | 200,307,560 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 48,
"blob_id": "bf01b6056b5dce8fa568d3e1e40e850b1fa7cb39",
"content_id": "2d82333086c4fe03d8c5b074b6f1fd25ff417d12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 50,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 1,
"path": "/README.md",
"repo_name": "ohwhatafool/Testing",
"src_encoding": "UTF-8",
"text": "\n## Practicing Software Testing and QA Automation\n"
},
{
"alpha_fraction": 0.7064676880836487,
"alphanum_fraction": 0.71517413854599,
"avg_line_length": 21.30555534362793,
"blob_id": "f16680952e7e52ac78518543b9f45fc5027119f2",
"content_id": "eb0c57bcc4836c5ba4b5277fa6c81a1f68959f53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 804,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 36,
"path": "/test.py",
"repo_name": "ohwhatafool/Testing",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\nimport time\ndriver = webdriver.Chrome()\n\n#go to facebook.com\ndriver.get('https://www.facebook.com/')\ntime.sleep(5)\n\n#make browser full screen\n# driver.maximize_window()\n\nemail_field = driver.find_element_by_id('email')\nemail_field.send_keys(\"[email protected]\")\n#time.sleep(3)\n\npss_field = driver.find_element_by_id('pass')\npss_field.send_keys('this_is_wrongpassword')\n#time.sleep(3)\n\n#click the login button\nlogin_button = driver.find_element_by_xpath('//*[@id=\"u_0_q\"]')\nlogin_button.click()\ntime.sleep(5)\n\nbody = driver.find_element_by_tag_name('body')\nall_text = body.text\n\n\nif \"Recover Your Account\" not in all_text:\n raise BaseException(\"The 'Recover your account' text is not found\")\nelse:\n print('The test case for login check has passed i.e. this test works')\n\n\n\ntime.sleep(10)\n\n"
}
] | 2 |
nguyenminh15988/DemoProject
|
https://github.com/nguyenminh15988/DemoProject
|
b700eed503ac863e7aaf75963715ddd42983533d
|
268f102c2607c7eba85b1e739ab011e4d6bb6493
|
1adb0599ada3423f6b88a946ca4bcad81c70f227
|
refs/heads/master
| 2023-06-03T16:08:52.735985 | 2021-06-20T06:44:45 | 2021-06-20T06:44:45 | 376,188,448 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.649068295955658,
"alphanum_fraction": 0.6511387228965759,
"avg_line_length": 19.14583396911621,
"blob_id": "0dd154c27a071993b62016c551b4878815c0e9b7",
"content_id": "138e7708d69bf2039df081b4194995fa068202c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 966,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 48,
"path": "/pythonLearning/trolyao.py",
"repo_name": "nguyenminh15988/DemoProject",
"src_encoding": "UTF-8",
"text": "import speech_recognition\nimport pyttsx3\nfrom datetime import date\n\n#khai bao bien\nai_listen = speech_recognition.Recognizer()\nai_talk = pyttsx3.init()\nai_brain = \"\"\n\nwhile True:\n\t#listen\n\twith speech_recognition.Microphone() as mic:\n\t\tprint(\"AI: i'm listening\")\n\t\taudio = ai_listen.listen(mic)\n\tprint(\"AI: ...\")\n\n\ttry:\n\t\tyou = ai_listen.recognize_google(audio)\n\texcept:\n\t\tyou = \"\"\n\tprint(\"You:\" + you)\n\n\t#AI\n\tif you == \"\":\n\t\tai_brain = \"I can't hear you, please try again\"\n\telif \"hello\" in you:\n\t\tai_brain = \"hello Minh dep trai\"\n\telif \"today\" in you:\n\t\ttoday = date.today()\n\t\tai_brain = today.strftime(\"%B %d, %Y\")\n\telif \"president\" in you:\n\t\tai_brain = \"Joe Biden\"\n\telif \"about\" in you:\n\t\tai_brain = \"You are handsome :)\"\n\telif \"bye\" in you:\n\t\tai_brain = \"Bye Minh dep trai\"\n\t\tai_talk.say(ai_brain)\n\t\tai_talk.runAndWait()\n\t\tbreak\n\telse:\n\t\tai_brain = \"I can't hear you, please try again\"\n\n\tprint(\"AI:\" + ai_brain)\n\n\n\t#talk\n\tai_talk.say(ai_brain)\n\tai_talk.runAndWait()"
},
{
"alpha_fraction": 0.49027636647224426,
"alphanum_fraction": 0.5056294798851013,
"avg_line_length": 13.984615325927734,
"blob_id": "d4cd59a613a0573ec63b9ae8dec5f8d4bf16e45f",
"content_id": "82ecdd073780a3e0d76c601b313b57e0e223b053",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 984,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 65,
"path": "/pythonLearning/test.py",
"repo_name": "nguyenminh15988/DemoProject",
"src_encoding": "UTF-8",
"text": "# person = {\n# 'name': 'Vũ Thanh Tài',\n# 'age': 22,\n# 'male': True,\n# 'status': 'alone' \n# }\n\n# del person ['status']\n\n# print(person)\n\n# name = \"nguyen tam minh\"\n# for i in name:\n# print(i)\n\n# name = \"nguyentamminh\"\n# for i in range(0,14):\n# for j in range(i,14):\n# print(j, end = \" \")\n# print(\"\")\n\nfor i in \"guyentaminh\":\n if i == \"n\":\n break\n print(i, end=\" \")\n\n# a=\"\"\n# def say(a):\n# a = \"Hello Minh\"\n# print(a)\n# say(a)\n\n# a = \"hello\"\n# def say():\n# global a\n# a = \"Minh dep trai\"\n# print(a)\n\n# say()\n# print(a)\n\n\ndef get_num(*num): #*num vi minh khong biet chinh xác bao nhiêu tham số truyền vào\n tmp = 0\n for i in num:\n tmp += i \n return tmp\n\nresult = get_num(1, 2, 3, 7, 8)\nprint(result)\n\n\ndef sum(a,b):\n return a / b\n\ntry:\n print(sum(6,0))\nexcept ZeroDivisionError:\n print('co loi xay ra')\nfinally:\n print('ngon lanh')\n\n\nstring = \"nguyentamminh\"\nprint(string.count('m'));\n\n\n\n"
},
{
"alpha_fraction": 0.7654867172241211,
"alphanum_fraction": 0.7654867172241211,
"avg_line_length": 24.22222137451172,
"blob_id": "f844afcefb99d46471dbd07d88a56cd69945baf4",
"content_id": "3a89d35894c14193d7a2171bc324b9a8e2c89c79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 226,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 9,
"path": "/pythonLearning/ai_listen.py",
"repo_name": "nguyenminh15988/DemoProject",
"src_encoding": "UTF-8",
"text": "import speech_recognition\n\nai_listen = speech_recognition.Recognizer()\nwith speech_recognition.Microphone() as mic:\n\tprint(\"AI: i'm listening\")\n\taudio = ai_listen.listen(mic)\n\nyou = ai_listen.recognize_google(audio)\nprint(you)"
},
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.62890625,
"avg_line_length": 20.41666603088379,
"blob_id": "8882127f5dfae9fc84a8b1330c8e58c92d0c6f05",
"content_id": "c144365a6315401b4641ba26d2c53ecf73cd03ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 256,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 12,
"path": "/pythonLearning/ai_brain.py",
"repo_name": "nguyenminh15988/DemoProject",
"src_encoding": "UTF-8",
"text": "you = \"hello\"\n\nif you == \"\":\n\tai_brain = \"I can't hear you, please try again\"\nelif you == \"hello\":\n\tai_brain = \"hello Minh dep trai\"\nelif you == \"today\":\n\tai_brain = \"hom nay la thu 6\"\nelse:\n\tai_brain = \"I can't hear you, please try again\"\n\nprint(ai_brain)"
},
{
"alpha_fraction": 0.6992481350898743,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 18,
"blob_id": "25be18e545069791b16568295a09ce9b1259d393",
"content_id": "8441fda1586a1bd477fa94060ee0b66eceb02970",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 133,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 7,
"path": "/pythonLearning/ai_talk.py",
"repo_name": "nguyenminh15988/DemoProject",
"src_encoding": "UTF-8",
"text": "import pyttsx3\n\nai_brain = \"i can't hear you, please try again\"\n\nai_talk = pyttsx3.init()\nai_talk.say(ai_brain)\nai_talk.runAndWait()\n"
}
] | 5 |
rakichan/pystuff
|
https://github.com/rakichan/pystuff
|
3f7b7121bf8e1c55ca1aa9ee9e63b25e54487a15
|
d3977a11c6d89b80836321700de1a05f3fd5f732
|
eb0e1ddbf29057e14318b9b99a82f02f29a8a85e
|
refs/heads/master
| 2020-12-03T09:16:20.337968 | 2017-10-03T20:18:34 | 2017-10-03T20:18:34 | 95,613,062 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6319715976715088,
"alphanum_fraction": 0.673534631729126,
"avg_line_length": 43.370967864990234,
"blob_id": "139540cc68408b87272ada5703519daf7f8d0b00",
"content_id": "ae709bd22d89ed8856cafe66773c5bcaab3f62e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2815,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 62,
"path": "/simpleForm/myForm.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\r\n# Form implementation generated from reading ui file 'myForm.ui'\r\n#\r\n# Created by: PyQt4 UI code generator 4.11.4\r\n#\r\n# WARNING! All changes made in this file will be lost!\r\n\r\nfrom PyQt4 import QtCore, QtGui\r\n\r\ntry:\r\n _fromUtf8 = QtCore.QString.fromUtf8\r\nexcept AttributeError:\r\n def _fromUtf8(s):\r\n return s\r\n\r\ntry:\r\n _encoding = QtGui.QApplication.UnicodeUTF8\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\r\nexcept AttributeError:\r\n def _translate(context, text, disambig):\r\n return QtGui.QApplication.translate(context, text, disambig)\r\n\r\nclass Ui_Dialog(object):\r\n def setupUi(self, Dialog):\r\n Dialog.setObjectName(_fromUtf8(\"Dialog\"))\r\n Dialog.resize(452, 198)\r\n self.label = QtGui.QLabel(Dialog)\r\n self.label.setGeometry(QtCore.QRect(30, 30, 46, 13))\r\n self.label.setObjectName(_fromUtf8(\"label\"))\r\n self.label_2 = QtGui.QLabel(Dialog)\r\n self.label_2.setGeometry(QtCore.QRect(30, 70, 46, 13))\r\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\r\n self.label_3 = QtGui.QLabel(Dialog)\r\n self.label_3.setGeometry(QtCore.QRect(30, 110, 46, 13))\r\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\r\n self.label_4 = QtGui.QLabel(Dialog)\r\n self.label_4.setGeometry(QtCore.QRect(30, 150, 46, 13))\r\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\r\n self.cityComboBox = QtGui.QComboBox(Dialog)\r\n self.cityComboBox.setGeometry(QtCore.QRect(100, 20, 321, 26))\r\n self.cityComboBox.setObjectName(_fromUtf8(\"cityComboBox\"))\r\n self.countyTextBrowser = QtGui.QTextBrowser(Dialog)\r\n self.countyTextBrowser.setGeometry(QtCore.QRect(100, 60, 321, 26))\r\n self.countyTextBrowser.setObjectName(_fromUtf8(\"countyTextBrowser\"))\r\n self.latitudeTextBrowser = QtGui.QTextBrowser(Dialog)\r\n self.latitudeTextBrowser.setGeometry(QtCore.QRect(100, 100, 321, 26))\r\n self.latitudeTextBrowser.setObjectName(_fromUtf8(\"latitudeTextBrowser\"))\r\n self.longitudeTextBrowser = QtGui.QTextBrowser(Dialog)\r\n self.longitudeTextBrowser.setGeometry(QtCore.QRect(100, 140, 321, 26))\r\n self.longitudeTextBrowser.setObjectName(_fromUtf8(\"longitudeTextBrowser\"))\r\n\r\n self.retranslateUi(Dialog)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog)\r\n\r\n def retranslateUi(self, Dialog):\r\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\", None))\r\n self.label.setText(_translate(\"Dialog\", \"City\", None))\r\n self.label_2.setText(_translate(\"Dialog\", \"County\", None))\r\n self.label_3.setText(_translate(\"Dialog\", \"Latitude\", None))\r\n self.label_4.setText(_translate(\"Dialog\", \"Longitude\", None))\r\n\r\n"
},
{
"alpha_fraction": 0.6301305890083313,
"alphanum_fraction": 0.6329290866851807,
"avg_line_length": 33.03174591064453,
"blob_id": "16c63017915d5d8d47a6143f1011fc4b19a259b1",
"content_id": "40373616d987d9524cd3a89acd7ac3befef6ce45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2144,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 63,
"path": "/blackframes.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "import os\nimport shutil\nimport subprocess\nimport tempfile\n\nfrom coreservices.exr import BlackExr\n\nimport Imath\n\ndef create(paths, res_x, res_y, image_extension, channels=(), verbose=False,\n extra_meta=None):\n \"\"\"create(paths, res_x, res_y, image_extension, channels=(), verbose=False)\n\n Create black (empty) images in the given resolution and image format at\n paths. Assumes current process has permission to write to each path\n specified in paths.\n\n\n The following only applies when creating an EXR image:\n\n channels: list of additional EXR channels that will be created for the\n black frame. 'R', 'G', 'B', 'A' and 'Z' are always written out.\n\n extra_meta: dictionary of additional metadata keys to write into the header\n\n \"\"\"\n if isinstance(paths, str):\n raise ValueError(\"'paths' arg must be a list of paths\")\n\n# # create a temp image in the correct resolution and format\n tmp_img = tempfile.mktemp(dir='/disk1/tmp', suffix='.'+image_extension)\n \n if image_extension.lower()=='exr': \n dataWindow = Imath.Box2i(Imath.point(0 ,0),Imath.point(res_x-1,res_y-1))\n displayWindow = dataWindow\n \n \n all_channels = ['R', 'G', 'B', 'A', 'Z']\n all_channels.extend(channels)\n \n #Create a blank single part image with the right size and channels filled with black\n img = BlackExr(tmp_img,dataWindow,displayWindow,all_channels,metaData=extra_meta)\n img.write()\n\n else: \n #non-exr case uses itconvert\n src_img = \"PATH_DELETED FOR SECURITY PURPOSES.%s\" % image_extension\n if not os.path.isfile(src_img):\n raise ValueError(\"No stock black image found for extension '%s'\" % image_extension)\n cmd = ['itconvert', src_img, '-resize', str(res_x), str(res_y), '-o', tmp_img]\n subprocess.check_call(cmd)\n \n \n # copy that image to each of the specified paths\n try:\n for path in paths:\n if verbose:\n print \"Creating\", path\n shutil.copy(tmp_img, path)\n except:\n pass\n finally:\n os.remove(tmp_img)\n"
},
{
"alpha_fraction": 0.5302102565765381,
"alphanum_fraction": 0.5360659956932068,
"avg_line_length": 29.544715881347656,
"blob_id": "2a06e99c80811bcf6f18c05e9b61b3c31fd2cf7c",
"content_id": "6853ecc074fb4e40338e9a4a90475cb75d28422d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3757,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 123,
"path": "/deleteShot",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n'''\ncommand line utility to delete a shot, remove all data and links\n'''\n\n\nimport os, sys, re\nimport argparse\nfrom subprocess import Popen, PIPE, STDOUT\n\nimport msg\n\n\ndef conform_seq_shot(seq, shot):\n '''\n make sure seq shot complies with our convention\n and returns proper sequence/shot\n @type seq: C{str}\n @param seq: sequence \n @type shot: C{str}\n @param shot: shot\n '''\n \n if re.search('[a-z]', seq):\n seq = str(seq)\n else:\n seq = '%04.1f' % float(seq)\n if re.search('[a-z]', shot):\n shot = str(shot)\n else:\n shot = '%06.2f' % float(shot)\n \n return seq, shot\n \n\ndef main() :\n '''\n core of program\n '''\n\n parser = argparse.ArgumentParser(description='Delete shot (all data).')\n\n parser.add_argument('--seq', dest = 'seq', help = 'sequence (required)')\n parser.add_argument('--shot', dest='shot', help='shot (required)')\n \n parsedArgs = parser.parse_args()\n\n seq = parsedArgs.seq\n shot = parsedArgs.shot\n \n # conforming seq/shot input to actual seq/shot convention\n if not seq or not shot:\n msg.postError(\"please provide sequence and shot (--help for more info)\")\n return \n seq, shot = conform_seq_shot(seq, shot)\n \n # make sure that the shot exist, prior to proceeding\n shot_dir = os.path.join(os.getenv('PRODROOT'),'work', 'Sequences', 'seq', seq, shot)\n if not os.path.isdir(shot_dir):\n msg.postError(\"shot: \" + seq + \" \" + shot + \" doesn't exist\")\n return\n \n # before going any further, we make sure we are running as lean\n user_id = os.getuid()\n if user_id != 3379:\n msg.postError(\"You are not 'lean', sudo as lean and run again.\")\n return\n\n # construct the path for remove commands\n rm_path1 = shot_dir.replace(\"work\", \"*\") + \"/*\"\n rm_path2 = shot_dir.replace(\"work/Sequences\", \"*\") + \"/*\"\n \n # confirm that you have sudo before proceeding\n sMsg = \"Are you sure you want to remove shot: \" + seq + \" \" + shot + \\\n \"\\nAll data for the shot will be lost. (y/n)?\"\n answer = raw_input(sMsg)\n \n if answer.lower() == \"y\":\n msg.postStatus(\"Removing shot... \" + seq + \" \" + shot)\n \n # building the remove command with lean\n sCmd = 'rm -rf ' + rm_path1 + '; rm -rf ' + rm_path2\n msg.postStatus(\"removing: \" + rm_path1)\n msg.postStatus(\"removing: \" + rm_path2)\n proc = Popen(\n sCmd,\n shell = True,\n stdout = PIPE,\n stderr = STDOUT,\n env = os.environ\n )\n proc.communicate()\n msg.postStatus(\"-\"*50)\n\n # now using linkman to remove the links from mkshot\n link_cmd = \"linkman --remove --path \"\n link_work_path = shot_dir\n link_rel_path = shot_dir.replace(\"work/Sequences\", \"rel\")\n link_repo_path = shot_dir.replace(\"work/Sequences\", \"repository\")\n msg.postStatus(\"removing link: \" + link_work_path)\n msg.postStatus(\"removing link: \" + link_rel_path)\n msg.postStatus(\"removing link: \" + link_repo_path)\n\n sCmd2 = link_cmd + link_work_path + \"; \" + \\\n link_cmd + link_rel_path + \"; \" + \\\n link_cmd + link_repo_path\n proc2 = Popen(\n sCmd2,\n shell = True,\n stdout = PIPE,\n stderr = STDOUT,\n env = os.environ\n )\n proc2.communicate()\n msg.postStatus(\"Done deleting shot.\")\n\n else:\n msg.postStatus(\"Nothing done, exiting.\")\n\n\nif __name__=='__main__':\n main()\n"
},
{
"alpha_fraction": 0.5818449854850769,
"alphanum_fraction": 0.5846068859100342,
"avg_line_length": 32.51852035522461,
"blob_id": "e0dc1deb7573df4413585c5a48583e5d02ebe40b",
"content_id": "3aa406afeceb9d19c0641bb50e6eb1948670e954",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5431,
"license_type": "no_license",
"max_line_length": 178,
"num_lines": 162,
"path": "/lighting_obr_gui.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "import os, subprocess\nfrom PyQt4 import QtGui, QtCore, uic\nfrom coreservices import prodmanUtils as pmu\nfrom rapfile import assetutils\nfrom rapfile.rapfilemgr import RapFileMgr\nfrom coreservices.contexts import daniContext\nfrom shotpublish import pipelineUtils\nimport msg\nimport danibb\n\n\nclass LightingObrTask(QtCore.QRunnable):\n\n def __init__(self, seq, shot, mem=56, spp=32, waves=8, xgen=True,\n xfilter=True, fml=True, mb=True, dof=True, maxVolumeWaves=1,\n frames=\"\", pool=None, halfRes=True, dirName=None):\n super(LightingObrTask, self).__init__()\n self.seq = seq\n self.shot = shot\n self.mem = mem \n self.spp = spp\n self.waves = waves \n self.xfilter = xfilter \n self.fml = fml \n self.mb = mb \n self.pool = pool\n self.dof = dof\n self.frames = frames\n self.xgen = xgen\n self.maxVolumeWaves = maxVolumeWaves\n self.halfRes = halfRes\n self.shotDir = dirName\n\n def run( self ):\n cmd = 'lighting_obr %(seq)s %(shot)s --memory %(mem)i --setSPP %(spp)i --setWave %(waves)i --maxVolumeWaves %(maxVolumeWaves)i --crossfilter %(xfilter)i ' % self.__dict__\n cmd = cmd.split()\n if self.fml:\n cmd.append(\"--fml\")\n if not self.mb:\n cmd.append(\"--noMB\")\n if not self.dof:\n cmd.append(\"--noDoF\")\n if self.pool:\n cmd.extend([\"--pool\", self.pool])\n if self.frames:\n framesStr = \"%s\" % self.frames\n cmd.extend([\"--frameRange\", framesStr])\n if not self.xgen:\n cmd.append(\"--noXgen\")\n if self.halfRes:\n cmd.append(\"--halfRes\")\n msg.postStatus(\"Sending OBR for %(seq)s-%(shot)s\" % self.__dict__)\n with daniContext.changeDani(self.shotDir):\n dbb = danibb.readIntoDict()\n subprocess.check_call(cmd)\n\n\nclass LightingObrDialog(QtGui.QDialog):\n\n\n def __init__( self, parent=None ):\n super(LightingObrDialog, self).__init__(parent)\n uic.loadUi(os.path.join(os.path.dirname(__file__), 'lighting_obr_gui.ui'), self)\n\n self.setWindowModality(QtCore.Qt.WindowModal)\n\n self._pool = QtCore.QThreadPool()\n self._pool.setMaxThreadCount(4)\n\n self._dbb = danibb.readIntoDict()\n self._show = self._dbb[\"d_show_name\"]\n self._seq = self._dbb.get(\"d_seq_name\", \"\")\n\n try:\n dept = \"\"\n dept = self._dbb[\"d_seq_dept_name\"]\n dept = self._dbb[\"d_shot_dept_name\"]\n except KeyError:\n pass\n finally:\n self._dept = dept\n\n self.seqComboBox.currentIndexChanged.connect(self.updateShots)\n self.showOOPBox.stateChanged.connect(self.updateSeqs)\n self.accepted.connect(self.renderSelectedShots)\n\n self.updateSeqs()\n\n\n def updateSeqs( self ):\n seq = self.seqComboBox.currentText() or self._seq\n self.seqComboBox.clear()\n showOOP = self.showOOPBox.isChecked()\n seqs = pmu.getSequenceList(OOP=showOOP)\n seqs.sort()\n self.seqComboBox.insertItems(0, seqs)\n idx = self.seqComboBox.findText(self._seq)\n if idx != -1:\n self.seqComboBox.setCurrentIndex(idx)\n\n\n def updateShots( self ):\n \n def isPublished( shot ):\n shotRapfile = msg.defrcvr.iStockroom.getShotPath(seq, shot)\n return os.path.exists(shotRapfile)\n\n self.shotList.clear()\n showOOP = self.showOOPBox.isChecked()\n seq = self.seqComboBox.currentText()\n if seq:\n seq = str(seq)\n shots = filter(isPublished, pmu.getShotList(seq, OOP=showOOP))\n shots.sort()\n self.shotList.insertItems(0, shots)\n\n\n def renderSelectedShots(self):\n seq = str(self.seqComboBox.currentText())\n if not seq:\n msg.postWarning(\"No sequence selected\")\n return\n\n shots = self.shotList.selectedItems()\n if not shots:\n msg.postWarning(\"No shots selected\")\n return\n\n fml = self.fmlBox.isChecked()\n frames = str(self.framesEdit.text()) if not fml else \"\"\n xfilter = int(self.xfilterBox.isChecked())\n mb = self.mbBox.isChecked()\n dof = self.dofBox.isChecked()\n mem = self.memBox.value() * 1024\n waves = self.wavesBox.value()\n spp = self.sppBox.value()\n xgen = self.xgenBox.isChecked()\n maxVolumeWaves = self.maxVolumes.value()\n halfRes = self.resolutionCheckBox.isChecked()\n codaPool = self._dept if (self._dept and self._dept != \"lighting\") else None\n isFoundation = self.foundationCheckBox.isChecked()\n if isFoundation:\n deptName = \"foundation\"\n else:\n deptName = self._dept\n\n for i, shot in enumerate(shots):\n shot = str(shot.text())\n shotDir = os.path.join(pipelineUtils.getShotWorkDir(seq, shot, \"Sequences\"), deptName)\n worker = LightingObrTask(seq, shot, mem, spp, waves, xgen,\n xfilter, fml, mb, dof, maxVolumeWaves, frames,\n pool=codaPool, halfRes=halfRes, dirName=shotDir)\n self._pool.start(worker)\n\n self._pool.waitForDone()\n msg.postStatus(\"all jobs sent\")\n\n\n\ndef lighting_obr_gui():\n dialog = LightingObrDialog()\n dialog.exec_()\n\n"
},
{
"alpha_fraction": 0.6139569282531738,
"alphanum_fraction": 0.6325166821479797,
"avg_line_length": 30.69411849975586,
"blob_id": "b80e17c3c4ee451868697c0515b3d22e6dae14d0",
"content_id": "16853f1e250ad29244dee14e78bf1a392b24ff7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2694,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 85,
"path": "/greyBg",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n'''\nTool to provide a gray background for various rendered images (e.g. tanim obrs,\nlook comps, etc.)\n\nInputs are the source images, the destination, and the frange to run. We use\n'oiiotool' to actually do the composite operation\n'''\n\nimport os\nimport subprocess\nimport argparse\nimport danibb\n\nif __name__ == '__main__':\n\n description = '''\n Tool to apply a 50 % gray background to source images and save the result \n in destination. Source is an image sequence in someDir/someName.#.exr format\n '''\n\n epilog = '''\n\n Examples:\n\n greyBg tanim.%04d.exr\n greyBg tanim.0129.exr\n greyBg tanim.#.exr --frameRange 1-10\n greyBg tanim.#.exr -f 1-10 --dest tanimOnGrey.#.exr\n '''\n\n parser = argparse.ArgumentParser(description=description, epilog=epilog, \\\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('srcPath', default=None,\n help='the path to the source images')\n parser.add_argument('-d', '--dest', dest='dstPath', default=None,\n help='the path to the destination images')\n parser.add_argument('-f', '--frameRange', dest='frange', default=None, \\\n help='Frame Range')\n args = parser.parse_args()\n\n\n if args.dstPath:\n dstPath = args.dstPath\n else:\n dstPath = args.srcPath\n if args.frange:\n frange = '--frames %s' % args.frange\n else:\n frange = ''\n\n # figure out the resolution and num channels of the input files. Use the \n # info option of oiiotool. the result has the following format: \n # tanim.0001.exr : 1920 x 804, 5 channel, half/half/half/half/float openexr\n # we need the 2nd, 4th, and 5th token\n cmd = 'oiiotool --info %s %s' % (frange, args.srcPath)\n try:\n result = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, \\\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)\n except subprocess.CalledProcessError as e:\n print 'Failed: %s' % e\n sys.exit(1)\n except OSError:\n print 'oiiotool Not found, quitting'\n sys.exit(1)\n\n # only care about the first line\n results = result.stdout.readline().split()\n res = '%sx%s' % (results[2], results[4])\n numChans = results[5]\n\n # convert the files now\n cmd = 'oiiotool %s %s --pattern' \\\n ' constant:color=0.2176,0.2176,0.2176,1 %s %s --over -o %s' % \\\n (frange, args.srcPath, res, numChans, dstPath)\n\n try:\n subprocess.check_call(cmd, shell=True)\n except subprocess.CalledProcessError as e:\n print 'Failed: %s' % e\n pass\n except OSError:\n print 'oiiotool Not found, quitting'\n pass\n"
},
{
"alpha_fraction": 0.633730411529541,
"alphanum_fraction": 0.6366503238677979,
"avg_line_length": 33.38554382324219,
"blob_id": "b058c775ba558b776e921a667c342e6958656741",
"content_id": "aa5c146ed6670b32db503acbd97b9f201b441397",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8562,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 249,
"path": "/missingVariants",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n\"\"\"\nmissingVariants\n\nCompare what variants are in shotgun vs rapfile for all elements.\nPresent the user with a GUI and the option to (additive) sync rapfile\nwith shotgun.\n - variants in rapfile will only be pushed to shotgun, none are deleted\n\"\"\"\n\n\n\nfrom PyQt4.QtCore import Qt\nfrom PyQt4.QtGui import (QLabel, QPushButton, QVBoxLayout, QWidget, QGridLayout, QFont, QMessageBox,\n QApplication, QListWidget, QListWidgetItem, QScrollArea, QMainWindow)\nimport sys\nimport argparse\nimport msg\nimport time\nimport elementsdb\nfrom coreservices import prodmanUtils\nfrom assethelpers import asset_helpers\nimport err\nimport multiprocessing\nfrom multiprocessing.pool import Pool\nfrom coreservices.prodmanUtils import ElementPublish\n\n\ndef parseArguments():\n parser = argparse.ArgumentParser(prog=\"missingVariants\",\n description=('Compare all in-picture element variants in shotgun vs rapfiles'))\n parser.add_argument(\"-c\", \"--category\", nargs='+',\n help=(\"Element category, by default all categories are used. Valid options include \"\n \"Camera, Character, Character Prop, Set Prop, Crowd, FX, Light\"))\n return parser.parse_args()\n\n\nclass CheckListWidget(QWidget):\n \"\"\"\n Sub-widget of checkboxes for missing variants\n \"\"\"\n def __init__(self, itemList):\n super(CheckListWidget, self).__init__()\n layout = QVBoxLayout()\n self.list = QListWidget()\n layout.addWidget(self.list)\n layout.addStretch()\n self.setLayout(layout)\n\n self.addItems(itemList)\n\n def addItems(self, itemList):\n for i in sorted(itemList):\n item = QListWidgetItem(i)\n item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)\n item.setCheckState(Qt.Unchecked)\n self.list.addItem(item)\n self.list.setMinimumHeight(self.list.sizeHintForRow(0)*(self.list.count()+.5))\n\n def getCheckedItems(self):\n return [str(self.list.item(c).text()) for c in range(self.list.count()) if self.list.item(c).checkState()]\n\n\nclass CategoryWidget(QWidget):\n \"\"\"\n Sub-widget to display category name, and all elements/variants within that category\n \"\"\"\n def __init__(self, categoryName, categoryDict):\n super(CategoryWidget, self).__init__()\n layout = QVBoxLayout()\n\n categoryLabel = QLabel(categoryName)\n categoryLabel.setAlignment(Qt.AlignCenter)\n categoryLabel.setStyleSheet(\"QLabel { background-color : blue; color : white; font: bold 14px; }\")\n font = QFont()\n font.bold()\n categoryLabel.setFont(font)\n layout.addWidget(categoryLabel)\n\n self.grid = QGridLayout()\n self.grid.setColumnMinimumWidth(0, 160)\n self._populateWidget(categoryDict)\n layout.addLayout(self.grid)\n\n self.setLayout(layout)\n\n def _populateWidget(self, categoryDict):\n for index, elem in enumerate(sorted(categoryDict)):\n # Element name\n self.grid.addWidget(QLabel(elem), index, 0, Qt.AlignRight)\n\n # Variants list\n list = CheckListWidget(categoryDict[elem])\n self.grid.addWidget(list, index, 1)\n\n def commitSelected(self):\n found = 0\n for row in range(self.grid.rowCount()):\n element = str(self.grid.itemAtPosition(row,0).widget().text())\n list = self.grid.itemAtPosition(row, 1).widget()\n variants = list.getCheckedItems()\n\n if variants:\n shotgunEvent = ElementPublish(element, 'Look', \"missingVariants::publish to shotgun\")\n shotgunEvent.addVariantList(variants)\n shotgunEvent.publish()\n found += len(variants)\n\n return found\n\nclass DisplayWidget(QWidget):\n \"\"\"\n Main widget visible in the MissingVariantsUI\n \"\"\"\n def __init__(self, category, parent=None):\n super(DisplayWidget, self).__init__()\n\n self.category = category\n layout = QVBoxLayout()\n\n scroll = QScrollArea()\n scroll.setWidgetResizable(True)\n\n dummy = QWidget()\n self.mainLayout = QVBoxLayout()\n\n self.missingFromShotgun = {}\n self._populateWidget()\n\n dummy.setLayout(self.mainLayout)\n scroll.setWidget(dummy)\n layout.addWidget(scroll)\n\n # Commit Button\n commitButton = QPushButton(\"Publish Checked Variants to Shotgun\")\n commitButton.clicked.connect(self._commitSelectedToShotgun)\n layout.addWidget(commitButton)\n\n self.setLayout(layout)\n\n def _populateWidget(self):\n self._findMissingVariants()\n self._populateList()\n\n\n def _findMissingVariants(self):\n \"\"\"\n Populate dict of variants missing in shotgun but present in rapfile\n \"\"\"\n context = \"missingVariants::findMissingVariants\"\n msg.postStatus(\"Searching for missing variants... This will take a few minutes. Grab some coffee :)\", context)\n\n startTime = time.time()\n processing_pool = Pool(8)\n manager = multiprocessing.Manager()\n queue = manager.Queue()\n\n for elem in elementsdb.getElements(inPicture=True):\n if elem.startswith('m_'):\n # We can skip master sets - they have no variant\n continue\n\n processing_pool.apply_async(_findMissingVariantsForElement, args=(elem, self.category, queue,),\n callback=self._processMissingVariants)\n\n processing_pool.close()\n processing_pool.join()\n endTime = time.time()\n msg.postStatus(\"Search took about %d minutes\"%int((endTime-startTime)/60), context)\n\n def _processMissingVariants(self, queue):\n\n elem, missingVars = queue.get()\n if missingVars:\n category = prodmanUtils.getElementInfo(elem)['pm_category']\n if category not in self.missingFromShotgun:\n self.missingFromShotgun[category] = {}\n\n self.missingFromShotgun[category][elem] = missingVars\n\n\n def _populateList(self):\n \"\"\"\n Populate the GUI with the elements/variants missing from shotgun\n \"\"\"\n for category in sorted(self.missingFromShotgun):\n self.mainLayout.addWidget(CategoryWidget(category, self.missingFromShotgun[category]))\n\n def _commitSelectedToShotgun(self):\n \"\"\"\n Commit the selected missing element/variants to shotgun\n Alert the user, and close the application\n \"\"\"\n publishCount = 0\n for idx in range(self.mainLayout.count()):\n publishCount += self.mainLayout.itemAt(idx).widget().commitSelected()\n\n ret = QMessageBox.information(self, \"Complete!\", \"Published %d variants to Shotgun.\" % publishCount,\n QMessageBox.Ok, QMessageBox.Ok)\n self.parent().close()\n\n\ndef _findMissingVariantsForElement(elem, category, queue):\n\n difference = []\n shotgun_category = prodmanUtils.getElementInfo(elem)['pm_category']\n if category and shotgun_category not in category:\n pass\n else:\n try:\n shotgunVars = set(prodmanUtils.getElementVariants(elem))\n rapfileVars = set(asset_helpers.get_variants(elem))\n difference = list(rapfileVars.difference(shotgunVars))\n except Exception as error:\n msg.postWarning(\"Could not find element: %s\" % elem, 'missingVariants')\n\n\n queue.put((elem, difference))\n return queue\n\n\nclass MissingVariantsUI(QMainWindow):\n \"\"\"\n UI used to display the elements with variants missing from shotgun\n \"\"\"\n def __init__(self, category):\n super(MissingVariantsUI, self).__init__()\n self.setWindowTitle(\"Missing Variants\")\n main = DisplayWidget(category, self)\n self.setCentralWidget(main)\n self.setMinimumWidth(500)\n self.setMinimumHeight(300)\n\n\nif __name__ == \"__main__\":\n pargs = parseArguments()\n category = pargs.category\n if category:\n for cat in category:\n if cat not in [\"Camera\", \"Character\", \"Character Prop\", \"Set Prop\", \"Crowd\", \"FX\", \"Light\"]:\n msg.postError('Invalid category \"%s\". Category must be one of the following options: '\n 'Camera, Character, Character Prop, Set Prop, Crowd, FX, Light' % cat, 'missingVariants') \n sys.exit()\n\n app = QApplication(sys.argv)\n window = MissingVariantsUI(category)\n window.show()\n sys.exit(app.exec_())\n"
},
{
"alpha_fraction": 0.782608687877655,
"alphanum_fraction": 0.782608687877655,
"avg_line_length": 10.5,
"blob_id": "33ffc4c234bfa1fc0a00c55c9a1addd6dc891365",
"content_id": "14c23c01d2ba80065b27b7ce80eb8a09b3defd5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 23,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 2,
"path": "/README.md",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "# pystuff\nPython Codes\n"
},
{
"alpha_fraction": 0.6949303150177002,
"alphanum_fraction": 0.7032315731048584,
"avg_line_length": 28.133928298950195,
"blob_id": "dfa05199ca8a277bf253a0d4f25f14e6578008af",
"content_id": "284f8a2e28cc2ab10fdc062fcf7b5f8ef66caa58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3373,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 112,
"path": "/lss.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\r\n'''\r\nScript to display a summary of files in the directory.\r\nDisplays number of files, filename and summary of frameranges\r\n\r\nUSAGE:\r\npython lss.py -d \\path\\to\\dir\r\n\r\nBUGs:\r\n1. Doesnt support if the filename has underscore before the framenumber\r\n'''\r\n__author__ = 'Rakesh Ramesh'\r\n\r\nimport glob\r\nimport re, os\r\nimport argparse\r\nfrom itertools import groupby\r\nfrom collections import Counter\r\n\r\n\r\n\r\nsequencetypes = ['*.rgb', '*.exr', \".jpg\"]\r\nnonSequenceTypes = ['*.xml', '*.info']\r\n\r\ndef getFilesByExtension(ext_type):\r\n\t'''seperating files based on extension type'''\r\n\tfilesList = []\r\n\tfor files in ext_type:\r\n\t\tfilesList.extend(glob.glob(files))\r\n\treturn filesList\r\n\r\ndef frameRangeSummary(nums):\r\n\t'''gets the summary of frame numbers'''\r\n\tranges = []\r\n\tfor n in nums:\r\n\t\tif not ranges or n > ranges[-1][-1] + 1:\r\n\t\t\tranges += [],\r\n\t\tranges[-1][1:] = n,\r\n\treturn ['-'.join(map(str, r)) for r in ranges]\r\n\r\ndef extractFilenameAndFrame(seqFiles):\r\n\textension = []\r\n\tfilenameAndFrame = []\r\n\tfor seqFile in seqFiles:\r\n\t\textension.append(seqFile.rsplit(\".\", 1))\r\n\tfor fname in extension:\r\n\t\tfilenameAndFrame.append([item[::-1] for item in fname[0][::-1].split('.', 1)][::-1])\r\n\treturn filenameAndFrame\r\n\r\ndef getFrameNumbers(seqFiles):\r\n\tframeNumberList = []\r\n\tfilenameAndFramenumberList = extractFilenameAndFrame(seqFiles)\r\n\tfor i in filenameAndFramenumberList:\r\n\t\tframeNumberList.append(i[1])\r\n\treturn frameNumberList\r\n\r\ndef seperateRGB(seqFiles):\r\n\t'''\r\n\tReturns a dictionary with key as sequence filename with no extension and frame number\r\n\tand values as a list of respective sequence files\r\n\t'''\r\n\tfilenameAndFrame = extractFilenameAndFrame(seqFiles)\r\n\tfnameAndFramesDict={}\r\n\tseqFilename =[]\r\n\tfor i in filenameAndFrame:\r\n\t\tseqFilename.append(i[0])\r\n\tseqFilename = list(set(seqFilename))\r\n\tfor j in seqFilename:\r\n\t\tfnameAndFramesDict[j]=[i for i in seqFiles if j in i]\r\n\treturn fnameAndFramesDict\r\n\t\r\ndef convertFramerange(seqInfo):\r\n\t'''\r\n\tReturns a dictionary with key as sequence filename with no extension and frame number\r\n\tand values as framerange summary\r\n\t'''\r\n\tseqfilecount = []\r\n\tpadding =[]\r\n\tfor key, value in seqInfo.iteritems():\r\n\t\tframeNumbers = getFrameNumbers(value)\r\n\t\tpadding.append(len(frameNumbers[0]))\r\n\t\tseqInfo[key] = frameRangeSummary(map(int, frameNumbers))\r\n\t\tseqfilecount.append(len(value))\r\n\treturn seqInfo, [seqfilecount, padding]\r\n\r\ndef countOccurences(files):\r\n\treturn dict(Counter(files))\r\n\r\ndef getExtension(seqFiles):\r\n\treturn seqFiles[0].split(\".\")[-1]\r\n\r\nif __name__ == '__main__':\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument('-d', '--directory', dest = 'dir', help='enter a path', action='store')\r\n\targs = parser.parse_args()\r\n\tif os.path.exists(args.dir):\r\n\t\tos.chdir(args.dir)\r\n\r\n\tsequenceFiles = getFilesByExtension(sequencetypes)\r\n\r\n\tnonSequenceFiles = getFilesByExtension(nonSequenceTypes)\r\n\tnonSeqFilesCounter = countOccurences(nonSequenceFiles)\r\n\r\n\tseperatedseq = seperateRGB(sequenceFiles)\r\n\tfileseqAndFrameRangeSummary, seqfileinfo = convertFramerange(seperatedseq)\r\n\r\n\ti=0\r\n\tfor key, value in fileseqAndFrameRangeSummary.iteritems():\r\n\t\tprint '%s' %(str(seqfileinfo[0][i])) + '%27s' %(key) + \".%0\" + str(seqfileinfo[1][i]) + \".\" + getExtension(sequenceFiles) + '%30s' %(\" \".join(str(x) for x in value))\r\n\t\ti+=1\r\n\tfor x in nonSeqFilesCounter:\r\n\t\tprint '%s %34s' %(nonSeqFilesCounter[x], x)"
},
{
"alpha_fraction": 0.6578616499900818,
"alphanum_fraction": 0.6584905385971069,
"avg_line_length": 35.86046600341797,
"blob_id": "8c6ee6ce4daf0f09fdb5ffa1a44cfe5a12cbbe16",
"content_id": "3121226c503758ebf75daa0df01f6a15475dbb50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1590,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 43,
"path": "/convert2ptx",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n'''\nMust be run in the directory that has the OBJ files in it, and a 'conv'\ndirectory \n\n'''\n\nimport os, sys, errno, msg\nimport danibb, dwd\nimport subprocess\nimport sys\nfrom argparse import ArgumentParser\n\nfrom modeltools.convert2ptx import *\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(description=\n \"\"\"For converting tif file textures from zbrush into ptex files\n usable in the pipeline. This program performs a point cloud\n transfer of OBJ and .tif file data saved in the 'conv' directory\n and then cleans up after itself. Output is saved in a\n 'zbrush_color' folder, unless you specify -o (overwrite), in which\n case files will go in the element's 'Color_base' area.\"\"\")\n \n parser.add_argument('-o', '--overwrite', default=False,\n help='If you want to overwrite Color_base and displacement texture dirs.')\n args = parser.parse_args()\n overwrite = args.overwrite\n \n # gather all of the appropriate data to begin execution\n workdir, texdir = checkToExecute()\n objlist = [{}, {}, {}, {}]\n dirList = getOutputDir(overwrite, texdir)\n infolist = cleanupConversionDir(workdir)\n objInfo = getOBJFiles(workdir)\n\n # iterate through collected data and convert ptx files.\n for i in range(len(infolist)):\n objlist[i]= pairTexturesWithObjs(infolist[i], objInfo)\n for obj, tiff in objlist[i].items():\n convertPtex(tiff, obj, dirList[i], False)\n print \"\\nItem completed. Output Directory is:\\n\" + dirList[i]\n \n"
},
{
"alpha_fraction": 0.7184849977493286,
"alphanum_fraction": 0.7190502882003784,
"avg_line_length": 28.483333587646484,
"blob_id": "513f00c70d9c637e121a7720cbbc7b92c3ce8f1d",
"content_id": "d03798b409dbdb97130eab68cefec1799b9f0985",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1769,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 60,
"path": "/simpleForm/launch.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "'''\nCreate a simple GUI of city information of California\n\tSee attached JSON file (ca.json), which contains information of all cities in CA\n\tUse the data abstract from the JSON file to create a simple GUI for it\n\tThe GUI should have a filter function based on the selection of city name (selectable)\n\tDisplay information of county full name, latitude, longitude \n\tSample GUI is shown below\n\tUse any python library as needed\n'''\nimport sys\nfrom PyQt4 import QtCore, QtGui\nfrom myForm import Ui_Dialog\nimport json\n\nCITY_INFORMATION = 'ca.json'\t# for now its hardcoded\n\nclass cityInformation(QtGui.QDialog):\n\t'''\n\tBuilds the UI and populates from the json data\n\t'''\n\tdef __init__(self, parent=None):\n\t\tQtGui.QWidget.__init__(self, parent)\n\t\tself.ui = Ui_Dialog()\n\t\tself.ui.setupUi(self)\n\t\tself.setWindowTitle(\"City Information\")\n\t\tself.populate()\n\n\t\tself.ui.cityComboBox.activated[int].connect(self.onActivated)\n\n\tdef populate(self):\n\t\t'''\n\t\tTo populate the combo box with the \n\t\tcity names from the json file\n\t\t'''\n\t\ttry:\n\t\t\twith open(CITY_INFORMATION) as dataFile:\n\t\t\t\tself.data = json.load(dataFile)\n\t\t\t\t# populate the combobox\n\t\t\t\tfor item in self.data:\n\t\t\t\t\tself.currText = item['name']\n\t\t\t\t\t# print self.currText\n\t\t\t\t\tself.ui.cityComboBox.addItem(self.currText)\n\t\texcept IOError:\n\t\t\tprint \"The file is missing\"\n\t\t\tsys.exit()\n\n\tdef onActivated(self, i):\n\t\t'''\n\t\tUpon item selection, the onactivated method is called\n\t\t'''\n\t\tself.ui.countyTextBrowser.setText(self.data[i]['county_name'])\n\t\tself.ui.latitudeTextBrowser.setText(self.data[i]['primary_latitude'])\n\t\tself.ui.longitudeTextBrowser.setText(self.data[i]['primary_longitude'])\n\t\n\nif __name__ == \"__main__\":\n\t\tapp = QtGui.QApplication(sys.argv)\n\t\tmyapp = cityInformation()\n\t\tmyapp.show()\n\t\tsys.exit(app.exec_())\n"
},
{
"alpha_fraction": 0.6264248490333557,
"alphanum_fraction": 0.6336787343025208,
"avg_line_length": 31.16666603088379,
"blob_id": "6a0717389678d1f2b039cbde051f8e38d319c60a",
"content_id": "85618abbc0db803642b101174e0074fca0929d88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1930,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 60,
"path": "/levelSetPreviewCAF.py",
"repo_name": "rakichan/pystuff",
"src_encoding": "UTF-8",
"text": "\"\"\"\nDebug File: Loads the Preview-Caf from the temprel/latest/cafPreview area\n\"\"\"\nimport os\nimport msg\nfrom rapfilecore import assetutils\n\ndef addPreviewScene():\n \"\"\"Adds the prviewcaf to the maya scene\"\"\"\n seq = os.getenv(\"NAV_SEQ\")\n shot = os.getenv(\"NAV_SHOT\")\n temprel = \"<PATH GOES HERE>\"\n path = \"{0}/{1}/{2}/levelSetFiles/latest/cafPreview/\".format(temprel, seq, shot)\n\n #Get Element\n scene = msg.defrcvr.iSceneMgr.getCurrentScene()\n elements = scene.getElements()\n masterSet = None\n namespacedName = \"\"\n for i in elements:\n if not i.getProperty(\"OOS\"):\n if i.getName().endswith(\"Ocean\"):\n #MasterSet\n namespacedName = i.getNamespace()\n if i.getNamespace().startswith(\"m_\"):\n masterSet = True\n namespace, elementName = namespacedName.split(\".\")\n\n else:\n elementName = i.getName()\n\n if masterSet:\n elementFullName = \"{0}:{1}:{0}_{0}_{1}.caf\".format(namespace, elementName, seq, shot)\n\n else:\n elementFullName = \"{0}:_{0}_{1}.caf\".format(elementName, seq, shot)\n\n\n cafPath = os.path.join(path, elementFullName)\n print cafPath\n\n if not os.path.isfile(cafPath):\n msg.postWarning(\"There is no levelSetCache - Caf {0}\".format(cafPath))\n return\n else:\n msg.postStatus(\"Loading - Caf {0}\".format(cafPath))\n\n elem = assetutils.findAssetByNamespace(scene, namespacedName)\n\n currentVariant = elem.getVariant()\n elem.setLoadFile(cafPath, variant=currentVariant, varProp='preview')\n elem.setLoadFileValue('preview')\n elem = assetutils.findAssetByNamespace(scene, namespacedName)\n\n #Invoke Refresh\n elem.setProperty(\"drawMode\", \"Unloaded\")\n elem.setProperty(\"drawMode\", \"Maya+Voodoo\")\n msg.postStatus(\"Updated Preview Caf for element: {0}\".format(elem.getNamespace()))\n\naddPreviewScene()\n"
}
] | 11 |
laondev12/Vision
|
https://github.com/laondev12/Vision
|
d44eb033e82fc9c9507647da49cfdb55c9eeafcf
|
42f070244d59d0ee78704f4f6c6aa645ff0f1669
|
e2eb8476ed297d0db8b6f0f404bbfe0d80f174d9
|
refs/heads/master
| 2020-05-26T01:40:43.484041 | 2019-05-21T07:22:35 | 2019-05-21T07:22:35 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5744563341140747,
"alphanum_fraction": 0.5928860902786255,
"avg_line_length": 29.917646408081055,
"blob_id": "53a6dbb1960eb3f8b974b09cb2229c47ad52b7fc",
"content_id": "563f27e3ef9f54d80a6e1b91e36fa4b4faf82661",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5426,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 170,
"path": "/4. Optical Character Recognition for Localization/ResNet_v1.py",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "# Reference Code: https://keras.io/examples/cifar10_resnet/\r\n# Modified by Inyong Hwang\r\n# Character level STR with ResNet Version 1\r\n\r\nimport keras\r\nfrom keras.layers import Dense, Conv2D, BatchNormalization, Activation\r\nfrom keras.layers import AveragePooling2D, Input, Flatten\r\nfrom keras.optimizers import Adam\r\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\r\nfrom keras.callbacks import ReduceLROnPlateau\r\nfrom keras.regularizers import l2\r\nfrom keras.models import Model\r\nimport numpy as np\r\nimport os\r\nimport pickle\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n# Load Dataset\r\nDatasets_Path = 'C:/Users/Inyong/Documents/PycharmProjects/STR/Dataset/PKL'\r\nDatasets = os.listdir(Datasets_Path)\r\n\r\nLabel = []\r\nX = []\r\nY = []\r\n\r\nfor Dataset in Datasets:\r\n Dataset_Path = Datasets_Path + '/' +Dataset\r\n with open(Dataset_Path, 'rb') as f:\r\n Data = pickle.load(f)\r\n if 'label' in Dataset:\r\n Label.extend(Data)\r\n elif 'X' in Dataset:\r\n X.extend(Data)\r\n else:\r\n Y.extend(Data)\r\n f.close()\r\n\r\nX = np.array(X)\r\nX = X[:, :, :, np.newaxis]\r\n\r\nY = np.array(Y)\r\n\r\nt = keras.preprocessing.text.Tokenizer(lower=False)\r\nt.fit_on_texts(Y)\r\nY = t.texts_to_sequences(Y)\r\nClasses = len(t.word_index)\r\nY = keras.utils.to_categorical(Y, Classes+1)\r\n\r\nX_Train, X_Test, Y_Train, Y_Test = train_test_split(X, Y, test_size=0.2, random_state=37, shuffle=True)\r\nX_Train = X_Train.astype('float32') / 255\r\nX_Test = X_Test.astype('float32') / 255\r\nX_Train_Mean = np.mean(X_Train, axis=0)\r\nX_Train -= X_Train_Mean\r\nX_Test -= X_Train_Mean\r\n\r\ndel X, Y, Dataset_Path, Datasets_Path, Datasets, Dataset, Data, f, Label\r\n\r\nprint('x_train shape:', X_Train.shape)\r\nprint(X_Train.shape[0], 'train samples')\r\nprint(X_Test.shape[0], 'test samples')\r\nprint('y_train shape:', Y_Train.shape)\r\n\r\n# Define Model\r\nversion = 1\r\nn = 9\r\ndepth = n * 6 + 2\r\ninput_shape = X_Train.shape[1:]\r\nbatch_size = 128\r\nepochs = 200\r\nmodel_type = 'ResNet%dv%d' % (depth, version)\r\n\r\n\r\ndef lr_schedule(epoch):\r\n lr = 1e-3\r\n if epoch > 180:\r\n lr *= 0.5e-3\r\n elif epoch > 160:\r\n lr *= 1e-3\r\n elif epoch > 120:\r\n lr *= 1e-2\r\n elif epoch > 80:\r\n lr *= 1e-1\r\n print('Learning rate: ', lr)\r\n return lr\r\n\r\n\r\ndef resnet_layer(inputs,\r\n filters=16,\r\n kernel_size=3,\r\n strides=1,\r\n activation='relu',\r\n batch_normalization=True,\r\n conv_first=True):\r\n conv = Conv2D(filters=filters,\r\n kernel_size=kernel_size,\r\n strides=strides,\r\n padding='same',\r\n kernel_initializer='he_normal',\r\n kernel_regularizer=l2(1e-4))\r\n x = inputs\r\n if conv_first:\r\n x = conv(x)\r\n if batch_normalization:\r\n x = BatchNormalization()(x)\r\n if activation is not None:\r\n x = Activation(activation)(x)\r\n else:\r\n if batch_normalization:\r\n x = BatchNormalization()(x)\r\n if activation is not None:\r\n x = Activation(activation)(x)\r\n x = conv(x)\r\n return x\r\n\r\n\r\ndef resnet_v1(input_shape=input_shape,\r\n depth=depth,\r\n classes=Classes):\r\n filters = 16\r\n resnet_blocks = int((depth - 2) / 6)\r\n inputs = Input(shape=input_shape)\r\n x = resnet_layer(inputs=inputs)\r\n for stack in range(3):\r\n for resnet_block in range(resnet_blocks):\r\n strides = 1\r\n if stack > 0 and resnet_block == 0:\r\n strides = 2\r\n y = resnet_layer(inputs=x, filters=filters, strides=strides)\r\n y = resnet_layer(inputs=y, filters=filters, activation=None)\r\n if stack > 0 and resnet_block == 0:\r\n x = resnet_layer(inputs=x, filters=filters, kernel_size=1, strides=strides, activation=None, batch_normalization=False)\r\n x = keras.layers.add([x, y])\r\n x = Activation('relu')(x)\r\n filters *= 2\r\n x = AveragePooling2D(pool_size=8)(x)\r\n y = Flatten()(x)\r\n outputs = Dense(classes+1, activation='softmax', kernel_initializer='he_normal')(y)\r\n model = Model(inputs=inputs, outputs=outputs)\r\n return model\r\n\r\n\r\nmodel = resnet_v1(input_shape=input_shape, depth=depth)\r\nmodel.compile(loss='categorical_crossentropy', optimizer=Adam(lr=lr_schedule(0)), metrics=['accuracy'])\r\nmodel.summary()\r\nprint(model_type)\r\n\r\n# Save\r\nsave_dir = os.path.join(os.getcwd(), 'saved_models')\r\nmodel_name = 'STR_%s_model.{epoch:03d}.hg' % model_type\r\nif not os.path.isdir(save_dir):\r\n os.makedirs(save_dir)\r\nfilepath = os.path.join(save_dir, model_name)\r\ncheckpoint = ModelCheckpoint(filepath=filepath,\r\n monitor='val_acc',\r\n verbose=1,\r\n save_best_only=True)\r\n\r\nlr_scheduler = LearningRateScheduler(lr_schedule)\r\n\r\nlr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),\r\n cooldown=0,\r\n patience=5,\r\n min_lr=0.5e-6)\r\n\r\ncallbacks = [checkpoint, lr_reducer, lr_scheduler]\r\n\r\nmodel.fit(X_Train, Y_Train, batch_size=batch_size, epochs=epochs, verbose=1, callbacks=callbacks, validation_split=0.2)\r\nscores = model.evaluate(X_Test, Y_Test, verbose=1)\r\nprint('Test loss:', scores[0])\r\nprint('Test accuracy:', scores[1])\r\n"
},
{
"alpha_fraction": 0.5837801694869995,
"alphanum_fraction": 0.5945039987564087,
"avg_line_length": 31.155555725097656,
"blob_id": "cf5f31534d9a0d3f0edcf8469099e504cce0a6bb",
"content_id": "6cff6c7c0dd5d4cf557960ea17cd0c31932cdb76",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1492,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 45,
"path": "/4. Optical Character Recognition for Localization/Dataset_Read_EMNIST.py",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Author: Inyong Hwang\r\n# EMNIST convert png to numpy array\r\n\r\nimport os\r\nimport cv2\r\nimport pickle\r\nfrom tqdm import tqdm\r\n\r\nDataset_Path = 'C:/Users/Inyong/Documents/PycharmProjects/STR/Dataset/EMNIST'\r\nfilenames = os.listdir(Dataset_Path)\r\n\r\nlabel_ASCII = []\r\nlabel_EMNIST = []\r\n\r\nfor filename in filenames:\r\n label_ASCII.append(filename)\r\n label_EMNIST.append(chr(int(filename, 16)))\r\n\r\nX_Train_EMNIST = []\r\nY_Train_EMNIST = []\r\n\r\nfor _, i in tqdm(enumerate(label_ASCII)):\r\n Directory_Path = Dataset_Path + '/' + i\r\n dirnames = os.listdir(Directory_Path)\r\n for dirname in tqdm(dirnames):\r\n Images_Path = Dataset_Path + '/' + i + '/' + dirname\r\n if 'mit' in Images_Path:\r\n pass\r\n else:\r\n filenames = os.listdir(Images_Path)\r\n for filename in filenames:\r\n Image_Path = Images_Path + '/' + filename\r\n # print(Image_Path, chr(int(i, 16)))\r\n Image = cv2.imread(Image_Path, cv2.IMREAD_UNCHANGED)\r\n Image = cv2.resize(Image, dsize=(64, 64), interpolation=cv2.INTER_AREA)\r\n X_Train_EMNIST.append(Image)\r\n Y_Train_EMNIST.append(chr(int(i, 16)))\r\n\r\ndel Dataset_Path, filename, filenames, i, Images_Path, Image_Path, Image, _, label_ASCII, dirname, dirnames\r\n\r\nfor d in ['X_Train_EMNIST', 'Y_Train_EMNIST', 'label_EMNIST']:\r\n exec('with open(\"{}\"+\".pkl\",\"wb\") as f: pickle.dump({},f)'.format(d, d))\r\n\r\nprint(\"Done!\")\r\n"
},
{
"alpha_fraction": 0.5980861186981201,
"alphanum_fraction": 0.6267942786216736,
"avg_line_length": 28.585365295410156,
"blob_id": "edee0989d3ebcc1800289c4cabb915f33f9cba89",
"content_id": "4cd90c40b3445cfb0f68a39aaa683a281c2f888b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1254,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 41,
"path": "/4. Optical Character Recognition for Localization/Dataset_Read_PHD08.py",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n# Author: Inyong Hwang\r\n# PHD08 convert png to numpy array\r\n\r\nimport os\r\nimport cv2\r\nimport numpy as np\r\nimport pickle\r\nfrom tqdm import tqdm\r\n\r\nDataset_Path = 'C:/Users/Inyong/Documents/PycharmProjects/STR/Dataset/PHD08'\r\nfilenames = os.listdir(Dataset_Path)\r\n\r\nlabel_PHD08 = []\r\n\r\nfor filename in filenames:\r\n label_PHD08.append(filename)\r\n\r\nX_Train_PHD08 = []\r\nY_Train_PHD08 = []\r\n\r\nfor _, i in tqdm(enumerate(label_PHD08)):\r\n Images_Path = Dataset_Path + '/' + i\r\n filenames = os.listdir(Images_Path)\r\n for filename in tqdm(filenames):\r\n Image_Path = Images_Path + '/' + filename\r\n # print(Images_Path, i)\r\n stream = open(Image_Path.encode(\"utf-8\"), \"rb\")\r\n byte = bytearray(stream.read())\r\n array = np.asarray(byte, dtype=np.uint8)\r\n Image = cv2.imdecode(array, cv2.IMREAD_GRAYSCALE)\r\n Image = cv2.resize(Image, dsize=(64, 64), interpolation=cv2.INTER_LINEAR)\r\n X_Train_PHD08.append(Image)\r\n Y_Train_PHD08.append(i)\r\n\r\ndel Dataset_Path, filename, filenames, i, Images_Path, Image_Path, Image, _\r\n\r\nfor d in ['X_Train_PHD08', 'Y_Train_PHD08', 'label_PHD08']:\r\n exec('with open(\"{}\"+\".pkl\",\"wb\") as f: pickle.dump({},f)'.format(d, d))\r\n\r\nprint(\"Done!\")\r\n"
},
{
"alpha_fraction": 0.5863401889801025,
"alphanum_fraction": 0.624355673789978,
"avg_line_length": 27.218181610107422,
"blob_id": "4755e815674c395c05292ee22c5ce9073264f427",
"content_id": "9c4d0d1731cec97e93321cfd84f628c3cb69a86f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1552,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 55,
"path": "/2. Vanishing Point to Control Posture/rbf_kernel.py",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "'''\nInyong Hwang\n\n# References\n# Python\n# array call: https://stackoverflow.com/questions/3582601/how-to-call-an-element-in-a-numpy-array\n# Matlab to Python: https://docs.scipy.org/doc/numpy-1.15.0/user/numpy-for-matlab-users.html\n# Matlab to Python: http://mathesaurus.sourceforge.net/matlab-numpy.html\n# numpy.arange: https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.arange.html\n# Matalb\n# RBF Kernel: https://kr.mathworks.com/matlabcentral/fileexchange/63033-svm-using-various-kernels\n# Function: https://kr.mathworks.com/help/matlab/ref/function.html\n# ETC\n# CS231n Korean: http://aikorea.org/cs231n/python-numpy-tutorial/\n'''\n\nimport numpy as np\n# import scipy as sp\nimport math as m\nimport matplotlib.pyplot as plt\n\ndef func_1(k):\n k = k + 1e-6*np.identity(n)\n ck = np.linalg.cholesky(k)\n f = ck*np.random.standard_normal(n,)\n return f\n\ndef func_2(x, i, j, constant, gamma):\n k[i, j] = constant * m.exp(((-1) * (abs(x[i] - x[j])) ** 2) / gamma)\n return k[i, j]\n\nx = np.arange(-10, 10, 0.2)\nn = np.size(x)\nk = np.zeros((n, n))\nconstant = 1\nconstnat = constant**2\nsigma = 1\ngamma = 2*(sigma**2)\n\n'''\nfor i in range(1, n+1):\n for j in range(1, n+1):\n for sigma in range(1, 6):\n for constant in range(1, 6):\n k[i,j] = constant*m.exp(((-1)*(x[i]-x[j])^2)/gamma)\n'''\nfor i in range(1, n):\n for j in range(1, n):\n # k[i, j] = constant * m.exp(((-1) * (abs(x[i] - x[j])) ** 2) / gamma)\n k[i, j] = func_2(x, i, j, constant, gamma)\n\nf = func_1(k)\n\nplt.plot(x, f)\nplt.show()\n"
},
{
"alpha_fraction": 0.684636116027832,
"alphanum_fraction": 0.684636116027832,
"avg_line_length": 17.549999237060547,
"blob_id": "f02855b8f30b99b509fe74a7219cd62c8e0904f7",
"content_id": "a646d6e5959dd9c0df2cd8abaa9ba29afae1d5e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 371,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 20,
"path": "/Install/Keras-ReinforcementLearning.md",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "## I. Install Keras Reinforcement Learning\n\nReference: https://github.com/keras-rl/keras-rl\n\n### i. Activate Targer Virtual Environment\n```\n> activate tensorflow\n```\n\n### ii-A. Install with Pypi (pip)\n```\n> pip install keras-rl\n```\n\n### ii-B. Install from Github source\n```\n> git clone https://github.com/keras-rl/keras-rl.git\n> cd keras-rl\n> python setup.py install\n```\n"
},
{
"alpha_fraction": 0.6766238212585449,
"alphanum_fraction": 0.7144842147827148,
"avg_line_length": 59.61052703857422,
"blob_id": "8ee7ba8d6ceb2829d25f6c74c6ba2f948f328955",
"content_id": "8b171363c879f13ef0dc824214b6873c3d7e2c53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5758,
"license_type": "no_license",
"max_line_length": 332,
"num_lines": 95,
"path": "/README.md",
"repo_name": "laondev12/Vision",
"src_encoding": "UTF-8",
"text": "# Vision Processing\nOpenCV & Python & TensorFlow & Keras\n\n## I. Dehazing to Object Detection (Human & Fire) (TODO)\n\n### i. Image Processing with OpenCV\n\n#### Human detection with RPi [Github](https://github.com/OmalPerera/Human-detection-system-with-raspberry-Pi/blob/master/pi_surveillance.py)\n#### HOG detectMultiScale [Korean](http://hamait.tistory.com/509), [English](https://www.pyimagesearch.com/2015/11/16/hog-detectmultiscale-parameters-explained/)\n#### Dark Channel Prior [Github](https://github.com/anhenghuang/dehaze), [Paper](http://www.robots.ox.ac.uk/~vgg/rg/papers/hazeremoval.pdf)\n\n### ii. Deep Learning\n\n#### A. Dataset [Reference](https://www.researchgate.net/post/Is_there_exists_any_haze_fog_dust_smog_removal_images_data-set_with_ground_truth_images)\n\n#### a. [RESIDE: V0 (REalistic Single Image DEhazing)](https://sites.google.com/view/reside-dehaze-datasets/reside-v0), [Paper (arXiv)](https://arxiv.org/pdf/1712.04143.pdf), [Paper (IEEE)](https://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=8451944)\n#### b. [I-Haze](http://www.vision.ee.ethz.ch/ntire18/i-haze/), [Paper (arXiv)](https://arxiv.org/abs/1804.05091)\n#### c. [D-Hazy(X)](http://www.meo.etc.upt.ro/AncutiProjectPages/D_Hazzy_ICIP2016/), [Paper (IEEE)](https://ieeexplore.ieee.org/document/7532754)\n#### d. O-Haze [Paper (arXiv)](https://arxiv.org/abs/1804.05101)\n\n### iii. Challenge\n#### [NTIRE2018](http://www.vision.ee.ethz.ch/ntire18/)\n\n## II. Vanishing Point to Control Posture\nImage Processing\n\n## III. Depth to Obstacle Avoidance (TODO)\n\n### i. Deep Learning\n\n#### A. Dataset\n\n#### a. [NYU Dataset V1](https://cs.nyu.edu/~silberman/datasets/nyu_depth_v1.html), [Paper](https://cs.nyu.edu/~silberman/papers/indoor_seg_struct_light.pdf)\n#### b. [NYU Dataset V2](https://cs.nyu.edu/~silberman/datasets/nyu_depth_v2.html), [Paper](https://cs.nyu.edu/~silberman/papers/indoor_seg_support.pdf)\n#### How to read NYU mat file with python [Korean Blog](https://ddokkddokk.tistory.com/21)\n#### Packages [scikit-image](http://scikit-image.org/docs/dev/install.html) [matplotlib](https://matplotlib.org/users/installing.html)\n```\n> pip install scikit-image\n> python -m pip install -U matplotlib\n```\n#### Change Code for Windows/OS X [Github issue](https://github.com/scikit-image/scikit-image/issues/2595)\n```\nimport skimage.io as io\n```\nto \n```\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom skimage import io\nio.use_plugin('matplotlib')\n```\n#### c. RGBD Dataset [Reference](http://www.open3d.org/docs/tutorial/Basic/rgbd_images/index.html#)\n\n#### B. Model\n\n#### a. FCRN [Paper (arXiv)](https://arxiv.org/abs/1606.00373), [Github](https://github.com/iro-cp/FCRN-DepthPrediction)\n\n## IV. Optical Character Recognition to Path Planning (TODO)\n\n### i. Tesseract [Github](https://github.com/tesseract-ocr/tesseract), [Demo](http://tesseract.projectnaptha.com/)\n\n#### A. pytesseract [Github](https://github.com/madmaze/pytesseract), [pip](https://pypi.org/project/pytesseract/)\n```\n> pip install pytesseract\n```\n\n#### B. Install Windows Version [Github](https://github.com/tesseract-ocr/tesseract/wiki#windows), [Download](https://github.com/UB-Mannheim/tesseract/wiki) \n#### Tesseract training [Github](https://github.com/tesseract-ocr/tesseract/wiki/TrainingTesseract-4.00)\n##### Variable-size Graph Specification Language (VGSL) [Github](https://github.com/tesseract-ocr/tesseract/wiki/VGSLSpecs)\n##### StreetView Tensorflow Recurrent End-to-End Transcription (STREET) [Github](https://github.com/tensorflow/models/tree/master/research/street)\n#### OCR Korean [Korean Blog](https://m.blog.naver.com/samsjang/220694855018)\n#### Remove spaces [Korean Blog](https://hashcode.co.kr/questions/692/%EC%8A%A4%ED%8A%B8%EB%A7%81%EC%97%90-%EB%AA%A8%EB%93%A0-%EA%B3%B5%EB%B0%B1-%EB%AC%B8%EC%9E%90%EB%A5%BC-%EC%A0%9C%EA%B1%B0%ED%95%98%EA%B3%A0-%EC%8B%B6%EC%9D%80%EB%8D%B0-%EC%95%9E-%EB%92%A4-%EA%B3%B5%EB%B0%B1%EB%A7%8C-%EC%A0%9C%EA%B1%B0%EB%90%A9%EB%8B%88%EB%8B%A4)\n#### Once you change the route, you need to turn off and restart Pycharm.\n#### Remove special characters [Korean Blog](https://niceman.tistory.com/156)\n#### Tesseract Optimal conditions [Korean Blog](https://creaby.tistory.com/17)\n#### Color Reversal [Korean Blog](https://076923.github.io/posts/Python-opencv-11/)\n```\nimage = cv2.bitwise_not(input_image)\n```\n#### Resize [Korean Blog](https://076923.github.io/posts/Python-opencv-8/)\n```\nimage = cv2.resize(input_image, dsize=(0, 0), fx=0.3, fy=0.7, interpolation=cv2.INTER_LINEAR)\n```\n----------------------------------------------------------------------------------------------------\n## Install\n### i. [Install OpenCV on Computer](https://github.com/inyong37/Vision/blob/master/Install/OpenCV-Computer.md)\n### ii. [Install OpenCV on Raspberry Pi](https://github.com/inyong37/Vision/blob/master/Install/OpenCV-RaspberryPi.md)\n### iii. [Install TensorFlow CPU on Computer](https://github.com/inyong37/Vision/blob/master/Install/TensorFlow-Computer-CPU.md)\n### iv. [Install TensorFlow GPU on Computer](https://github.com/inyong37/Vision/blob/master/Install/TensorFlow-Computer-GPU.md)\n### v. [Install & Uninstall TensorFlow on Raspberry Pi](https://github.com/inyong37/Vision/blob/master/Install/TensorFlow-RaspberryPi.md)\n### vi. [Install Keras](https://github.com/inyong37/Vision/blob/master/Install/Keras.md)\n### vii. [Install Keras Reinforcement Learning](https://github.com/inyong37/Vision/blob/master/Install/Keras-ReinforcementLearning.md)\n### viii. [Install Pytorch](https://github.com/inyong37/Vision/blob/master/Install/Pytorch.md)\n### ix. [Install Theano](https://github.com/inyong37/Vision/blob/master/Install/Theano.md)\n### x. [Virtual Environment with Conda](https://github.com/inyong37/Vision/blob/master/Install/Virtual-Environment_conda.md)\n"
}
] | 6 |
ZhangPeterGree/TerminalCompareHex
|
https://github.com/ZhangPeterGree/TerminalCompareHex
|
b4ef38d2325ad31c3d1cc16d04132955699ea0af
|
969fe6c5a54910ba6d44fac6ffdfbde24abcde41
|
f1793c04b7ddee7c77492e80fc96d9aaa8796315
|
refs/heads/master
| 2023-06-27T22:15:51.623379 | 2020-11-25T04:04:12 | 2020-11-25T04:04:12 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5485475659370422,
"alphanum_fraction": 0.5724602937698364,
"avg_line_length": 29.242717742919922,
"blob_id": "e992225be6b8f0bedc90468351a21ab5921acb17",
"content_id": "8b1d791a4bdf3e826b5f7c4ec5f85a3074ed8e12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6231,
"license_type": "no_license",
"max_line_length": 466,
"num_lines": 206,
"path": "/OrangeHexCompare_No_Emoji.py",
"repo_name": "ZhangPeterGree/TerminalCompareHex",
"src_encoding": "UTF-8",
"text": "# Der3k Burrola\n# July 2020\n# Orange Hex Compare\n\nimport binascii\nimport os\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\n\n\nclass ByteHolder():\n\tbyteValue = ''\n\tbyteColor = \"\\033[92m\"\n\tbyteOffset = -1\n\tbyteNextOffset = -1\n\tbyteFake = False\n \n#-------------------\n\nRED = \"\\033[91m\"\nBLACK = \"\\033[92m\"\n\ndef createByteObject(value, offset, isFake):\n\tbt = ByteHolder()\n\tbt.byteValue = value\n\tbt.byteOffset = hex(offset)\n\tbt.byteNextOffset = hex(offset+1)\n\tbt.byteFake = isFake\n\treturn bt\n\ndef getHexOf(file):\n\thexString = []\n\tisBlank = False\n\tx = 0\n\twith open(file, 'rb') as f:\n\t\twhile(not isBlank):\n\t\t\t# Reads one byte at a time\n\t\t\tcontent = f.read(1)\n\t\t\t# Converts to hex then to useable string\n\t\t\tpw_bytes = binascii.hexlify(content)\n\t\t\tpw_bytes = pw_bytes.decode(\"utf-8\")\n\n\t\t\tif(pw_bytes != ''):\t\n\t\t\t\tbt = createByteObject(pw_bytes, x, False)\n\t\t\t\thexString.append(bt)\n\t\t\t\tx = x + 1\n\t\t\telse:\n\t\t\t\tisBlank = True\n\treturn hexString\n\n# takes a file in & then returns an array of arrays for the length of the file\ndef getHexOfInArray(file):\n\thexString = []\n\thexStringLine = []\n\tisBlank = False\n\tlineAmount = 0\n\twith open(file, 'rb') as f:\n\t\twhile(not isBlank):\n\t\t\t#Read one byte at a time\n\t\t\tcontent = f.read(1)\n\t\t\t# Converts to hex then to useable string\n\t\t\tpw_bytes = binascii.hexlify(content)\n\t\t\tpw_bytes = pw_bytes.decode(\"utf-8\")\n\n\t\t\t# Takes 16 bytes\n\t\t\tif(lineAmount != 16):\n\t\t\t\t# Add byte to an array\n\t\t\t\thexStringLine.append(pw_bytes)\n\t\t\t\tlineAmount = lineAmount + 1\n\t\t\telse:\n\t\t\t\t# add array to final array\n\t\t\t\thexString.append(hexStringLine)\n\t\t\t\t# Clear temp values\n\t\t\t\thexStringLine.clear()\n\t\t\t\tlineAmount = 0\n\t\t\t# When the last byte is blank break out of while loop\n\t\t\tif(pw_bytes == ''):\n\t\t\t\tisBlank = True\n\treturn hexString\t\n\n\n\ndef pickFile():\n\tprint()\n\tTk().withdraw()\n\tfile = askopenfilename()\n\treturn getHexOf(file)\n\ndef compareFiles(file1, file2):\n\tinfo = []\n\ttextInfo = ''\n\tcount = 0\n\tfor i in range(len(file1)):\n\t\tif(file1[i].byteValue != file2[i].byteValue and not file1[i].byteFake and not file2[i].byteFake):\n\t\t\tcount = count + 1\n\t\t\tfile1[i].byteColor = RED\n\t\t\tfile2[i].byteColor = RED\n\t\t\tcompareString = 'File 1: ' + file1[i].byteColor + file1[i].byteValue + BLACK + ' vs File 2: ' + file1[i].byteColor + file2[i].byteValue + BLACK\n\t\t\tfullString = 'Byte at: ' + file1[i].byteColor + file1[i].byteOffset + BLACK + ' are different! ' + compareString\n\t\t\ttextInfo = textInfo + 'Byte at: ' + file1[i].byteOffset + ' are different! ' + 'File 1 Value: ' + file1[i].byteValue + ' vs File 2 Value: ' + file2[i].byteValue + '\\n'\n\t\t\tprint(fullString)\n\tinfo.append(textInfo)\n\tinfo.append(count)\n\treturn info\n\ndef saveToString(data, file, i, ending):\n\thexString = data + file[i].byteColor + file[i].byteValue + \"\\033[92m\" + ending\n\treturn hexString\n\ndef displayBothFilesInHex(file1, file2):\n\thexString = ''\n\thexString1 = ''\n\thexString2 = ''\n\tlargerFile = len(file1) if len(file1) > len(file2) else len(file2)\n\tfor i in range (largerFile):\n\t\tif(i==0):\n\t\t\thexString = str(file1[i].byteOffset) + '\\t'\n\t\thexString1 = saveToString(hexString1, file1, i, '')\n\t\thexString2 = saveToString(hexString2, file2, i, '')\n\t\tif((i+1)%4==0):\n\t\t\thexString1= hexString1 + ' '\n\t\t\thexString2= hexString2 + ' '\n\t\tif((i+1)%16==0 or i==len(file1)-1):\n\t\t\tif(i==len(file1)-1):\n\t\t\t\thexString = hexString + (hexString1 + ' | ' + hexString2) + '\\n'\n\t\t\telse:\t\n\t\t\t\thexString = hexString + (hexString1 + ' | ' + hexString2) + '\\n' + str(file1[i].byteNextOffset) + '\\t'\n\t\t\t\thexString1 = ''\n\t\t\t\thexString2 = ''\n\tprint('File 1: | File 2:')\n\tprint(hexString)\n\ndef fixAlignmentof(file1, file2):\n\t#?? Add blank characters at end of file1 if line doesn't align\n\tfiles = []\n\t# blank characters at end of files if they are different sizes\n\tif(len(file1) != len(file2)):\n\t\tif(len(file1) > len(file2)):\n\t\t\tsizeToAdd = len(file1) - len(file2)\n\t\t\tfor x in range(sizeToAdd):\n\t\t\t\tbt = createByteObject(' ', x, True)\n\t\t\t\tfile2.append(bt)\n\t\tif(len(file1) < len(file2)):\n\t\t\tsizeToAdd = len(file2) - len(file1)\n\t\t\tfor x in range(sizeToAdd):\n\t\t\t\tbt = createByteObject(' ', x, True)\n\t\t\t\tfile1.append(bt)\n\tfiles.append(file1)\n\tfiles.append(file2)\n\treturn files\n\ndef writeDifferencesToText(file1, file2):\n\ttext_file = open(\"Diffrences.txt\", \"w\")\n\tdifferences = compareFiles(file1, file2)[0]\n\tos.system('clear')\n\ttoText = ''\n\tfor i in differences:\n\t\ttoText = toText + i\n\tn = text_file.write(toText)\n\ttext_file.close()\n\tprint('\\nSuccessfully exported to Differences.txt')\n\ndef main():\n\tfile1Hex = pickFile()\n\tfile2Hex = pickFile()\n\tfiles =\tfixAlignmentof(file1Hex, file2Hex)\n\tfile1Hex = files[0]\n\tfile2Hex = files[1]\n\tisRunning = True\n\twhile(isRunning):\n\t\tprint('_______________________')\n\t\tprint(' Orange HexCompare ')\n\t\tprint('_______________________\\n')\n\t\tprint('Select an option from below')\n\t\tprint('[1] Display files side-by-side')\n\t\tprint('[2] Display differences only')\n\t\tprint('[3] Export differences to text file')\n\t\tprint('[4] Exit')\n\t\tanswer = str(input())\t\t\n\t\tos.system('clear')\n\n\t\tif(answer == '1'):\n\t\t\tprint('--------------------------')\n\t\t\tprint(' File Comparison ')\n\t\t\tprint('--------------------------\\n')\n\t\t\tdisplayBothFilesInHex(file1Hex, file2Hex)\n\t\t\tprint('\\n\\n-------------------\\n\\n')\n\t\tif(answer == '2'):\n\t\t\tprint('--------------------------')\n\t\t\tprint(' Offset Differences ')\n\t\t\tprint('--------------------------\\n')\n\t\t\tprint('\\nNumber of differences: ' + str(compareFiles(file1Hex, file2Hex)[1]))\n\t\t\tprint('\\n\\n-------------------\\n\\n')\n\t\tif(answer == '3'):\n\t\t\twriteDifferencesToText(file1Hex, file2Hex)\n\t\t\tprint('\\n\\n-------------------\\n\\n')\n\t\tif(answer == '4'):\n\t\t\tprint('\\n\\n-------------------\\n\\n')\n\t\t\tprint('Good-bye')\n\t\t\tisRunning = False\n\t\tif(answer == 'Easter Egg'):\n\t\t\tprint('*********************************\\n*** ****** ***** **** ***********\\n*** ****** ********** ************\\n*** ****** ***** **** **** ** *\\n*** ****** ***** **** **** ** *\\n*** ***** **** ***********\\n*** ****** ***** **** *** ***** *\\n*** ****** ***** **** **** *\\n*** ****** ***** **** ***********\\n*** ****** ***** **** ***********\\n*** ****** ***** ****************\\n*** ****** ***** **** ***********\\n*********************************')\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n"
},
{
"alpha_fraction": 0.6795443296432495,
"alphanum_fraction": 0.7077761292457581,
"avg_line_length": 24.506328582763672,
"blob_id": "8907a3d7260c5aa8595b44cf9d5a5683ca8d00e9",
"content_id": "a3d332d49ec2bfeb491104c0a8ee7e9e8ee5fa67",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2019,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 79,
"path": "/OrangeHexCompare.py",
"repo_name": "ZhangPeterGree/TerminalCompareHex",
"src_encoding": "UTF-8",
"text": "# Der3k Burrola\n# July 2020\n# Orange Hex Compare\n\nimport codeBase, os, kivy\nfrom kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.graphics import *\nfrom kivy.uix.scrollview import ScrollView\nfrom kivy.lang import Builder \n\n\ndef orange_layout(self):\n\t\n\ts = ScrollView()\n\tscreen = BoxLayout(orientation='horizontal')\n\tleftFileScreen = BoxLayout(orientation='vertical')\n\trightFileScreen = BoxLayout(orientation='vertical')\n\tfor i in range (10):\n\t\tb = Label(text='Test' + str(i), size_hint_y=None, height=40)\n\t\tb2 = Button(text='Test' + str(i), size_hint_y=None, height=40)\n\t\tleftFileScreen.add_widget(b)\n\t\trightFileScreen.add_widget(b2)\n\t\tscreen.height += leftFileScreen.height\n\n\tscreen.add_widget(leftFileScreen)\n\tscreen.add_widget(rightFileScreen)\n\ts.add_widget(screen)\n\treturn s\n\n\tfile1Hex = codeBase.pick_file()\n\tfile2Hex = codeBase.pick_file()\n\tfiles = codeBase.format_files_in_hex(file1Hex,file2Hex)\n\tfile1Hex = files[0]\n\tfile2Hex = files[1]\n\thexCount = files[2]\n\n\tlayout = GridLayout(cols=5)\n\tlayout.add_widget(Label(text=hexCount, size_hint_x=None, width=50))\n\n\tseparatorLabel = Label(size_hint_x=None, width=3)\n\twith separatorLabel.canvas:\n Color(1, 1, 1, 1)\n Rectangle(pos=(42,0), size=(3,1000))\n\tlayout.add_widget(separatorLabel)\n\n\tlayout.add_widget(Label(text=file1Hex, markup=True, pos_hint={'top':0}))\n\tseparatorLabel2 = Label(size_hint_x=None, width=3)\n\twith separatorLabel2.canvas:\n Color(1, 1, 1, 1)\n Rectangle(pos=(415, 0), size=(3,1000))\n\tlayout.add_widget(separatorLabel2)\n\tlayout.add_widget(Label(text=file2Hex, markup=True))\n\t\n\n\n\n\t\n\n\t#return layout\n\n\nclass MyApp(App):\n\n\tdef build(self):\n\t\tself.title = codeBase.ORANGE_EMOJI + 'Orange HexCompare' + codeBase.ORANGE_EMOJI\n\t\tlayout = orange_layout(self)\n\t\t\n\t\tself.root =Builder.load_file('Screens.kv')\n\t\treturn self.root\n\n \n\n\nif __name__ == '__main__':\n MyApp().run()\n\n\n\n\n"
},
{
"alpha_fraction": 0.6529731750488281,
"alphanum_fraction": 0.6724817156791687,
"avg_line_length": 25.13725471496582,
"blob_id": "56cb37c574c2e26cb1ccf49ad97346e6b1dc922f",
"content_id": "9a924e18633cd42061eba16a7f41be4ef2dc4387",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5331,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 204,
"path": "/codeBase.py",
"repo_name": "ZhangPeterGree/TerminalCompareHex",
"src_encoding": "UTF-8",
"text": "import binascii\nimport emoji\nimport binascii\nimport os\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\n\nRED = '[color=ff0000]'\nBLACK = '[color=ffffff]'\nORANGE_EMOJI = emoji.emojize(':tangerine:')\n\nclass ByteHolder():\n\tbyteValue = ''\n\tbyteColor = BLACK\n\tbyteOffset = -1\n\tbyteNextOffset = -1\n\t# This is a byte that was created as a filler when one file is longer than another\n\tbyteFake = False\n \n#-------------------\n\ndef get_hex_of(file):\n\thexString = []\n\tisBlank = False\n\tx = 0\n\twith open(file, 'rb') as f:\n\t\twhile(not isBlank):\n\t\t\t# Reads one byte at a time\n\t\t\tcontent = f.read(1)\n\t\t\t# Converts to hex then to useable string\n\t\t\tpw_bytes = binascii.hexlify(content)\n\t\t\tpw_bytes = pw_bytes.decode(\"utf-8\")\n\n\t\t\tif(pw_bytes != ''):\t\n\t\t\t\tbt = create_byte_object(pw_bytes.upper(), x, False)\n\t\t\t\thexString.append(bt)\n\t\t\t\tx = x + 1\n\t\t\telse:\n\t\t\t\tisBlank = True\n\treturn hexString\n\n# takes a file in & then returns an array of arrays for the length of the file\ndef getHexOfInArray(file):\n\thexString = []\n\thexStringLine = []\n\tisBlank = False\n\tlineAmount = 0\n\tdeleteThisCount = 0\n\n\twith open(file, 'rb') as f:\n\t\twhile(not isBlank):\n\t\t\t#Read one byte at a time\n\t\t\tcontent = f.read(1)\n\t\t\t# Converts to hex then to useable string\n\t\t\tpw_bytes = binascii.hexlify(content)\n\t\t\tpw_bytes = pw_bytes.decode(\"utf-8\")\n\n\t\t\t# Takes 16 bytes\n\t\t\tif(lineAmount != 16):\n\t\t\t\t# Add byte to an array\n\t\t\t\thexStringLine.append(pw_bytes)\n\t\t\t\tlineAmount = lineAmount + 1\n\t\t\telse:\n\t\t\t\t# add array to final array\n\t\t\t\thexString.append(hexStringLine)\n\t\t\t\tif (deleteThisCount == 0):\n\t\t\t\t\tprint(hexStringLine)\n\t\t\t\t\tprint(hexString[0])\n\t\t\t\t\tdeleteThisCount = 1\n\t\t\t\t# Clear temp values\n\t\t\t\thexStringLine.clear()\n\t\t\t\tlineAmount = 0\n\t\t\t# When the last byte is blank break out of while loop\n\t\t\tif(pw_bytes == ''):\n\t\t\t\tisBlank = True\n\n\tprint(hexString[0])\n\treturn hexString\t\n\ndef getHexOfInDictionary(file):\n\thexStringDict = {}\n\tisBlank = False\n\tbyteCount = 0\n\n\twith open(file, 'rb') as f:\n\t\twhile(not isBlank):\n\t\t\t# Read one byte at a time\n\t\t\tcontent = f.read(1)\n\t\t\t# Convert to hex then to useable string\n\t\t\tpw_bytes = binascii.hexlify(content)\n\t\t\tpw_bytes = pw_bytes.decode(\"utf-8\")\n\n\t\t\t#hexStringDict.update({str(byteCount), pw_bytes})\n\t\t\thexStringDict[str(byteCount)] = pw_bytes\n\t\t\tbyteCount = byteCount + 1\n\n\t\t\t# When the lastdbye is blank, break out of while loop\n\t\t\tif(pw_bytes == ''):\n\t\t\t\tisBlank = True\n\treturn getHexForScreen(hexStringDict)\n\n# Separates the Dictionary of a file into an array\ndef getHexForScreen(fileDictionary):\n\thexString = []\n\thexStringLine = hex(0) + '\\t\\t'\n\tcount = 0\n\tfor i in range(len(fileDictionary)):\n\t\tif(count != 16):\n\t\t\t# Separates each section by 4 bytes with a space\n\t\t\tif(count == 4 or count ==8 or count ==12):\n\t\t\t\thexStringLine = hexStringLine + ' '\n\t\t\thexStringLine = hexStringLine + fileDictionary[str(i)]\n\t\t\tcount = count + 1\n\t\telse:\n\t\t\t# makes sure the first offset is 0 instead of current i\n\t\t\tif(i > 20):\n\t\t\t\thexStringLine = hex(i-1) + '\\t\\t' + hexStringLine\n\t\t\t# makes all upper case in order to keep similar size for characters\n\t\t\thexStringLine = hexStringLine.upper()\n\t\t\t# Add current line to the array\n\t\t\thexString.append(hexStringLine)\n\t\t\t# Reset parameters for next line\n\t\t\thexStringLine = ''\n\t\t\tcount = 0\n\treturn hexString\n\ndef pick_file():\n\tprint()\n\tTk().withdraw()\n\tfile = askopenfilename()\n\treturn getHexOfInDictionary(file)\n\n\ndef pick_file_old():\n\tTk().withdraw()\n\tfile = askopenfilename()\n\treturn get_hex_of(file)\n\ndef create_byte_object(value, offset, isFake):\n\tbt = ByteHolder()\n\tbt.byteValue = value\n\tbt.byteOffset = hex(offset)\n\tbt.byteNextOffset = hex(offset+1)\n\tbt.byteFake = isFake\n\treturn bt\n\ndef save_to_string(data, file, i, ending):\n\thexString = data + file[i].byteColor + file[i].byteValue + '[/color]' + ending\n\treturn hexString\n\n\n\ndef spot_differences(file1,file2):\n\tfiles = []\n\tfor i in range(len(file1)):\n\t\tif(file1[i].byteValue != file2[i].byteValue and not file1[i].byteFake and not file2[i].byteFake):\n\t\t\tfile1[i].byteColor = RED\n\t\t\tfile2[i].byteColor = RED\n\tfiles.append(file1)\n\tfiles.append(file2)\n\treturn files\n\n\ndef format_files_in_hex(file1, file2):\n\tfiles = []\n\t# Adds blank characters at end of file to make both files same size\n\tif(len(file1) != len(file2)):\n\t\tif(len(file1) > len(file2)):\n\t\t\tsizeToAdd = len(file1) - len(file2)\n\t\t\tfor x in range(sizeToAdd):\n\t\t\t\tbt = create_byte_object(' ', x, True)\n\t\t\t\tfile2.append(bt)\n\t\tif(len(file1) < len(file2)):\n\t\t\tsizeToAdd = len(file2) - len(file1)\n\t\t\tfor x in range(sizeToAdd):\n\t\t\t\tbt = create_byte_object(' ', x, True)\n\t\t\t\tfile1.append(bt)\n\n\t# Shows the differences between the files\n\tfilesWithDifferences = spot_differences(file1, file2)\n\thexString1 = filesWithDifferences[0]\n\thexString2 = filesWithDifferences[1]\n\n\t# Formats the strings for each file\n\thexString1 = ''\n\thexString2 = ''\n\thexCount = ''\n\tfor i in range (len(file1)):\n\t\thexString1 = save_to_string(hexString1, file1, i, ' ')\n\t\thexString2 = save_to_string(hexString2, file2, i, ' ')\n\t\tif((i+1)%4 == 0):\n\t\t\thexString1 = hexString1 + ' '\n\t\t\thexString2 = hexString2 + ' '\n\t\tif((i+1)%16 == 0):\n\t\t\thexString1 = hexString1 + '\\n'\n\t\t\thexString2 = hexString2 + '\\n'\n\t\t\t#if(i != len(file1)-1):\n\t\t\thexCount = hexCount + str(file1[i].byteNextOffset) + '\\n'\n\n\t# Returns files\n\tfiles.append(hexString1)\n\tfiles.append(hexString2)\n\tfiles.append(hexCount)\n\treturn files"
},
{
"alpha_fraction": 0.6747826337814331,
"alphanum_fraction": 0.6933333277702332,
"avg_line_length": 24.761194229125977,
"blob_id": "03b1a50d38c11a2de07a2a4875c478ffbe0336e8",
"content_id": "6ef67f339fc7c78a9e81d58f5b4861a2394b68ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1725,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 67,
"path": "/orangeGUI.py",
"repo_name": "ZhangPeterGree/TerminalCompareHex",
"src_encoding": "UTF-8",
"text": "import PySimpleGUI as sg\nimport codeBase as cb\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\n\nlistBoxWidth = 60\nlistBoxHeight = 50\nsg.theme('DarkGrey3')\nsg.theme('Topanga')\n\ndef show_hex_differences():\n\ts = 1\n\ndef showBothFiles(file1, file2):\n\twindowBase.hide()\n\twindowShow = make_windowShow(file1, file2)\n\ndef make_windowBase():\n\tlayout = [\n\t\t\t[sg.Text(\"Select Files\")],\n\t\t\t[sg.Button('Show Both Files')],\n\t\t ]\n\treturn sg.Window('Orange Hex Compare GUI', layout, finalize=True, size=(250,250))\n\ndef make_windowShow(file1, file2):\n\tlayout=[]\n\titem = [sg.Text('File 1 in Hex'), sg.Text('File 2 in Hex')]\n\tlayout.append(item)\n\t# Shows the 2 files that are being compared\n\titem = [sg.Listbox(file1, size=(listBoxWidth,listBoxHeight)), \n\t\t\tsg.Listbox(file2, size=(listBoxWidth,listBoxHeight))]\n\tlayout.append(item)\n\n\titem = [sg.Button('Show Only Differences'), sg.Button('Export Differences')]\n\tlayout.append(item)\n\treturn sg.Window('Orange Hex Compare GUI - Showing Files', layout, finalize=True)\n\n\nwindowBase, windowShow, windowDiff = make_windowBase(), None, None\n\n# Main area that will load\ndef main():\n\tfile1Hex = ''\n\tfile2Hex = ''\n\n\twhile True:\n\t\twindow, event, values = sg.read_all_windows()\n\t\t# Exits application properly\n\t\tif event == 'Quit' or event == sg.WIN_CLOSED:\n\t\t\t\texit(0)\n\t\t# Events for the main screen\n\t\tif window == windowBase:\n\t\t\tif event == 'Show Both Files':\n\t\t\t\tfile1Hex = cb.pick_file()\n\t\t\t\tfile2Hex = cb.pick_file()\n\t\t\t\tshowBothFiles(file1Hex,file2Hex)\n\t\t# Events for the window showing the 2 files\n\t\tif window == windowShow:\n\t\t\tif event == 'Show Only Differences':\n\t\t\t\tshow_hex_differences()\n\t\t\telif event == 'Export Differences':\n\t\t\t\ts = 1\n\n\n\nif __name__ == \"__main__\":\n\tmain()"
},
{
"alpha_fraction": 0.7179487347602844,
"alphanum_fraction": 0.7227997183799744,
"avg_line_length": 31.795454025268555,
"blob_id": "ba08bc084250e74b9e2af3ab2f65e56a55815fc7",
"content_id": "d3ae7213fb51de1abae19a6faf29302c1faec25d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1443,
"license_type": "no_license",
"max_line_length": 127,
"num_lines": 44,
"path": "/README.md",
"repo_name": "ZhangPeterGree/TerminalCompareHex",
"src_encoding": "UTF-8",
"text": "# :tangerine: Orange HexCompare :tangerine:\nA Visual Hex File Compare Tool written in Python using PySimpleGUI &\n\nA Terminal-based Hex File compare tool\n\nSince there's no good Hex compare tool I could find for mac (didn't compare side by side accurately), I decided to make my own.\n\nIt's currently a work in progress, but the goal is to make it like other popular hex compare tools (HexFiend) but with\ngreater compatibility and cross-platform\n\n<img src=\"Example.png\" alt=\"Terminal screenshot of Orange HexCompare side-by-side example\" width=\"500\"/>\n<img src=\"ExampleGUI.png\" alt=\"GUI screenshot of Orange HexCompare side-by-side example\" width=\"500\"/>\n\n## Dependencies\n\n* [Emoji](https://pypi.org/project/emoji/) (Optional for terminal version)\n* [PySimpleGUI](https://pysimplegui.readthedocs.io/en/latest/#install)\n * To Install **PySimpleGUI**:\n\n pip install pysimplegui\n or\n pip3 install pysimplegui\n\n\n## Features\n\n- [X] Compares files (txt,png,sav,dat,etc.)\n- [X] Export differences to a text file\n- [ ] Add paging for larger binaries\n- [ ] Compares Apps\n- [X] GUI\n- [ ] Edit Bytes\n\n## Bugs\n\n* On first load side-by-side view doesn't highlight the differences.\n * Fix: load 'Display differences only' then load 'Display files side-by-side'\n\n## Currently in the works\n- [ ] Improve GUI looks\n- [ ] Add GUI Themes\n- [ ] Fix alignment in GUI\n- [ ] Implement 'exporting' on GUI\n- [ ] Implement 'show differences' on GUI\n"
}
] | 5 |
likit/talentMobility
|
https://github.com/likit/talentMobility
|
3c6d6dc682ea05bb6e50cba66b4e0de3ba4a08f5
|
7b404cd5c79e90e4cec01a4ac5e9b5f7c3509665
|
9c09fd148a0ce1f745a07693a9688cc11faade87
|
refs/heads/master
| 2018-04-01T21:24:09.031404 | 2018-01-08T10:35:53 | 2018-01-08T10:35:53 | 88,422,388 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7256097793579102,
"alphanum_fraction": 0.7317073345184326,
"avg_line_length": 22.571428298950195,
"blob_id": "9c3325b5046940312932a42f4947c08b97647e5f",
"content_id": "1a33c71d5a39356525d9ebdae55c9a571d577a0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 164,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 7,
"path": "/Dockerfile",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "FROM python:2\nWORKDIR /usr/src/\nCOPY app /usr/src/app\nCOPY requirements.txt /usr/src/\nCOPY run.py /usr/src/\nRUN pip install -r requirements.txt\nCMD [\"flask\", \"run\"]"
},
{
"alpha_fraction": 0.6498422622680664,
"alphanum_fraction": 0.6498422622680664,
"avg_line_length": 38.75,
"blob_id": "e0522b67a46df79674e0584c80a4744f78a484bf",
"content_id": "136d448feb481f0e2f87c2a1cb2d99e75ad11461",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 8,
"path": "/app/models.py",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "from . import db\n\nclass AppConfig(db.Model):\n __tablename__ = 'app_configs'\n id = db.Column('id', db.Integer(), primary_key=True)\n key = db.Column('key', db.String(), nullable=False)\n value = db.Column('value', db.String(), nullable=False)\n devstage = db.Column('devstage', db.String(), nullable=False)"
},
{
"alpha_fraction": 0.6821829676628113,
"alphanum_fraction": 0.6982343792915344,
"avg_line_length": 27.363636016845703,
"blob_id": "f9cf1dc740ff8b04be1d5be389c6ccf4d0c6f604",
"content_id": "8af9000e5606dcb9c552454e6b40762ea321bd07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 623,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 22,
"path": "/config.py",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "import os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nclass Config:\n SQLALCHEMY_COMMIT_ON_TEARDOWN = True\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \\\n 'postgres+psycopg2://postgres:genius01@localhost:5444/talentmob_dev'\n\n\nclass ProductionConfig(Config):\n SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \\\n 'postgres+psycopg2://postgres:genius01@pg/talentmob_dev'\n\nconfig = {\n 'development': DevelopmentConfig,\n 'production': ProductionConfig,\n 'default': DevelopmentConfig\n}"
},
{
"alpha_fraction": 0.5058823823928833,
"alphanum_fraction": 0.7019608020782471,
"avg_line_length": 16.386363983154297,
"blob_id": "98a35c745d0138f6078e2652b495aeadaea214d7",
"content_id": "d980f7f5eb05433ce279af1fc4680d34f3257d1e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 765,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 44,
"path": "/requirements.txt",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "alembic==0.9.6\nBabel==2.5.1\nblinker==1.4\ncertifi==2017.11.5\nchardet==3.0.4\nclick==6.7\nfacebook-sdk==3.0.0a0\nFlask==0.12.2\nFlask-BabelEx==0.9.3\nFlask-Login==0.4.1\nFlask-Mail==0.9.1\nFlask-Migrate==2.1.1\nFlask-OAuth==0.12\nFlask-Principal==0.4.0\nFlask-Security==3.0.0\nFlask-Social==1.6.2\nFlask-SQLAlchemy==2.3.2\nFlask-WTF==0.14.2\ngoogle-api-python-client==1.6.4\ngunicorn==19.7.1\nhttplib2==0.10.3\nidna==2.6\nitsdangerous==0.24\nJinja2==2.10\nMako==1.0.7\nMarkupSafe==1.0\noauth2==1.9.0.post1\noauth2client==4.1.2\npasslib==1.7.1\npsycopg2==2.7.3.2\npyasn1==0.4.2\npyasn1-modules==0.2.1\npython-dateutil==2.6.1\npython-editor==1.0.3\npytz==2017.3\nrequests==2.18.4\nrsa==3.4.2\nsix==1.11.0\nspeaklater==1.3\nSQLAlchemy==1.2.0\nuritemplate==3.0.0\nurllib3==1.22\nWerkzeug==0.14.1\nWTForms==2.1\n"
},
{
"alpha_fraction": 0.7320261597633362,
"alphanum_fraction": 0.7320261597633362,
"avg_line_length": 24.5,
"blob_id": "002522bab82a62497c937fa1159e0e7f20849e57",
"content_id": "7f2d48b61a15279f32a1095841ddee670380b5ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 153,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 6,
"path": "/app/main/views.py",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "from flask import render_template, redirect\nfrom . import main_blueprint as main\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n"
},
{
"alpha_fraction": 0.5350194573402405,
"alphanum_fraction": 0.5739299654960632,
"avg_line_length": 15.09375,
"blob_id": "0cc9ac67ec29a6c4a3053658c08d7ef191f974e0",
"content_id": "d16e02fe693012e7d99aae8d9de77c48ee487eb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 514,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 32,
"path": "/docker-compose.yml",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "version: \"3.4\"\nservices:\n web:\n build: .\n depends_on:\n - pg\n ports:\n - \"5000:5000\"\n environment:\n - FLASK_CONFIG=development\n volumes:\n - type: bind\n source: .\n target: /usr/src/talentmob\"\n\n pg:\n image: postgres\n environment:\n - POSTGRES_PASSWORD=genius01\n volumes:\n - talentmob-data:/var/lib/postgresql/data\n ports:\n - \"5444:5432\"\n\nvolumes:\n talentmob-data:\n external: true\n\nnetworks:\n default:\n external:\n name: talentmob"
},
{
"alpha_fraction": 0.7368420958518982,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 25.1875,
"blob_id": "43f79e78180b5daefa5b16cd85adac66ff72c16f",
"content_id": "07a791adb21baf8bf2bccc00c1f670be5eb77e5c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 16,
"path": "/app/__init__.py",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom .main import main_blueprint\nfrom config import config\n\ndb = SQLAlchemy()\nmigrate = Migrate()\n\ndef create_app(config_name='default'):\n app = Flask(__name__)\n app.config.from_object(config[config_name])\n app.register_blueprint(main_blueprint)\n db.init_app(app)\n migrate.init_app(app, db)\n return app"
},
{
"alpha_fraction": 0.8627451062202454,
"alphanum_fraction": 0.8627451062202454,
"avg_line_length": 24.5,
"blob_id": "d8c1101c6ff61f22bb5cf2ae636bc26d4edbe3a7",
"content_id": "70bb9fdd2f03f2dd6597c82777ab93fcce101464",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 2,
"path": "/README.md",
"repo_name": "likit/talentMobility",
"src_encoding": "UTF-8",
"text": "# talentMobility\nTalent Mobility Analytical System\n"
}
] | 8 |
ArrAfel/Huszonegy
|
https://github.com/ArrAfel/Huszonegy
|
67089d5d270da3c9fb1efa66ee5afbeb22518024
|
7781f46cc96cb06c4bdf5dd34db697130f7e0e06
|
cb7c44fa645cb1904c13e5d3838a9d674efa06c7
|
refs/heads/master
| 2020-06-07T14:31:35.014491 | 2015-10-17T14:32:57 | 2015-10-17T14:32:57 | 34,757,254 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5955726504325867,
"alphanum_fraction": 0.620095431804657,
"avg_line_length": 25.285715103149414,
"blob_id": "691c399fa7ad259f9348fa139c207f7557642f71",
"content_id": "88c0481ba28eee8313ced558aff7106f0054d748",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 7548,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 287,
"path": "/app.js",
"repo_name": "ArrAfel/Huszonegy",
"src_encoding": "UTF-8",
"text": "$(document).ready(function(){\n\t\t$(\"#angular\").click(function() {\n\t\t\t window.location.href = \"asd.html\";\n\t\t\t\t\t\tlocalStorage.setItem('penz', 100);\n\t\t});\n\t\t$(\"#about\").click(function() {\n\t\t\t window.location.href = \"about.html\";\n\t\t});\n\t\t$(\"#backIndex\").click(function() {\n\t\t\t window.location.href = \"index.html\";\n\t\t\t localStorage.setItem('penz', 100);\n\t\t});\n\t\t\n\t\t$(\"#back\").click(function() {\n\t\t\t window.location.href = \"options.html\";\n\t\t});\n\t\t\n\t\t$(\"#back1\").click(function() {\n\t\t\t betolt();\n\t\t});\n\t\t\n\t\t$(\"#RandomGenerate\").click(function() {\n\t\t\tbetolt();\n\t\t\tdocument.getElementById(\"penz\").innerHTML = localStorage.getItem('penz');\n\t\t\tlocalStorage.setItem('kovetkezo',0);\n\t\t\trandomGenerator(); \n\t\t});\n\t\t\n\t\t$(\"#addItem\").click(function() {\n\t\t\t ment();\n\t\t});\t\n\t\t$(\"#kiirat\").click(function() {\n\t\t\t var button = document.getElementById(\"kiirat\");\n\t\t\t\tbutton.style.visibility = 'hidden';\n\t\t\t\tujkor();\n\t\t\t\tdocument.getElementById(\"penz\").innerHTML = localStorage.getItem('penz');\n\t\t\t\tlocation.reload();\n\t\t\t\tdocument.getElementById(\"penz\").innerHTML = localStorage.getItem('penz');\n\t\t\t\t\n\t\t});\t\n\t\n\t\t$(\"#megall\").click(function() {\n\t\t\t\tlap = 6;\n\t\t\tvar button = document.getElementById(\"megall\");\n\t\t\t\tbutton.style.visibility = 'hidden';\n\t\t\t\n\t\t\t button = document.getElementById(\"RandomGenerate\");\n\t\t\t\tbutton.style.visibility = 'hidden';\n\t\t\t\n\t\t\t bankLapok();\n\t\t\t button = document.getElementById(\"kiirat\");\n\t\t\t\tbutton.style.visibility = 'visible';\n\n\t\t\t\n\t\t\t\t\tpenzJatekos = localStorage.getItem('penz');\n\t\t\t\n\t\t\t\t if(eredmenyBank > 21) {\n\t\t\t\t\t\t penzJatekos = parseInt(penzJatekos) + tet;\n\t\t\t\t\t\t\t\tdocument.getElementById(\"nyertes\").innerHTML = \"Jatekos nyert!\";\n\t\t\t\t\t}\n\t\t\t\t\telse if(eredmeny > eredmenyBank) {\n\t\t\t\t\t\t\tpenzJatekos = parseInt(penzJatekos) + tet;\n\t\t\t\t\t\t\tdocument.getElementById(\"nyertes\").innerHTML = \"Jatekos nyert!\"\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\t\tpenzJatekos = parseInt(penzJatekos) - tet;\n\t\t\t\t\t\tdocument.getElementById(\"nyertes\").innerHTML = \"Jatekos veszitett!\"\n\t\t\t\t\t}\n\t\t\t\t\tlocalStorage.setItem('penz',penzJatekos);\n\t\t\t\t\tdocument.getElementById(\"penz\").innerHTML = penzJatekos;\n\t\t});\t\n\t\n\tbetolt();\n\tujkor();\n\n\tnehezseg = penzJatekos = localStorage.getItem('nehez');\n\n\tif(nehezseg == \"1\")\t{\t\n\t\t tet = 10;\n\t}\n\telse if(nehezseg == \"2\"){\n\t\t tet = 20;\n\t}\n\telse{\n\t\t tet = 50;\n\t}\n\tpenzJatekos = localStorage.getItem('penz');\n\tdocument.getElementById(\"penz\").innerHTML = penzJatekos;\t\n});\n\n\nfunction bankLapok() {\n\t\n\twhile(eredmenyBank < 18) {\n\t\tvar szam = Math.floor((Math.random()*8)+0);\n\t\tvar szin = Math.floor((Math.random()*4)+0);\n\n\n\t\twhile(!(kartya[szin][szam] == 0)) {\n\t\t\t\tvar szam = Math.floor((Math.random()*8)+0);\n\t\t\t\tvar szin = Math.floor((Math.random()*4)+0);\n\t\t}\n\n\t\tswitch (szam) {\n\t\t\tcase 0: eredmenyBank = eredmenyBank + 11;\n\t\t\t\tbreak;\n\t\t\tcase 1: eredmenyBank = eredmenyBank + 4;\n\t\t\t\tbreak;\n\t\t\tcase 2: eredmenyBank = eredmenyBank + 3;\n\t\t\t\tbreak;\n\t\t\tcase 3: eredmenyBank = eredmenyBank + 2;\n\t\t\t\tbreak;\n\t\t\tcase 4: eredmenyBank = eredmenyBank + 10;\n\t\t\t\tbreak;\n\t\t\tcase 5: eredmenyBank = eredmenyBank + 9;\n\t\t\t\tbreak;\n\t\t\tcase 6: eredmenyBank = eredmenyBank + 8;\n\t\t\t\tbreak;\n\t\t\tcase 7: eredmenyBank = eredmenyBank + 7;\n\t\t\t\tbreak;\n\t\t}\n\n\t\tkartya[szin][szam] = 1;\n\t\tlap = lap + 1;\n\t\tvar kep = \"layer\"+lap;\n\t\tvar img = document.getElementById(kep);\n\t\timg.src = lapok[szin][szam];\n\t\timg.style.visibility = 'visible';\n\t\timg.style.left = '185px';\n\t}\n\t\tdocument.getElementById(\"bank\").innerHTML = eredmenyBank;\n}\n\nfunction ment() {\n\t nev = $(\"#nev\").val();\n\t email = $(\"#email\").val();\n\t kor = $(\"#kor\").val();\n\t var rate_value;\n\n\t if (document.getElementById('r1').checked) {\n\t\t rate_value = document.getElementById('r1').value;\n\t } \n\t if (document.getElementById('r2').checked) {\n\t\t rate_value = document.getElementById('r2').value;\n\t } \n\t if (document.getElementById('r3').checked) {\n\t\t rate_value = document.getElementById('r3').value;\n\t }\n\t \n\t if (window.localStorage) {\n\t\t localStorage.setItem('nev',nev);\n\t localStorage.setItem('email',email);\n\t\t localStorage.setItem('kor',kor);\n\t\t localStorage.setItem('nehez',rate_value);\n\t\t alert(\"Adatok elmentve\");\n\t }\n}\nvar tet=1;\nvar lapok = new Array(1);\nvar kartya = new Array(1);\n\t\t for (var i = 0; i < 4; i++) {\n\t\t\tkartya[i] = new Array(9);\n\t\t\tlapok[i] = new Array(9);\n}\n\nfunction ujkor() {\n\n\tfor(var i = 0; i < 4; i++) {\n\t\t\tfor(var j = 0; j < 9; j++){\n\t\t\t\tkartya[i][j] = 0;\t\n\t\t\t}\n\t}\n}\n\t\n\n\t\tlapok[0][0] = 'Kartyak/makdiszno.png';\n\t\tlapok[0][1] = 'Kartyak/makcsiko.png';\n\t\tlapok[0][2] = 'Kartyak/makfelso.png';\n\t\tlapok[0][3] = 'Kartyak/makalso.png';\n\t\tlapok[0][4] = 'Kartyak/maktiz.png';\n\t\tlapok[0][5] = 'Kartyak/makkilenc.png';\n\t\tlapok[0][6] = 'Kartyak/maknyolc.png';\n\t\tlapok[0][7] = 'Kartyak/makhet.png';\n\t\tlapok[1][0] = 'Kartyak/pirosdisz.png';\n\t\tlapok[1][1] = 'Kartyak/piroscsiko.png';\n\t\tlapok[1][2] = 'Kartyak/pirosfelso.png';\n\t\tlapok[1][3] = 'Kartyak/pirosalso.png';\n\t\tlapok[1][4] = 'Kartyak/pirostiz.png';\n\t\tlapok[1][5] = 'Kartyak/piroskilenc.png';\n\t\tlapok[1][6] = 'Kartyak/pirosnyolc.png';\n\t\tlapok[1][7] = 'Kartyak/piroshet.png';\n\t\tlapok[2][0] = 'Kartyak/tokdiszno.png';\n\t\tlapok[2][1] = 'Kartyak/tokcsiko.png';\n\t\tlapok[2][2] = 'Kartyak/tokfelso.png';\n\t\tlapok[2][3] = 'Kartyak/tokalso.png';\n\t\tlapok[2][4] = 'Kartyak/toktiz.png';\n\t\tlapok[2][5] = 'Kartyak/tokkilenc.png';\n\t\tlapok[2][6] = 'Kartyak/toknyolc.png';\n\t\tlapok[2][7] = 'Kartyak/tokhet.png';\n\t\tlapok[3][0] = 'Kartyak/zolddiszno.png';\n\t\tlapok[3][1] = 'Kartyak/zoldcsiko.png';\n\t\tlapok[3][2] = 'Kartyak/zoldfelso.png';\n\t\tlapok[3][3] = 'Kartyak/zoldalso.png';\n\t\tlapok[3][4] = 'Kartyak/zoldtiz.png';\n\t\tlapok[3][5] = 'Kartyak/zoldkilenc.png';\n\t\tlapok[3][6] = 'Kartyak/zoldnyolc.png';\n\t\tlapok[3][7] = 'Kartyak/zoldhet.png';\n\nvar lap = 0;\nvar eredmeny = 0;\nvar eredmenyBank =0;\nvar penzJatekos = 100;\n\n\nfunction randomGenerator() {\n\t\n\t// Megvan a 4x12 tömb evvel ellenőrzöm h kiosztottam e már a lapot.\n\n\t\n\tvar szam = Math.floor((Math.random()*8)+0);\n\tvar szin = Math.floor((Math.random()*4)+0);\n\t\t\n\t\n\twhile(!(kartya[szin][szam] == 0)) {\n\t\t\tvar szam = Math.floor((Math.random()*8)+0);\n\t\t\tvar szin = Math.floor((Math.random()*4)+0);\n\t}\n\t\n\tswitch (szam) {\n\t\tcase 0: eredmeny = eredmeny + 11;\n\t\t\tbreak;\n\t\tcase 1: eredmeny = eredmeny + 4;\n\t\t\tbreak;\n\t\tcase 2: eredmeny = eredmeny + 3;\n\t\t\tbreak;\n\t\tcase 3: eredmeny = eredmeny + 2;\n\t\t\tbreak;\n\t\tcase 4: eredmeny = eredmeny + 10;\n\t\t\tbreak;\n\t\tcase 5: eredmeny = eredmeny + 9;\n\t\t\tbreak;\n\t\tcase 6: eredmeny = eredmeny + 8;\n\t\t\tbreak;\n\t\tcase 7: eredmeny = eredmeny + 7;\n\t\t\tbreak;\n\t}\n\n//\tconsole.log(szin, szam);\n\t\n\tkartya[szin][szam] = 1;\n\tlap = lap + 1;\n\tvar kep = \"layer\"+lap;\n\tvar img = document.getElementById(kep);\n\timg.src = lapok[szin][szam];\n\timg.style.visibility = 'visible';\n\n\t\n\tif(eredmeny > 15) {\n\t\tvar button = document.getElementById(\"megall\");\n\t\t\t\tbutton.style.visibility = 'visible';\n/*\t\tvar button = document.getElementById(\"kiirat\");\n\t\t\t\tbutton.style.visibility = 'hidden';*/\n\t\t\n\t}\n\t\n\tif(eredmeny > 21) {\n\t\tvar button = document.getElementById(\"kiirat\");\n\t\t\t\tbutton.style.visibility = 'hidden';\n\t\t\t\tujkor();\t\n\t\t\t\talert(\"Tullepted a 21-t \\n A pontod :\" + eredmeny);\n\t\t\t\tpenzJatekos = localStorage.getItem('penz');\n\t\t\t\tpenzJatekos = penzJatekos - tet;\n\t\t\t\tlocalStorage.setItem('penz',penzJatekos);\n\t\t\t\tdocument.getElementById(\"nyertes\").innerHTML = \"Jatekos veszitett!\"\n\t\t\t\tlocation.reload();\n\t}\t\n\t\n\tdocument.getElementById(\"jatekos\").innerHTML = eredmeny;\n\n\t/*$(\"#aze\").value = Math.floor((Math.random()*13)+1);\n\t$(\"#eze\").value = Math.floor((Math.random()*13)+1);*/\n\t\n}\n\nfunction betolt() {\n\t\t\tdocument.getElementById(\"az\").innerHTML = localStorage.getItem('nev');\n}\n"
},
{
"alpha_fraction": 0.7627118825912476,
"alphanum_fraction": 0.7966101765632629,
"avg_line_length": 18.66666603088379,
"blob_id": "fe0be03f7cfc0a486e9f507184dc3862f68ac614",
"content_id": "f528eeffe856bd63711d7cbd76362cb01588fbe4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 59,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 3,
"path": "/README.md",
"repo_name": "ArrAfel/Huszonegy",
"src_encoding": "UTF-8",
"text": "# Huszonegy\nBlack jack game Hungraian version \nVersion 1.1\n"
},
{
"alpha_fraction": 0.43718594312667847,
"alphanum_fraction": 0.4874371886253357,
"avg_line_length": 31.16666603088379,
"blob_id": "e3641f4eb77212c2e86520b51f72d480761d068d",
"content_id": "60f4245ea71f09869652cf6daa9f90aea315f8ad",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 199,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 6,
"path": "/kozos_oos.py",
"repo_name": "ArrAfel/Huszonegy",
"src_encoding": "UTF-8",
"text": "def kozos_oos (szam1, szam2):\r\n osztok = ()\r\n for i in range (1, min (szam1, szam2) + 1):\r\n if szam1 % i == 0 and szam2 % i == 0:\r\n osztok = osztok + (i,)\r\n return osztok\r\n"
}
] | 3 |
Web5design/linkypedia
|
https://github.com/Web5design/linkypedia
|
9f7b0546b3086c4dae63a1ae4e98e1f6b93138cd
|
76d5ecdaa00579f3fb773c3cbf2d4f91c5513b9e
|
326aa922ce75b52ac68fdf9d5940e38837739b22
|
refs/heads/master
| 2020-12-24T11:05:56.104945 | 2010-11-24T07:17:22 | 2010-11-24T07:17:22 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6709235310554504,
"alphanum_fraction": 0.680267870426178,
"avg_line_length": 35.691429138183594,
"blob_id": "cdbf297908c29fe50bfe6807f0aaac4d252d34c1",
"content_id": "ee3e055d263df6aebff7255d86b95f78c646600b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6421,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 175,
"path": "/linkypedia/web/views.py",
"repo_name": "Web5design/linkypedia",
"src_encoding": "UTF-8",
"text": "import json\nimport urllib2\nimport datetime\nimport urlparse\nimport cStringIO\n\nfrom lxml import etree\n\nfrom django.db.models import Count\nfrom django.template import RequestContext\nfrom django.core.paginator import Paginator\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.views.decorators.cache import cache_page\n\nfrom linkypedia.web import models as m\nfrom linkypedia.rfc3339 import rfc3339\nfrom linkypedia.paginator import DiggPaginator\nfrom linkypedia.settings import CRAWL_CUTOFF, CACHE_TTL_SECS\n\ndef about(request):\n return render_to_response('about.html')\n\n@cache_page(CACHE_TTL_SECS)\ndef websites(request):\n websites = m.Website.objects.all()\n websites = websites.annotate(Count('links'))\n websites = websites.order_by('-links__count')\n host = request.get_host()\n\n return render_to_response('websites.html', dictionary=locals(),\n context_instance=RequestContext(request))\n\ndef websites_feed(request):\n websites = m.Website.objects.all()\n websites = websites.order_by('-created')\n host = request.get_host()\n\n # figure out the last time the feed changed based on the\n # most recently crawled site\n feed_updated = datetime.datetime.now()\n if websites.count() > 0:\n feed_updated = websites[0].created\n\n return render_to_response('websites.atom', dictionary=locals(),\n context_instance=RequestContext(request),\n mimetype='application/json; charset=utf-8')\n\ndef website_summary(request, website_id):\n website = get_object_or_404(m.Website, id=website_id)\n tab = 'summary'\n tab_summary = \"Summary Information for %s\" % website.name\n title = \"website: %s\" % website.url\n if website.links.count() == CRAWL_CUTOFF:\n cutoff = CRAWL_CUTOFF\n return render_to_response('website_summary.html', dictionary=locals())\n\ndef website_pages(request, website_id):\n website = get_object_or_404(m.Website, id=website_id)\n\n page_num = request.GET.get('page', 1)\n page_num = int(page_num)\n\n # make sure we support the order\n order = request.GET.get('order', 'update')\n direction = request.GET.get('direction', 'desc')\n other_direction = 'asc' if direction == 'desc' else 'desc'\n\n if order == 'update' and direction =='asc':\n sort_order = 'last_modified'\n elif order == 'update' and direction == 'desc':\n sort_order = '-last_modified'\n elif order == 'links' and direction == 'asc':\n sort_order = 'links__count'\n else:\n sort_order = '-links__count'\n\n wikipedia_pages = m.WikipediaPage.objects.filter(links__website=website)\n wikipedia_pages = wikipedia_pages.annotate(Count('links'))\n wikipedia_pages = wikipedia_pages.order_by(sort_order)\n wikipedia_pages = wikipedia_pages.distinct()\n\n paginator = DiggPaginator(wikipedia_pages, 100)\n page = paginator.page(page_num)\n wikipedia_pages = page.object_list\n\n tab = 'pages'\n tab_summary = \"wikipedia pages %s\" % website.name \n title = \"website: %s\" % website.url\n\n return render_to_response('website_pages.html', dictionary=locals())\n\n\ndef website_page_links(request, website_id, page_id):\n website = get_object_or_404(m.Website, id=website_id)\n wikipedia_page = m.WikipediaPage.objects.get(id=page_id)\n links = m.Link.objects.filter(wikipedia_page=wikipedia_page,\n website=website)\n\n return render_to_response('website_page_links.html', dictionary=locals())\n\ndef website_pages_feed(request, website_id, page_num=1):\n website = get_object_or_404(m.Website, id=website_id)\n wikipedia_pages = m.WikipediaPage.objects.filter(links__website=website)\n wikipedia_pages = wikipedia_pages.annotate(Count('links'))\n wikipedia_pages = wikipedia_pages.order_by('-last_modified')\n wikipedia_pages = wikipedia_pages.distinct()\n\n feed_updated = datetime.datetime.now()\n if wikipedia_pages.count() > 0:\n feed_updated = wikipedia_pages[0].last_modified\n\n host = request.get_host()\n paginator = Paginator(wikipedia_pages, 100)\n page = paginator.page(int(page_num))\n wikipedia_pages = page.object_list\n \n return render_to_response('website_pages_feed.atom', \n mimetype=\"application/atom+xml\", dictionary=locals())\n\ndef website_categories(request, website_id, page_num=1):\n website = get_object_or_404(m.Website, id=website_id)\n categories = website.categories().order_by('-pages__count')\n paginator = DiggPaginator(categories, 100)\n page = paginator.page(int(page_num))\n categories = page.object_list\n tab = 'categories'\n tab_summary = \"Categories for %s\" % website.name \n title = \"website: %s\" % website.url\n return render_to_response('website_categories.html', dictionary=locals())\n\ndef website_users(request, website_id):\n website = get_object_or_404(m.Website, id=website_id)\n users = m.WikipediaUser.objects.filter(wikipedia_pages__links__website=website)\n users = users.distinct()\n users = users.order_by('username')\n tab = 'users'\n title = \"website: %s\" % website.url\n return render_to_response('website_users.html', dictionary=locals())\n\ndef lookup(request):\n url = request.REQUEST.get('url', None)\n results = []\n for link in m.Link.objects.filter(target=url):\n w = link.wikipedia_page\n result = {\n 'url': w.url, \n 'title': w.title, \n 'last_modified': rfc3339(w.last_modified)\n }\n results.append(result)\n return HttpResponse(json.dumps(results, indent=2), mimetype='application/json')\n\ndef robots(request):\n return render_to_response('robots.txt', mimetype='text/plain')\n\ndef status(request):\n link = m.Link.objects.all().order_by('-created')[0]\n update = {\n 'wikipedia_url': link.wikipedia_page.url,\n 'wikipedia_page_title': link.wikipedia_page.title,\n 'target': link.target,\n 'website_name': link.website.name,\n 'website_url': link.website.url,\n 'created': rfc3339(link.created),\n }\n\n crawls = m.Crawl.objects.filter(finished=None).order_by('-started')\n if crawls.count() > 0:\n website = crawls[0].website\n crawl = {'name': website.name, 'url': website.url, \n 'link': website.get_absolute_url()}\n update['current_crawl'] = crawl\n\n return HttpResponse(json.dumps(update, indent=2), mimetype='application/json')\n"
}
] | 1 |
ryanhanli/Talking-Python
|
https://github.com/ryanhanli/Talking-Python
|
5bafad37023dd83fa6d9744086bc41cbc82fda3e
|
6c329029fd87147cda883f5104f42c8dd93ac612
|
e3dc8a5f91ffb28663016e672ab8b939d576289a
|
refs/heads/main
| 2023-09-04T01:15:59.618700 | 2021-11-04T01:54:44 | 2021-11-04T01:54:44 | 404,508,864 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6858974099159241,
"alphanum_fraction": 0.7243589758872986,
"avg_line_length": 38,
"blob_id": "23ff10dd27020a291e2cd01f68c1f5434d59b450",
"content_id": "21305c6a5f7ab0dbff3cf7f4e8f8465d02d02132",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 156,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 4,
"path": "/ch02 - Python Refresher/create_local_module.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "# This creates a local module to be imported to other scripts\ndef team_sales(sales1, sales2, sales3):\n sales = sales1 + sales2 + sales3\n return sales\n"
},
{
"alpha_fraction": 0.7054263353347778,
"alphanum_fraction": 0.7080103158950806,
"avg_line_length": 32.65217208862305,
"blob_id": "678fbcfb77e6c83bfadef8b0e2f93c76cd3ef9b6",
"content_id": "323fefad4c971d9244c7c81df63a3f08dd0057bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 774,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 23,
"path": "/ch06 - Web Scraping Podcasts, Radios, and Videos/scrape_live_web.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from bs4 import BeautifulSoup\nimport requests\n\n# Provide the web address of the live web\nurl = 'http://libraries.uky.edu'\n# Obtain information from the live web\npage = requests.get(url)\n# Parse the page to obtain the parent div tag\nsoup = BeautifulSoup(page.text, \"html.parser\")\ndiv = soup.find('div', class_=\"sf-middle\")\n# Locate the three child div tags\ncontacts = div.find_all(\"div\", class_=\"dashing-li\")\n# Print out the first child div tag to examine it\nprint(contacts[0])\n# Obtain information from each child tag\nfor contact in contacts:\n # Obtain the area name\n area = contact.find('span', class_=\"contact_area\")\n print(area.text)\n # Obtain the phone and email\n atags = contact.find_all('a', href = True)\n for atag in atags:\n print(atag.text)\n"
},
{
"alpha_fraction": 0.7450980544090271,
"alphanum_fraction": 0.7472766637802124,
"avg_line_length": 29.600000381469727,
"blob_id": "99cd1ad2efd4cf24be6e737daff0f77a694fd681",
"content_id": "e17c7127771439a7aaf32e2c0a3183e88d719ef0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 459,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 15,
"path": "/ch15 - Stock Market Watch/bitcoin_price.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import requests\n\n# https://jsonformatter.curiousconcept.com/ JSON Parser\n\n# Specify the url to find the bitcoin price\nurl = 'https://api.coindesk.com/v1/bpi/currentprice.json'\n# Retrieve the live information from bitcoin url\nresponse = requests.get(url)\n# Read the JSON data\nresponse_json = response.json()\n# Obtain the USD dictionary\nusd = response_json['bpi']['USD']\n# Get the price\nprice = usd['rate_float']\nprint(f\"The Bitcoin price is {price} dollars.\")\n"
},
{
"alpha_fraction": 0.6532007455825806,
"alphanum_fraction": 0.6569297909736633,
"avg_line_length": 29.358489990234375,
"blob_id": "02854d3b2f292744027d2925e95743f399cfdc49",
"content_id": "deb85c1b04966bcec2a93f136d880664d46e6e92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1609,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 53,
"path": "/ch16 - Use World Languages/wiki_world_languages.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from io import BytesIO\n\nimport speech_recognition as sr\nfrom gtts import gTTS\nfrom pydub import AudioSegment\nfrom pydub.playback import play\nimport wikipedia\n\nfrom mptpkg import print_say\n\n# Create a dictionary of languages and the corresponding codes\nlang_abbre = {\"english\":\"en\",\n \"chinese\":\"zh\",\n \"spanish\":\"es\",\n \"french\":\"fr\",\n \"japanese\":\"ja\",\n \"portuguese\":\"pt\",\n \"russian\":\"ru\",\n \"korean\":\"ko\",\n \"german\":\"de\",\n \"italian\":\"it\"}\n\nlang = input(\"What language do you want to use?\\n\")\n \n# Ask what you want to know\nprint_say(f\"Say what you want to know in {lang}...\")\n# Initiate speech recognition\nspeech = sr.Recognizer() \n# Capture your voice query in the language of your choice\nwith sr.Microphone() as source:\n speech.adjust_for_ambient_noise(source)\n while True:\n try:\n audio = speech.listen(source)\n my_input = speech.recognize_google(audio, language=lang_abbre[lang])\n break\n except sr.UnknownValueError:\n print_say(\"Sorry, I cannot understand what you said!\")\n# Print out what you said\nprint(f\"you said: {my_input}\")\n# Obtain answer from Wikipedia and print out\nwikipedia.set_lang(lang_abbre[lang])\nans = wikipedia.summary(my_input)[0:200]\nprint(ans)\n# Convert text to speech in the language of your choice\ntts = gTTS(text=ans,lang=lang_abbre[lang])\n# Create a temporary file \nvoice = BytesIO()\n# Save the voice output as an audio file\ntts.write_to_fp(voice)\n# Play the audio file\nvoice.seek(0)\nplay(AudioSegment.from_mp3(voice))\n"
},
{
"alpha_fraction": 0.5906040072441101,
"alphanum_fraction": 0.6845637559890747,
"avg_line_length": 14.631579399108887,
"blob_id": "6ee40bc0d346c460da5bea0b2b4ac665cf12ace8",
"content_id": "a4f4e601b5187d6733c4da11f7e04286475966e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 298,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 19,
"path": "/ch09 - Graphics and Animation with the Turtle Module/left_right.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('light blue')\nt.title('Python Turtle Graphics')\nt.pensize(5)\nt.right(30)\nt.forward(200)\nt.left(30)\nt.backward(400)\nt.left(90)\nt.pencolor('red')\nt.forward(200)\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n\n"
},
{
"alpha_fraction": 0.4739130437374115,
"alphanum_fraction": 0.593478262424469,
"avg_line_length": 14.82758617401123,
"blob_id": "a2f67f163aeea24709f9154d4314b13f0bd7122c",
"content_id": "5d5a89fa278fed0f0e2028f967a9d53a254b7cd3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 460,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 29,
"path": "/ch09 - Graphics and Animation with the Turtle Module/create_lines.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('lightgreen')\nt.title('Python Turtle Graphics')\nt.pensize(6)\nt.goto(200,100)\nt.up()\nt.pencolor('blue')\nfor i in range(8):\n t.goto(-200+50*i,-150)\n t.down()\n t.goto(-200+50*i+30,-150)\n t.up()\n\nfor i in range(8):\n t.goto(-200+50*i, -50)\n t.down()\n t.goto(-200+50*i+30, -50)\n t.up()\n\nt.hideturtle()\nt.done()\n\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n\n"
},
{
"alpha_fraction": 0.6014362573623657,
"alphanum_fraction": 0.6678635478019714,
"avg_line_length": 16.3125,
"blob_id": "63c51e77f6259c2e7f31de2c503ddba3086e527a",
"content_id": "4c8c557ee910772bacfb04d7e69a1f797e5af02f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 557,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 32,
"path": "/ch09 - Graphics and Animation with the Turtle Module/two_turtles.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screent.\nt.setup(810,710)\nt.tracer(False)\nt.hideturtle()\nt.bgcolor('lightgreen')\nt.color('blue')\nt.pensize(5)\nt.up()\nt.goto(-200,-100)\nt.down()\nt.forward(400)\nt.left(90)\nt.forward(400)\nt.left(90)\nt.forward(400)\nt.left(90)\nt.forward(400)\n# Create a second turtle \nmsg = t.Turtle()\nmsg.hideturtle()\nmsg.up()\nmsg.color('red')\nmsg.goto(0,-200)\nmsg.write('this is written by the second turtle', align = 'center', font = ('Arial',30,'normal'))\nt.update()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n\n\n\n"
},
{
"alpha_fraction": 0.7356321811676025,
"alphanum_fraction": 0.7356321811676025,
"avg_line_length": 28,
"blob_id": "465e5f314f610f1383f2f783cabecb89d572ce56",
"content_id": "e347b9f3a606c004ce94c3c120ff3e1c5985ae8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 3,
"path": "/ch01 - Setup/my_first_script.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "print(\"This is very first Python script!\")\n\nprint(\"This is my second Python message!\")\n"
},
{
"alpha_fraction": 0.7264150977134705,
"alphanum_fraction": 0.7264150977134705,
"avg_line_length": 20,
"blob_id": "8888f1d166d0165da88a0a270e76e0b32a0053fc",
"content_id": "87df127da53af7488f9506a6d278adf62f618b5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 5,
"path": "/ch05 - Speaking Applications/wiki.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import wikipedia\n\nqs = input(\"What do you want to know?\\n\")\nanswer = wikipedia.summary(qs)\nprint(answer)\n\n"
},
{
"alpha_fraction": 0.5568996667861938,
"alphanum_fraction": 0.615143358707428,
"avg_line_length": 25.891565322875977,
"blob_id": "048685459d268eccdd74129e2d08eb364cb669bf",
"content_id": "830715da5fbe981759e1de7aef58522827c6e531",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2232,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 83,
"path": "/ch11 - Connect Four/disc_fall.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\nfrom time import sleep\n\n# Set up the screen\nt.setup(700,600,10,70)\nt.hideturtle()\nt.tracer(False)\nt.bgcolor(\"lightgreen\")\nt.title(\"Connect Four in Turtle Graphics\")\n# Draw six thick vertical lines\nt.pensize(5)\nfor i in range(-250,350,100): \n t.up()\n t.goto(i,-350)\n t.down()\n t.goto(i,350)\n t.up()\n# Draw five thin gray horizontal lines to form grid \nt.pensize(1)\nt.pencolor(\"grey\")\nfor i in range(-200,300,100): \n t.up()\n t.goto(-350,i)\n t.down()\n t.goto(350,i)\n t.up()\n# Write column numbers on the board\ncolnum = 1\nfor x in range(-300, 350, 100):\n t.goto(x,270)\n t.write(colnum,font = ('Arial',20,'normal'))\n colnum += 1\n# The red player moves first\nturn = \"red\"\n# The x-coordinates of the center of the 7 columns\nxs = [-300,-200,-100,0,100,200,300]\n# The y-coordinates of the center of the 6 rows\nys = [-250,-150,-50,50,150,250]\n# Keep track of the occupied cells\noccupied = [list(),list(),list(),list(),list(),list(),list()]\n# Create a second turtle to show disc falling\nfall = t.Turtle()\nfall.up()\nfall.hideturtle()\n# Define a function conn() to place a disc in a cell\ndef conn(x,y):\n # Make the variable turn a globale variable\n global turn\n # Calculate the column number based on x and y values\n if -350<x<350 and -300<y<300:\n col = int((x+450)//100)\n else:\n print('You have clicked outside the game board!')\n # Calculate the lowest available row number in that column\n row = len(occupied[col-1])+1\n # Show the disc fall from the top\n if row<6:\n for i in range(6,row,-1):\n fall.goto(xs[col-1],ys[i-1])\n fall.dot(80,turn)\n t.update()\n sleep(0.05)\n fall.clear()\n\n # Go to the cell and place a dot of the player's color\n t.up()\n t.goto(xs[col-1],ys[row-1])\n t.dot(80,turn)\n # Add the move to the occupied list to keep track\n occupied[col-1].append(turn)\n # Give the turn to the other player\n if turn == \"red\":\n turn = \"yellow\"\n else:\n turn = \"red\" \n# Bind the mouse click to the conn() function\nt.onscreenclick(conn)\nt.listen() \nt.done() \ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.5257142782211304,
"alphanum_fraction": 0.6628571152687073,
"avg_line_length": 15.666666984558105,
"blob_id": "4db547c9bdb357e303903aedbdf5939d5c823d9a",
"content_id": "0452410c81acdfcf28e0a520dad5e3bf5a614225",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 350,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 21,
"path": "/ch09 - Graphics and Animation with the Turtle Module/dots.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('lightgreen')\nt.title('Python Turtle Graphics')\nt.up()\nt.goto(150,100)\nt.dot(120,'red')\nt.goto(-150,100)\nt.dot(135,'yellow')\nt.goto(150,-100)\nt.dot(125,'blue')\nt.goto(-150,-100)\nt.dot(140,'green')\nt.hideturtle()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.6309794783592224,
"alphanum_fraction": 0.7015945315361023,
"avg_line_length": 15.259259223937988,
"blob_id": "eb19b7172255fc40468ba5a69d0872c7f24a27e2",
"content_id": "708b058bd4067f963bcc0e98730768b583ffa6df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 439,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 27,
"path": "/ch09 - Graphics and Animation with the Turtle Module/rectangle.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screen\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('green')\nt.title('Python Turtle Graphics')\nt.hideturtle()\nt.tracer(False)\nt.pensize(6)\n# Draw the first side\nt.forward(200)\nt.left(90)\n# Draw the second side\nt.forward(100)\nt.left(90)\n# Draw the third side\nt.forward(200)\nt.left(90)\n# Finish the rectangle\nt.forward(100)\nt.update()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.6718224883079529,
"alphanum_fraction": 0.686617374420166,
"avg_line_length": 38.157894134521484,
"blob_id": "791ae295464b07f530a0f0aca3778d31ad5c7762",
"content_id": "a9418062df6092ef48611e0e944b6963016a9f14",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1487,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 38,
"path": "/ch14 - Financial Applications/alpha_beta.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from datetime import date, timedelta\n\nimport statsmodels.api as sm\nfrom pandas_datareader import data as pdr\n\n# Set the start and end dates\nend_date = date.today().strftime(\"%Y-%m-%d\")\nstart_date = (date.today() - timedelta(days = 180)).strftime(\"%Y-%m-%d\")\nmarket = \"^GSPC\" \nticker = \"MSFT\"\n# Retieve prices\nsp = pdr.get_data_yahoo(market, start = start_date, end = end_date)\nstock = pdr.get_data_yahoo(ticker, start = start_date, end = end_date)\n# Calculate returns for sp500 and the stock\nsp['ret_sp'] = (sp['Adj Close']/sp['Adj Close'].shift(1))-1\nstock['ret_stock'] = (stock['Adj Close']/stock['Adj Close'].shift(1))-1\n# Merge the two datasets, keep only returns\ndf = sp[['ret_sp']].merge(stock[['ret_stock']], left_index = True, right_index = True) \n# Add risk free rate (assume constant for simplicity) \ndf['rf'] = 0.00001\n# We need a constant to run regressions\ndf['const'] = 1 \ndf['exret_stock'] = df.ret_stock - df.rf\ndf['exret_sp'] = df.ret_sp - df.rf\n# Remove missing values\ndf.dropna(inplace=True) \n# Calculate the stock's alpha and Beta\nreg = sm.OLS(endog = df['exret_stock'], exog = df[['const', 'exret_sp']], missing = 'drop')\nresults = reg.fit()\nprint(results.summary())\nalpha = round(results.params['const']*100,3)\nbeta = round(results.params['exret_sp'],2)\n# Print the values of alpha and beta\nprint(f'The alpha of the stock of {ticker} is {alpha} percent.')\nprint(f'The beta of the stock of {ticker} is {beta}.')\n\n\n# These alpha and beta values are on a per day basis"
},
{
"alpha_fraction": 0.7600950002670288,
"alphanum_fraction": 0.7600950002670288,
"avg_line_length": 29,
"blob_id": "4f8c3f75ef9726ac871898a9788042457976db8c",
"content_id": "5947858e501057e93e7fbe24735955689e9e34a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 421,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 14,
"path": "/ch08 - Know-It-All VPA/wolfram.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "# Import the wolframalpha module\nimport wolframalpha\n\n# Enter your own WolframAlpha APIkey below\nAPIkey = \"XEXJUY-G6XPPYUYR4\" \nwolf = wolframalpha.Client(APIkey)\n# Enter your query \ninp = input(\"What do you want to know from WolframAlpha?\\n\")\n# Send your query to WolframAlpha and get a response\nresponse = wolf.query(inp)\n# Retrieve the text from the response\nres = next(response.results).text \n# Print out the response\nprint(res) \n"
},
{
"alpha_fraction": 0.6938775777816772,
"alphanum_fraction": 0.7172011733055115,
"avg_line_length": 27.5,
"blob_id": "ed728dbef6da10b67cd78efec78dcbc671673771",
"content_id": "086696a4ea88ae1510eb0c8364cd79bb44f6a496",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 343,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 12,
"path": "/ch15 - Stock Market Watch/tk_label.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import tkinter as tk\n\n# Create the root window\nroot = tk.Tk()\n# Specify the title and size of the root window\nroot.title(\"A Label Inside A Root Window\")\nroot.geometry(\"800x200\")\n# Create a label inside the root window\nlabel = tk.Label(text=\"this is a label\", fg=\"Red\", font=(\"Helvetica\", 80))\nlabel.pack()\n# Run the game loop\nroot.mainloop()\n\n"
},
{
"alpha_fraction": 0.5098253488540649,
"alphanum_fraction": 0.5993449687957764,
"avg_line_length": 25.171428680419922,
"blob_id": "e75bfacd8963c61fd0de2b7440b091b080efe887",
"content_id": "7543fb041508dbd60cf2d20109cf5f63940c90a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 916,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 35,
"path": "/ch10 - Tic-Tac-Toe/ttt_board.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screen\nt.setup(600,600,10,70)\nt.tracer(False)\nt.bgcolor(\"red\")\nt.hideturtle()\nt.title(\"Tic-Tac-Toe in Turtle Graphics\")\n# Draw horizontal lines and vertical lines to form grid\nt.pensize(5)\n# This is not a range this is just two values\nfor i in (-100,100):\n print(i)\n t.up()\n t.goto(i,-300)\n t.down()\n t.goto(i,300)\n t.up()\n t.goto(-300,i)\n t.down()\n t.goto(300,i)\n t.up()\n# Create a dictionary to map cell numbers to cell center coordinates\ncellcenter = {'1':(-200,-200), '2':(0,-200), '3':(200,-200),\n '4':(-200,0), '5':(0,0), '6':(200,0),\n '7':(-200,200), '8':(0,200), '9':(200,200)} \n# Go to the center of each cell, write down the cell number\nfor cell, center in list(cellcenter.items()):\n t.goto(center)\n t.write(cell,font = ('Arial',20,'normal'))\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.6987577676773071,
"alphanum_fraction": 0.6987577676773071,
"avg_line_length": 22.071428298950195,
"blob_id": "fc69405a1622c0581259e797854aadf842ac439c",
"content_id": "5633a72fc78809393e78802bd074de62a8de2049",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 322,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 14,
"path": "/ch03 - Speech Recognition/os_platform.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import os\nimport pathlib\nimport platform\n\nmyfolder = pathlib.Path.cwd()\nprint(myfolder)\nmyfile = myfolder/'files'/'example.txt'\nprint(myfile)\nif platform.system() == \"Windows\":\n os.system(f\"explorer {myfile}\")\nelif platform.system() == \"Darwin\":\n os.system(f\"open {myfile}\")\nelse:\n os.system(f\"xdg-open {myfile}\")"
},
{
"alpha_fraction": 0.6264045238494873,
"alphanum_fraction": 0.6446629166603088,
"avg_line_length": 30.64444351196289,
"blob_id": "720433e769abb70e9cf671d280e445217f939873",
"content_id": "e400ef09b4e15a3a858b7220a47e7c5d9995ce44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1424,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 45,
"path": "/ch07 - Building a Virtual Personal Assistant/timer.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import time\nimport arrow\n\n# Tell you the format to set the timer\nprint('''set your timer; you can set it to the number of hours,\n number of minutes, \n or a combination of both ''')\n# Set the timer\ninp = input(\"How long do you want to set your timer for?\\n\")\n# Find the positions of \"timer for\" and \"hour\" and \"minute\"\npos1 = inp.find(\"timer for\")\npos2 = inp.find(\"hour\")\npos3 = inp.find(\"minute\")\n# Handle the case \"set a timer for hours only\"\nif pos3 == -1:\n addhour = inp[pos1 + len(\"timer for\"):pos2]\n addminute = 0\n# Handle the case \"set a timer for minutes only\"\nelif pos2 == -1:\n addhour = 0\n addminute = inp[pos1 + len(\"timer for\"):pos3]\n print(addminute)\n# Handle the case for \"set a timer for hours and minutes\nelse:\n addhour = inp[pos1 + len(\"timer for\"):pos2]\n addminute = inp[pos2 + len(\"hour\"):pos3]\n# Current hour, minute, and second\nstartHH = arrow.now().format('H')\nstartmm = arrow.now().format('m')\nstartss = arrow.now().format('s')\n# Obtain the time for the timer to go off\nnewHH = int(startHH) + int(addhour)\nnewmm = int(startmm) + int(addminute)\nif newmm > 59:\n newmm -= 60\n newHH += 1\nnewHH = newHH % 24\nend_time = str(newHH) + \":\" + str(newmm) + \":\" + startss\nprint(\"Your timer will go off at \" + end_time)\nwhile True:\n timenow = arrow.now().format('H:m:s')\n if timenow == end_time:\n print(\"Your timer has gone off!\")\n break\n time.sleep(0.5)\n"
},
{
"alpha_fraction": 0.6644295454025269,
"alphanum_fraction": 0.6935123205184937,
"avg_line_length": 32.525001525878906,
"blob_id": "ccf0d75ef0c46baf88f2a02cd2435a9e4ebcf89a",
"content_id": "98eb53c36d763a6e0665460c47e67c9bdc8f494e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1341,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 40,
"path": "/ch14 - Financial Applications/candle_stick.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "#import needed modules\nimport matplotlib.pyplot as plt\nfrom pandas_datareader import data as pdr\nimport matplotlib.dates as mdates\nfrom mplfinance.original_flavor import candlestick_ohlc\n\n#set the start and end date\nstart_date = \"2020-05-01\"\nend_date = \"2020-05-31\"\n#choose stock ticker symbol\nticker = \"AMZN\"\n#get stock price\nstock = pdr.get_data_yahoo(ticker, start = start_date, end = end_date)\n#obtain dates\nstock['Date'] = stock.index.map(mdates.date2num)\n#choose the four daily prices: open, hihg, low, and close\ndf_ohlc = stock[['Date','Open', 'High', 'Low', 'Close']]\n#choose figure size\nfigure, fig = plt.subplots(dpi = 128, figsize = (8,4))\n#format date\nformatter = mdates.DateFormatter('%m/%d/%Y')\n#choose x-axis\nfig.xaxis.set_major_formatter(formatter)\nfig.xaxis_date()\nplt.setp(fig.get_xticklabels(), rotation = 10)\n#create teh candlestick chart\ncandlestick_ohlc(fig, \n df_ohlc.values, \n width = 0.8, \n colorup = 'black', \n colordown = 'gray')\n#put text in the chart \nplt.figtext(0.3,0.2,'Black: Close > Open')\n#put text in the chart that red color means close is lower than open\nplt.figtext(0.3,0.15,'Gray: Close < Open')\n#put chart title and axis labels\nplt.title(f'Candlesticks Chart for {ticker} in May 2020')\nplt.ylabel('Pirce')\nplt.xlabel('Date')\nplt.show()\n"
},
{
"alpha_fraction": 0.7574931979179382,
"alphanum_fraction": 0.7629427909851074,
"avg_line_length": 23.46666717529297,
"blob_id": "903a08bd7df47a2e26364f83b212690565b0fe09",
"content_id": "3df27da067742cb14a6e0de59d90cbe9c6807c13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 368,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 15,
"path": "/ch16 - Use World Languages/speak_spanish.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from io import BytesIO\n\nfrom gtts import gTTS\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\n# Convert text to speech in Spanish\ntts = gTTS(text='Buenos días',lang='es')\n# Create a temporary file \nvoice = BytesIO()\n# Save the voice output as an audio file\ntts.write_to_fp(voice)\n# Play the audio file\nvoice.seek(0)\nplay(AudioSegment.from_mp3(voice))\n"
},
{
"alpha_fraction": 0.7280701994895935,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 37.33333206176758,
"blob_id": "c8e12f261640b340ce84340a74c32681a0c8ec17",
"content_id": "a6c794b9b0f092fc7d737d8ac3e91c52f88400b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 114,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 3,
"path": "/ch05 - Speaking Applications/chat/generate_mp3.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from gtts import gTTS\ntts = gTTS('replace this file with a country music song', lang='en')\ntts.save('country.mp3')"
},
{
"alpha_fraction": 0.6787382960319519,
"alphanum_fraction": 0.7126168012619019,
"avg_line_length": 28.517240524291992,
"blob_id": "c9d9e1659291f074cd7152425aa6af396b6f4fa1",
"content_id": "0a86aabd41fa80f09884ee2dea30def82760b0fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 856,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 29,
"path": "/ch14 - Financial Applications/price_plot.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nfrom pandas_datareader import data as pdr\nimport matplotlib.dates as mdates\n\n# Set the start and end dates\nstart_date = \"2019-12-01\"\nend_date = \"2020-05-31\"\n\n# Choose stock ticker symbol\nticker = \"TSLA\"\n# Get stock price\nstock = pdr.get_data_yahoo(ticker, start = start_date, end = end_date)\nprint(stock)\n# Obtain dates\nstock['Date'] = stock.index.map(mdates.date2num)\nprint(stock['Date'])\n# Choose figure size\nfig = plt.figure(dpi = 128, figsize = (10, 6))\n# Format date to place on the x-axis\nformatter = mdates.DateFormatter('%m/%d/%Y')\nplt.gca().xaxis.set_major_formatter(formatter)\n# Plot data.\nplt.plot(stock['Date'], stock['Adj Close'], c = 'blue')\n# Format plot.\nplt.title(\"The Stock Price of Tesla\", fontsize = 16)\nplt.xlabel('Date', fontsize = 10)\nfig.autofmt_xdate()\nplt.ylabel(\"Price\", fontsize = 10)\nplt.show()\n"
},
{
"alpha_fraction": 0.5376344323158264,
"alphanum_fraction": 0.6155914068222046,
"avg_line_length": 19.66666603088379,
"blob_id": "7d6945651e7a1e21aed632af4417d52ea881c0d2",
"content_id": "591235de5d1d397644fb06b0e2974914fb513972",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 744,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 36,
"path": "/ch11 - Connect Four/conn_board.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screen\nt.setup(700,600,10,70)\nt.hideturtle()\nt.tracer(False)\nt.bgcolor(\"lightgreen\")\nt.title(\"Connect Four in Turtle Graphics\")\n# Draw six thick vertical lines\nt.pensize(5)\nfor i in range(-250,350,100): \n t.up()\n t.goto(i,-350)\n t.down()\n t.goto(i,350)\n t.up()\n# Draw five thin gray horizontal lines to form grid \nt.pensize(1)\nt.pencolor(\"gray\")\nfor i in range(-200,300,100): \n t.up()\n t.goto(-350,i)\n t.down()\n t.goto(350,i)\n t.up()\n# Write column numbers on the board\ncolnum = 1\nfor x in range(-300, 350, 100):\n t.goto(x,270)\n t.write(colnum,font = ('Arial',20,'normal'))\n colnum += 1\nt.done() \ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.6946308612823486,
"alphanum_fraction": 0.7214764952659607,
"avg_line_length": 31.22222137451172,
"blob_id": "f456387f9c4a1e58b14974b00c85a4b08117cf0a",
"content_id": "d85d6be0938df4b1f5cf8e9a3b6e178a1742f0c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 298,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 9,
"path": "/ch04 - Make Python Talk/pyttsx3_adjust.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import pyttsx3\nengine = pyttsx3.init()\nvoice_id = 1\nvoices = engine.getProperty('voices')\nengine.setProperty('voice', voices[voice_id].id)\nengine.setProperty('rate', 150)\nengine.setProperty('volume', 1.2)\nengine.say(\"This is a test of my speech id, speed, and volume.\")\nengine.runAndWait() \n"
},
{
"alpha_fraction": 0.5896226167678833,
"alphanum_fraction": 0.5896226167678833,
"avg_line_length": 22.66666603088379,
"blob_id": "5f348f6376766b54f2593896dafaeff85f04500f",
"content_id": "1118482ff554d73509c73404afe973bbe830eeef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 212,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 9,
"path": "/ch03 - Speech Recognition/stand_by.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from mysr import voice_to_text\n\nwhile True:\n print('Python is listening...')\n inp = voice_to_text()\n print(f'You just said {inp}.')\n if inp == \"stop listening\":\n print('Goodbye!')\n break"
},
{
"alpha_fraction": 0.6424116492271423,
"alphanum_fraction": 0.6673596501350403,
"avg_line_length": 25.72222137451172,
"blob_id": "c8622796b1d1bf9ce5eb71d5abef18ab883b3bb9",
"content_id": "a4b218fc32e30676ec2ab0dc8c47b8dce3b92f4f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 18,
"path": "/ch10 - Tic-Tac-Toe/mouse_click.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screen\nt.setup(620,620,360,100)\nt.title(\"How Mouse-Clicks Work in Turtle Graphics\")\n# Define a function get_xy() to print the x and y value of the point you click\ndef get_xy(x,y):\n print(f'(x, y) is ({x}, {y})') \n# Hide turtle so that you don't see the arrowhead \nt.hideturtle()\n# Bind the mouse click to the get_xy() function\nt.onscreenclick(get_xy)\nt.listen() \nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.7272727489471436,
"alphanum_fraction": 0.7342657446861267,
"avg_line_length": 27.600000381469727,
"blob_id": "ea10c91cedf16499ac0ac824b27cfd0507fa9ab2",
"content_id": "939e433b76663e694c34e14fad2f1e63d5330e24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 286,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 10,
"path": "/ch04 - Make Python Talk/pyttsx3_property.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import pyttsx3\n\nengine = pyttsx3.init()\nvoices = engine.getProperty('voices')\nfor voice in voices:\n print(voice)\nrate = engine.getProperty(\"rate\")\nprint(\"the default speed of the speech is\", rate)\nvol = engine.getProperty(\"volume\")\nprint(\"the default volume of the speech is\", vol)\n"
},
{
"alpha_fraction": 0.6167076230049133,
"alphanum_fraction": 0.6650286912918091,
"avg_line_length": 23.918367385864258,
"blob_id": "64acd0f9f02d28eded77b38f90759e5fe8be6578",
"content_id": "def8f78d2bb403b22cb261c3e15291b867b2d9e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1221,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 49,
"path": "/ch12 - Guess The Word Game/show_coins.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\nfrom tkinter import PhotoImage\nfrom time import sleep\n\n# Set up the board\nt.setup(600,500)\nt.hideturtle()\nt.tracer(True)\nt.bgcolor(\"lavender\")\nt.title(\"Guess the Word Game in Turtle Graphics\")\n# Define a variable to count how many guesses left\nscore = 6\n# Create a second turtle to show guesses left\nleft = t.Turtle()\nleft.up()\nleft.hideturtle()\nleft.goto(-290,200)\nleft.write(f\"guesses left: {score}\", font = ('Arial',20,'normal'))\n# Put incorrect guesses on top\nt.up()\nt.goto(-290,150)\nt.write(\"incorrect guesses:\", font = ('Arial',20,'normal'))\n# Put four empty spaces for the four letters at bottom\nfor x in range(4):\n t.goto(-275+150*x,-200)\n t.down()\n t.goto(-175+150*x,-200) \n t.up()\n# Load a picture of the coin to the script\ncoin = PhotoImage(file = \"cash.png\").subsample(10,10)\nt.addshape(\"coin\", t.Shape(\"image\", coin))\n# Create six coin on screen \ncoins = [0]*6\nfor i in range(6):\n coins[i] = t.Turtle('coin')\n coins[i].up()\n coins[i].goto(-100 + 50 *i, -10)\nt.update()\nsleep(3)\n# Make the coins disappear one at a time\nfor i in range(6):\n coins[i].hideturtle()\n t.update()\n sleep(1)\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.727078914642334,
"alphanum_fraction": 0.7292110919952393,
"avg_line_length": 30.266666412353516,
"blob_id": "185aa468e82d5e37dc621eedab5b8dc13b399beb",
"content_id": "1d807ae7fc1b38164331299cad6d393cf31e2f13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1876,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 60,
"path": "/ch16 - Use World Languages/voice_translator.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from io import BytesIO\n\nfrom translate import Translator\nimport speech_recognition as sr\nfrom gtts import gTTS\nfrom pydub import AudioSegment\nfrom pydub.playback import play\n\n# Initiate speech recognition\nspeech = sr.Recognizer()\n# Prompt you to say something in English\nprint('say something in English') \n# Capture spoken English \nwith sr.Microphone() as source:\n speech.adjust_for_ambient_noise(source)\n try:\n audio = speech.listen(source)\n my_input = speech.recognize_google(audio, language=\"en\")\n print(f\"you said: {my_input}\") \n except sr.UnknownValueError:\n pass\n# Specify the input and output languages\ntranslator = Translator(from_lang=\"en\",to_lang=\"es\")\n# Do the actual translation\ntranslation = translator.translate(my_input)\nprint(translation)\n# Convert text to speech in Spanish\ntts = gTTS(text=translation,lang='es')\n# Create a temporary file \nvoice = BytesIO()\n# Save the voice output as an audio file\ntts.write_to_fp(voice)\n# Play the audio file\nvoice.seek(0)\nplay(AudioSegment.from_mp3(voice))\n# Prompt you to say something in Spanish\nprint('say something in Spanish') \n# Capture spoken Spanish \nwith sr.Microphone() as source:\n speech.adjust_for_ambient_noise(source)\n try:\n audio = speech.listen(source)\n my_input = speech.recognize_google(audio, language=\"es\")\n print(f\"you said: {my_input}\") \n except sr.UnknownValueError:\n pass\n# Specify the input and output languages\ntranslator = Translator(from_lang=\"es\",to_lang=\"en\")\n# Do the actual translation\ntranslation = translator.translate(my_input)\nprint(translation)\n# Convert text to speech in Spanish\ntts = gTTS(text=translation,lang='en')\n# Create a temporary file \nvoice = BytesIO()\n# Save the voice output as an audio file\ntts.write_to_fp(voice)\n# Play the audio file\nvoice.seek(0)\nplay(AudioSegment.from_mp3(voice))\n"
},
{
"alpha_fraction": 0.6656990647315979,
"alphanum_fraction": 0.6797291040420532,
"avg_line_length": 33.400001525878906,
"blob_id": "f16591fdf728e81645fa4ace1f53502ae5d6ba4d",
"content_id": "042ec1eb39a78ce1dd573367d9e84c79083a3e4e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2067,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 60,
"path": "/ch15 - Stock Market Watch/bitcoin_watch.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import tkinter as tk\nimport requests\n\nimport arrow\n\nfrom mptpkg import print_say\n\n# Specify the url to find the bitcoin price\nurl = 'https://api.coindesk.com/v1/bpi/currentprice.json'\n# Create a root window hold all widgets\nroot = tk.Tk()\n# Specify the title and size of the root window\nroot.title(\"Bitcoin Watch\")\nroot.geometry(\"1000x400\")\n# Create a first label using hte Label() function\nlabel = tk.Label(text=\"\", fg=\"Blue\", font=(\"Helvetica\", 80))\nlabel.pack()\n# Create a second label\nlabel2 = tk.Label(text=\"\", fg=\"Red\", font=(\"Helvetica\", 60))\nlabel2.pack()\n# Set up the price bounds\nresponse = requests.get(url)\nresponse_json = response.json()\noldprice = response_json['bpi']['USD']['rate_float']\nmaxprice = oldprice * 1.05\nminprice = oldprice * 0.95\nprint_say(f'The Bitcoin price is now {oldprice}!')\n\n\n# Define the bitcoin_watch() function\ndef bitcoin_watch():\n global oldprice\n # Get the live information from bitcoin url\n response = requests.get(url)\n response_json = response.json()\n price = response_json['bpi']['USD']['rate_float']\n # If there is update in price, announce it \n if price != oldprice:\n oldprice = price\n print_say(f'The Bitcoin price is now {oldprice}!')\n # If price goes out of bounds, announce it \n if price > maxprice:\n print_say('The Bitcoin price has gone above the upper bound!')\n if price < price:\n print_say('The Bitcoin price has gone below the lower bound!')\n # Obtain current date and time information \n tdate = arrow.utcnow().format('MMMM DD, YYYY')\n tm = arrow.utcnow().format('hh:mm:ss A')\n # Put the date and time information in the first label \n label.configure(text=tdate + \"\\n\" + tm)\n # Put all the five messages on the stock market in the second label \n label2.configure(text=f'Bitcoin: {price}', justify=tk.LEFT)\n # call the bitcoin_watch() function after 1000 milliseconds\n root.after(1000, bitcoin_watch)\n\n\n# call the bitcoin_watch() function\nbitcoin_watch()\n# run the game loop\nroot.mainloop()\n\n\n\n"
},
{
"alpha_fraction": 0.6844305396080017,
"alphanum_fraction": 0.6875653266906738,
"avg_line_length": 33.17856979370117,
"blob_id": "63ac6dd29a8b3525e3610b5166f95aaaadc1b762",
"content_id": "8a29bc106abe58fb96fdc4f918723f6dbdcc0b7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 957,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 28,
"path": "/ch07 - Building a Virtual Personal Assistant/emails.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import smtplib\n\n# Build a dictionary of names and emails\nemails = {'mark':'[email protected]',\n 'sarah':'Sarah email address here',\n 'chris':'Chris email address here'}\n# Different email providers have different domain name and port number\nmysmt = smtplib.SMTP('smtp.gmail.com', 587)\nmysmt.ehlo()\nmysmt.starttls()\n# Use your own login info; you may need an app password\nmysmt.login('{your email here}', '{your password here}')\n# Ask for the name of of the recipeint\nname = input('Who do you want to send the email to?\\n')\nemail = emails[name]\nprint(f\"You just said {name}.\")\n# Ask for the subject line\nsubline = input('What is the subject line?\\n')\nprint(f\"You just said {subline}.\")\n# Ask for the email content\ncontent = input('What is the email content?\\n')\nprint(f\"You just said {content}.\")\n# Send the actual email\nmysmt.sendmail('[email protected]', email, \n f'Subject: {subline}.\\nHello, {content}.')\n{}\nprint('Ok, email sent')\nmysmt.quit()\n"
},
{
"alpha_fraction": 0.6315789222717285,
"alphanum_fraction": 0.7171052694320679,
"avg_line_length": 17.875,
"blob_id": "52f2c2054641c2a921a0c71c9ad76d61dd22c5b6",
"content_id": "c07f1558f6c72f9829ff1b5a971fc58c0ea60149",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 152,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 8,
"path": "/ch09 - Graphics and Animation with the Turtle Module/set_up_screen.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('SpringGreen3')\nt.title('Setting Up A Screen with Turtle Graphics')\nt.done()\nt.bye() \n"
},
{
"alpha_fraction": 0.7901498675346375,
"alphanum_fraction": 0.7901498675346375,
"avg_line_length": 34.92307662963867,
"blob_id": "5e5fe180d2db25561eaa36557f1164a427bdee41",
"content_id": "5a8eb684ccf378c5762e6fc4e21b187b9ceb4687",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 477,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 13,
"path": "/ch16 - Use World Languages/english_chinese.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "# Import the Translator function from the translate module\nfrom translate import Translator\n\n# Specify the input and output languages\ntranslator = Translator(from_lang=\"en\",to_lang=\"zh\")\n# Do the actual translation\ntranslation = translator.translate(\"hello all\")\nprint(translation)\n# Specify the input and output languages\ntranslator = Translator(from_lang=\"zh\",to_lang=\"en\")\n# Do the actual translation\ntranslation = translator.translate(\"请再说一遍\")\nprint(translation)\n"
},
{
"alpha_fraction": 0.5797872543334961,
"alphanum_fraction": 0.686170220375061,
"avg_line_length": 13.461538314819336,
"blob_id": "b814069ab9f4572b92f288fa24cf9a3763c1b58d",
"content_id": "7b9704454bbd9fa2ce60a5e3fa549734266e4fc0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 188,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 13,
"path": "/ch09 - Graphics and Animation with the Turtle Module/show_turtle.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('SpringGreen')\nt.title('Show Turtle')\nt.shape('turtle')\nt.forward(200)\nt.right(90)\nt.up()\nt.forward(100)\nt.done()\nt.bye()\n"
},
{
"alpha_fraction": 0.7002187967300415,
"alphanum_fraction": 0.7089715600013733,
"avg_line_length": 40.54545593261719,
"blob_id": "15308522d5458d7ac18bf1fd5cd4dba304db7027",
"content_id": "1c52a012c43c592bbb21c746b4b15e732303626f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 457,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 11,
"path": "/ch07 - Building a Virtual Personal Assistant/get_time.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import arrow\n\n# Current time in HH:MM:SS format\ncurrent_time = arrow.now().format('H:m:s')\nprint('the current time is', current_time)\ncurrent_time12 = arrow.now().format('hh:mm:ss A')\nprint('the current time is', current_time12)\n# We can also print out hour, minute, and second individually\nprint(\"the current hour is\", arrow.now().format('H'))\nprint(\"the current minute is\", arrow.now().format('m'))\nprint(\"the current second is\", arrow.now().format('s'))\n"
},
{
"alpha_fraction": 0.5987654328346252,
"alphanum_fraction": 0.709876537322998,
"avg_line_length": 15.199999809265137,
"blob_id": "88c1a1ea28f7b493700304ee98eb05707ba0dbf0",
"content_id": "185b6fd1b23c359088162eeffba23500ec98413a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 10,
"path": "/ch09 - Graphics and Animation with the Turtle Module/forward_backward.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('blue')\nt.title('Movements in Turtle Graphics')\nt.forward(200)\nt.backward(300)\nt.done()\nt.bye()\n"
},
{
"alpha_fraction": 0.7204301357269287,
"alphanum_fraction": 0.7419354915618896,
"avg_line_length": 22.25,
"blob_id": "b7668455e29ee0d97b1e092a79e2a0f135c49721",
"content_id": "f5cf0db9ccd1c31393843633bb6dc3039c0524dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 93,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 4,
"path": "/ch04 - Make Python Talk/test_pyttsx3.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import pyttsx3\nengine = pyttsx3.init()\nengine.say(\"hello, how are you?\")\nengine.runAndWait()\n"
},
{
"alpha_fraction": 0.5781710743904114,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 14.409090995788574,
"blob_id": "ba227e3c6ee93478ab52ffeb9622e32f7b665fab",
"content_id": "4d840f7a4901ae267859c2b2735f10c2b496a3ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 339,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 22,
"path": "/ch09 - Graphics and Animation with the Turtle Module/triangle.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\nt.Screen()\nt.setup(600,500,100,200)\nt.bgcolor('springgreen3')\nt.title('Python Turtle Graphics')\nt.hideturtle()\nt.tracer(False)\nt.pencolor('blue')\nt.pensize(5)\nt.up()\nt.goto(-50,-50)\nt.down()\nt.goto(50,-50)\nt.goto(0,100)\nt.goto(-50,-50)\nt.update()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.6230191588401794,
"alphanum_fraction": 0.6230191588401794,
"avg_line_length": 32.30555725097656,
"blob_id": "39c191a06fc0a7ef11e9184b5c442be0e28855dc",
"content_id": "a256eb480a1689afafc69a2f1617ca07eeeeab18",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1199,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 36,
"path": "/ch06 - Web Scraping Podcasts, Radios, and Videos/voice_live_radio.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "# Put chromedriver.exe in the same folder as this script\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options \n\n# Import functions from the loacal package\nfrom mptpkg import voice_to_text, print_say\n\n# Define a live_radio() function\ndef live_radio():\n global button\n chrome_options = Options() \n chrome_options.add_argument(\"--headless\") \n browser = webdriver.Chrome\\\n (executable_path='./chromedriver',options=chrome_options)\n browser.get(\"https://onlineradiobox.com/us/\")\n button = browser.find_element_by_xpath('//*[@id=\"b_top_play\"]')\n button.click()\n# Start the loop\nwhile True: \n print_say(\"How may I help you?\")\n inp = voice_to_text().lower()\n print_say(f'You just said {inp}.')\n if inp == \"stop listening\":\n print_say('Goodbye!')\n break\n elif \"radio\" in inp: \n print_say('OK, play live radio online for you!')\n live_radio()\n # Say stop playing to stop the radio any time\n while True:\n background = voice_to_text().lower()\n if \"stop playing\" in background:\n button.click()\n break\n else:\n continue\n"
},
{
"alpha_fraction": 0.7369791865348816,
"alphanum_fraction": 0.7473958134651184,
"avg_line_length": 26.428571701049805,
"blob_id": "1e1ccf83de7a71bffe9576b3dceb30ec81cdd01e",
"content_id": "b2fd5f5a605da4d7317b8a907ce7ed0bdb8410e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 14,
"path": "/ch05 - Speaking Applications/wiki_hs.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import wikipedia\n\n# Import functions from the loacal package\nfrom mptpkg import voice_to_text, print_say\n\n# Ask what you want to know\nprint_say(\"What do you want to know?\")\n# Capture your voice input\nmy_query = voice_to_text()\nprint_say(f\"you said {my_query}\")\n# Obtain answer from Wikipedia\nans = wikipedia.summary(my_query)\n# Speak the answer in a human voice\nprint_say(ans[0:200])\n"
},
{
"alpha_fraction": 0.8056679964065552,
"alphanum_fraction": 0.8056679964065552,
"avg_line_length": 31.933332443237305,
"blob_id": "6b9355b2bd0d9c0bb4f342095c50b8c7ebd97565",
"content_id": "a74dc35e8ebbd4798b82deb0eb6e9a40018dd89e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 494,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 15,
"path": "/mptpkg/__init__.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "from .mysr import voice_to_text\nfrom .mysay import print_say\nfrom .mywakeup import wakeup\nfrom .mytimer import timer\nfrom .myalarm import alarm\nfrom .myjoke import joke\nfrom .myemail import email\nfrom .myknowall import know_all\nfrom .mymusic import music_play, music_stop\nfrom .mynews import news_brief, news_stop\nfrom .myradio import live_radio, radio_stop\nfrom .myttt import ttt\nfrom .myconn import conn\nfrom .mystock import stock_market, stock_price\nfrom .mytranslate import voice_translate\n"
},
{
"alpha_fraction": 0.6161074042320251,
"alphanum_fraction": 0.6724832057952881,
"avg_line_length": 23.032258987426758,
"blob_id": "f6c9072521460c438b068f288d68a39e54ca192d",
"content_id": "73c99a9d193982ccfb104116c2875268a8ea3079",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 745,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 31,
"path": "/ch12 - Guess The Word Game/guess_word_board.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the board\nt.setup(600,500)\nt.hideturtle()\nt.tracer(False)\nt.bgcolor(\"lavender\")\nt.title(\"Guess the Word Game in Turtle Graphics\")\n# Define a variable to count how many guesses left\nscore = 6\n# Create a second turtle to show guesses left\nleft = t.Turtle()\nleft.up()\nleft.hideturtle()\nleft.goto(-290,200)\nleft.write(f\"guesses left: {score}\", font = ('Arial',20,'normal'))\n# Put incorrect guesses on top\nt.up()\nt.goto(-290,150)\nt.write(\"incorrect guesses:\", font = ('Arial',20,'normal'))\n# Put four empty spaces for the four letters at bottom\nfor x in range(4):\n t.goto(-275+150*x,-200)\n t.down()\n t.goto(-175+150*x,-200) \n t.up()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
},
{
"alpha_fraction": 0.5947368144989014,
"alphanum_fraction": 0.6236842274665833,
"avg_line_length": 22,
"blob_id": "5c47666f5a4b71cbe80381dc76a3c561878e4585",
"content_id": "6841fe615c263660b233375d3cac525f754e2287",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 760,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 33,
"path": "/ch09 - Graphics and Animation with the Turtle Module/turtle_clock.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\nimport time\n\nimport arrow\n\n# Set up the screen\nt.setup(800,600, 10, 70)\nt.tracer(False)\nt.bgcolor('lightgreen')\nt.hideturtle()\n# Put the program in an infinite loop\nwhile True:\n # Clear the screen\n t.clear()\n # Obtain the current time\n current_time = arrow.now().format('hh:mm:ss A')\n t.color('blue')\n t.up()\n t.goto(0,50)\n # Write the first line of text\n t.write('The Current Time Is\\n', align = 'center', font = ('Arial',50,'normal'))\n t.color('red')\n t.goto(0,-100)\n # Write what time it is\n t.write(current_time, align = 'center', font = ('Arial',80,'normal'))\n time.sleep(1)\n # Put everything on screen\n t.update()\nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n\n"
},
{
"alpha_fraction": 0.7115384340286255,
"alphanum_fraction": 0.7173076868057251,
"avg_line_length": 29.41176414489746,
"blob_id": "eb8b62c0ab83786c1042db6144df3b0068dd65e9",
"content_id": "8643bb271d6caa77b0fab076578780f5d03b677a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 520,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 17,
"path": "/ch06 - Web Scraping Podcasts, Radios, and Videos/parse_local.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "# Import the Beautiful Soup library\nfrom bs4 import BeautifulSoup\n\n# Open the local HTML file as a text file\ntextfile = open(\"UKYexample.html\", encoding='utf8')\n# Use the findAll() function to locate all <p> tags\nsoup = BeautifulSoup(textfile, \"html.parser\")\nptags = soup.findAll(\"p\")\n# Print out <p> tags\nprint(ptags)\n# Find the <a> tag nested in the third <p> tag\natag = ptags[2].find(\"a\")\nprint(atag)\n# Print the web address of the hyperlink\nprint(atag['href'])\n# Print the content of the <a> tag\nprint(atag.text)\n\n\n\n"
},
{
"alpha_fraction": 0.533450722694397,
"alphanum_fraction": 0.61091548204422,
"avg_line_length": 17.933332443237305,
"blob_id": "b16a978a4f3e8be33f1dd72e45712091e99b1255",
"content_id": "df2148210bec81e2f86c8637afebb649109994d1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 568,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 30,
"path": "/ch09 - Graphics and Animation with the Turtle Module/grid_lines.py",
"repo_name": "ryanhanli/Talking-Python",
"src_encoding": "UTF-8",
"text": "import turtle as t\n\n# Set up the screen \nt.Screen()\nt.setup(810,710, 10, 70)\nt.hideturtle()\nt.tracer(False)\nt.bgcolor('lightgreen')\n# Draw the vertical lines to create 7 columns\nt.pensize(5)\nfor i in range(-350,400,100): \n t.up()\n t.goto(i, -298)\n t.down()\n t.goto(i, 303)\n t.up()\n# Draw the horizontal lines to separate the screen in 6 rows\nt.pensize(1)\nt.color('gray')\nfor i in range(-300,400,101): \n t.up()\n t.goto(-350,i)\n t.down()\n t.goto(350,i)\n t.up() \nt.done()\ntry:\n t.bye()\nexcept t.Terminator:\n print('exit turtle')\n"
}
] | 45 |
panhsu/distributed-fast
|
https://github.com/panhsu/distributed-fast
|
11b257de8724989893c894d2559ec63b179908ed
|
aaec6a9936bdd73906079815aae7ec477de3688b
|
4683a517ee46cbf016cc9869868df3ebb38a53c4
|
refs/heads/master
| 2021-01-21T21:32:48.701995 | 2016-07-27T19:15:18 | 2016-07-27T19:15:18 | 51,769,036 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5893837809562683,
"alphanum_fraction": 0.5918242931365967,
"avg_line_length": 32.14583206176758,
"blob_id": "758a89d56f5976011e2a14fdbbd16e3a2ee788ae",
"content_id": "97774f0a77306cea0351e8591e677be7b05fe5b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1639,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 48,
"path": "/postman.py",
"repo_name": "panhsu/distributed-fast",
"src_encoding": "UTF-8",
"text": "import smtplib\r\nfrom email.MIMEMultipart import MIMEMultipart\r\nfrom email.MIMEText import MIMEText\r\nfrom email.MIMEBase import MIMEBase\r\nfrom email import encoders\r\nfrom email.mime.application import MIMEApplication \r\nfrom os.path import basename\r\nfrom email.utils import COMMASPACE, formatdate\r\nimport os\r\n\r\n\r\nclass postman():\r\n \r\n def __init__(self):\r\n self.server = smtplib.SMTP('company.smtp.server')\r\n self.usename = \"\"\r\n self.password = \"\"\r\n \r\n \r\n \r\n def mail_attachment(self,subject,receivers,filepath,html_content):\r\n \r\n # Construct email\r\n msg = MIMEMultipart()\r\n msg['From'] = \"Team Name\"\r\n msg['To'] = receivers\r\n msg['Subject'] = subject\r\n for file in filepath:\r\n if file is not None:\r\n with open(file, \"rb\") as attachment:\r\n body = attachment.read()\r\n msg.attach(MIMEApplication(body,Content_Disposition='attachment; filename=\"%s\"' % basename(file),Name=basename(file)))\r\n attachment.close()\t\r\n msg.attach(MIMEText(\"<html>\"+str(html_content)+\"</html>\", 'html'))\r\n text = msg.as_string()\r\n self.server.sendmail(\"AEGIS\", receivers.split(\";\"), text)\r\n #if filepath is not None:\r\n # attachment.close()\r\n\r\nif __name__ ==\"__main__\":\r\n filepath = \"xxx.html\"\r\n filename = basename(filepath)\r\n title = os.path.splitext(filename)[0]\r\n result = \"(0)\"\r\n build = \"7.0\"\r\n subject = \"[\"+build+\"] \"+\"FAST Report:\"+title+result\r\n sender = postman()\r\n sender.mail_attachment(subject,'[email protected]',filepath,filepath)\r\n"
},
{
"alpha_fraction": 0.48186424374580383,
"alphanum_fraction": 0.48571428656578064,
"avg_line_length": 35.540740966796875,
"blob_id": "ee1e7ef0e61925a39280d2df95b108687515a8a6",
"content_id": "f45758c045ecc97eaa006259c53a0a93bce75b75",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4935,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 135,
"path": "/time_consumption.py",
"repo_name": "panhsu/distributed-fast",
"src_encoding": "UTF-8",
"text": "\nimport ConfigParser\nimport os\nimport re\n \nclass record_time_consumption(ConfigParser.ConfigParser):\n time_consumtion = {}\n dict_time_cost = {}\n\t\n \n \n def as_dict(self):\n def upper_kdict(d):\n r = {}\n for k, v in d.items():\n K = k.upper()+\"-\"\n r[K] = v if not r.__contains__(K) else v + r[K]\n return r\n \n d = dict(self._sections)\n for k in d: \n d[k] = dict(self._defaults, **d[k])\n d[k].pop('__name__', None)\n d[k] = upper_kdict(d[k])\n self.dict_time_cost = d\n return d \n\t\t\n def get_dict_time_cost(self):\n return self.dict_time_cost\n\t\t\n def pa_reportfiles_to_ini(self,dir_path,filelist):\n \tdict_cases_timecost = {}\n section = re.match(\"(.*)\\-(.*)\\-(.*).log\",filelist[0]).group(2)\n self.time_consumtion.update({section:dict_cases_timecost})\n #dict_cases_timecost = self.time_consumtion[section]\n #print self.time_consumtion\n for f in filelist:\n full_filepath = os.path.join(dir_path,f)\n with open(full_filepath,'r') as rf:\n for line in rf.readlines(): \n \n m = re.match(\"\\[(.*)\\-(\\d*)\\]\\s*\\[(\\d+)\\]\\s*\\[(.*)\\]\",line)\n if not (m is None):\n \t#print line\n case_id = m.group(1)\n cost_time = m.group(3)\n n = re.match(\"(.*)\\-(\\d*)\",case_id)\n if not (n is None):\n case_id = n.group(1)\n \n if case_id in dict_cases_timecost.keys():\n cost = dict_cases_timecost[str(case_id)] \n cost_time = int(cost)+ int(cost_time)\n \n dict_cases_timecost.update({str(case_id).upper():int(cost_time)})\n return self.time_consumtion\n\n\n def save_as_ini(self,ini_file,d):\n config = ConfigParser.RawConfigParser()\n for section in d.keys():\n config.add_section(section)\n dict_items = d[section]\n for cid in dict_items.keys():\n #print section,cid,dict_items[cid]\n config.set(section,cid,dict_items[cid])\n with open(ini_file,'w') as configfile:\n config.write(configfile)\n\n def get_optimize_caseslist(self,d,workers_count,cases_id,section_name):\n \n \n dict_items = dict([a, int(x)] for a, x in d[section_name].iteritems())\n total_config_cid_count = len(dict_items)\n total_cids_count = len(cases_id)\n cid_list = []\n opt_dict = {}\n avg_cid_num = total_cids_count / workers_count \n sorted_tuple = sorted(dict_items.items(), key=lambda p: int(p[1]))\n sorted_cid_list = [ cid for (cid, cost) in sorted_tuple]\n cid_not_in_list= list(set(cases_id) - set(sorted_cid_list))\n cid_extra_in_config = list(set(sorted_cid_list)-set(cases_id))\n cid_list = list(set(sorted_cid_list) - set(cid_extra_in_config))\n cid_not_in_list_counts = len(cid_not_in_list)\n avg_best_cost = sum(dict_items.itervalues()) / workers_count\n print avg_best_cost\n cid_cost_dict = {}\n l = []\n sorted_cid_list = []\n worker_idx = 0\n total_cids_cost = 0\n acc_cid_cost = 0\n for cid, cid_cost in sorted_tuple:\n if cid in cid_list:\n \ttotal_cids_cost += cid_cost\n \tcid_cost_dict.update({cid:cid_cost})\n \tsorted_cid_list.append(cid)\n counter = 0\n cid_list_len = len(sorted_cid_list)\n avg_cid_cost = total_cids_cost / workers_count\n while (workers_count - worker_idx) != 1:\n \n if acc_cid_cost >= avg_cid_cost:\n opt_dict.update({worker_idx:l})\n counter = 0\n acc_cid_cost = 0\n worker_idx += 1\n l =[]\n #re-calc\n remain_workers = workers_count - worker_idx\n avg_cid_cost = sum(cid_cost_dict.itervalues())/remain_workers\n elif(counter==0):\n cid = sorted_cid_list[-1]\n cid_cost = cid_cost_dict[cid]\n l.append(cid)\n acc_cid_cost = cid_cost\n sorted_cid_list.remove(cid)\n del cid_cost_dict[cid]\n counter+=1\n else:\n \tcid = sorted_cid_list[0]\n \tcid_cost = cid_cost_dict[cid]\n \tl.append(cid)\n \tacc_cid_cost += cid_cost\n sorted_cid_list.remove(cid)\n del cid_cost_dict[cid]\n \n\n cid_list_len -= 1\n \n \n\n opt_dict.update({worker_idx:sorted_cid_list})\n opt_list = [ opt_dict[k] for k in opt_dict.keys()] \n\n return opt_list\n\n"
},
{
"alpha_fraction": 0.732846736907959,
"alphanum_fraction": 0.732846736907959,
"avg_line_length": 27.54166603088379,
"blob_id": "9ceb1ca830b9216f2ebd8d89012e224dbedd92c9",
"content_id": "a1596ac07870715dae5e010a9ff50f85654ebd91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 685,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 24,
"path": "/README.md",
"repo_name": "panhsu/distributed-fast",
"src_encoding": "UTF-8",
"text": "[Synopis]\nFor effective verify the software quality without too many manul control.\nThis is for trigger multiple platforms and automatically return the result report by email. I only post some scripts which I used for this project.\n\n</br>[Installation]\n</br>pyspherie\n</br>html\n\n</br>[Files]\n</br>trigger.py \n</br> - the main control follow\n</br>config.py \n</br> - copy source to worker machines\n</br> - worker info: account, pwd\n</br>postman.py\n</br> - send mail and attachments\n</br>virtualmachine.py\n</br> - control Esxi and workers\n</br>report.py\n</br> - generate report\n</br>time_consumptioon.py\n</br> - calculate test cases cost \n</br>watchdog.py\n</br> -monitor the main follows\n"
}
] | 3 |
kashgupta/NLP_Language_Models
|
https://github.com/kashgupta/NLP_Language_Models
|
72e21e9299a7233f42a083719bbf694aa944d0cb
|
2e4e9c392a6ba1a50efefd316862cb0519a77180
|
d1059e56fdc31af1dd11e2a3fb94e41a141ddc28
|
refs/heads/master
| 2021-03-27T19:08:55.924321 | 2018-02-14T11:41:34 | 2018-02-14T11:41:34 | 121,170,917 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.763668417930603,
"alphanum_fraction": 0.7742504477500916,
"avg_line_length": 283,
"blob_id": "5bd0f1ccf1552baf78602ce9daf1d35432a08220",
"content_id": "769f4dc6998fac00c1ac3e12b8373ab14909ea81",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 567,
"license_type": "no_license",
"max_line_length": 348,
"num_lines": 2,
"path": "/README.txt",
"repo_name": "kashgupta/NLP_Language_Models",
"src_encoding": "UTF-8",
"text": "The script for generating labels was written in the __main__ function so the language_model.py script can just be run as is in the terminal. It will output to labels.txt by itself with k=0.05 and orders of 1, 2 and 3. \nIn the language_models.py file, to change paramaters in the __main__ function, simply navigate to the variables add_k and order_max in order to change the order of the LMs or the add_k. This is how we tested our function when we wanted to output the labels. Otherwise, we wrote scripts to test on perplexity and try to find values that minimize it."
},
{
"alpha_fraction": 0.6199012398719788,
"alphanum_fraction": 0.630144476890564,
"avg_line_length": 30.606935501098633,
"blob_id": "a231395020fa8f7e3f2c097089d9e13c0ae9bcea",
"content_id": "b349d0881c4104c90d6b6a41d8fd04f22ea74df5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5475,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 173,
"path": "/language_model.py",
"repo_name": "kashgupta/NLP_Language_Models",
"src_encoding": "UTF-8",
"text": "from collections import *\nfrom random import random\nimport math\nimport os\nfrom operator import itemgetter\n\ndef train_char_lm(fname, order=4, add_k=1):\n ''' Trains a language model.\n\n This code was borrowed from \n http://nbviewer.jupyter.org/gist/yoavg/d76121dfde2618422139\n\n Inputs:\n fname: Path to a text corpus.\n order: The length of the n-grams.\n add_k: k value for add-k smoothing. NOT YET IMPLMENTED\n\n Returns:\n A dictionary mapping from n-grams of length n to a list of tuples.\n Each tuple consists of a possible net character and its probability.\n '''\n\n data = open(fname).read()\n lm = defaultdict(Counter)\n pad = \"~\" * order\n data = pad + data\n add_k = float(add_k)\n possible_char = [chr(i) for i in range(127)]\n for i in range(len(data)-order):\n history, char = data[i:i+order], data[i+order]\n lm[history][char]+=1\n def normalize(counter):\n V = len(possible_char)\n s = float(sum(counter.values())) + V*float(add_k)\n return {c: (((counter[c]+add_k)/s) if c in counter else add_k/s) for c in possible_char}\n outlm = {hist:normalize(chars) for hist, chars in lm.items()}\n outlm['<UNK>'] = normalize(Counter())\n return outlm\n\n\ndef generate_letter(lm, history, order):\n ''' Randomly chooses the next letter using the language model.\n \n Inputs:\n lm: The output from calling train_char_lm.\n history: A sequence of text at least 'order' long.\n order: The length of the n-grams in the language model.\n \n Returns: \n A letter\n '''\n \n history = history[-order:]\n if history in lm:\n dist = lm[history]\n else:\n dist = lm['<UNK>']\n x = random()\n for c,v in dist.items():\n x = x - v\n if x <= 0: return c\n \n \ndef generate_text(lm, order, nletters=500):\n '''Generates a bunch of random text based on the language model.\n \n Inputs:\n lm: The output from calling train_char_lm.\n history: A sequence of previous text.\n order: The length of the n-grams in the language model.\n \n Returns: \n A letter \n '''\n history = \"~\" * order\n out = []\n for i in range(nletters):\n c = generate_letter(lm, history, order)\n history = history[-order:] + c\n out.append(c)\n return \"\".join(out)\n\ndef perplexity(test_filename, lm, order=4):\n '''Computes the perplexity of a text file given the language model.\n \n Inputs:\n test_filename: path to text file\n lm: The output from calling train_char_lm.\n order: The length of the n-grams in the language model.\n '''\n test = open(test_filename).read()\n pad = \"~\" * order\n test = pad + test\n log_sum = 0\n N = 0\n for i in range(len(test)-order):\n history, char = test[i:i+order], test[i+order]\n if char == '’':\n char = \"'\"\n if char == '—':\n char = '-'\n if char == '“':\n char = '\"'\n if char == '”':\n char = '\"'\n if history in lm:\n log_sum += math.log(float(1)/lm[history][str(char)])\n else:\n log_sum += math.log(float(1)/lm['<UNK>'][str(char)])\n N+=1\n\n return math.exp(log_sum/N)\n\n\ndef calculate_prob_with_backoff(char, history, lms, lambdas):\n '''Uses interpolation to compute the probability of char given a series of \n language models trained with different length n-grams.\n\n Inputs:\n char: Character to compute the probability of.\n history: A sequence of previous text.\n lms: A list of language models, outputted by calling train_char_lm.\n lambdas: A list of weights for each lambda model. These should sum to 1.\n \n Returns:\n Probability of char appearing next in the sequence.\n '''\n histories = [history[-(i+1):] for i in range(len(lms))]\n contains = [histories[i] in lms[i] for i in range(len(lms))]\n return sum(lambdas[i]*lms[i][histories[i]][char] if contains[i] else lambdas[i]*lms[i]['<UNK>'][char] for i in range(len(lambdas)))\n\n\ndef set_lambdas(lms, dev_filename):\n '''Returns a list of lambda values that weight the contribution of each n-gram model\n\n This can either be done heuristically or by using a development set.\n\n Inputs:\n lms: A list of language models, outputted by calling train_char_lm.\n dev_filename: Path to a development text file to optionally use for tuning the lmabdas.\n\n Returns:\n Probability of char appearing next in the sequence.\n '''\n lambdas_init = [1.0/len(lms) for i in range(len(lms))]\n #perplexities = [perplexity(dev_filename, lms[i], i+1) for i in range(len(lms))]\n\n lambdas = lambdas_init\n return lambdas\n\nif __name__ == '__main__':\n print('Training language model')\n lm = train_char_lm(\"shakespeare_input.txt\", order=2)\n print(generate_text(lm, 2))\n train_dir = 'train'\n models = []\n order_max = 3\n for fname in os.listdir(train_dir):\n #testing out k = 0.05 and orders of 1 through 3\n lms_temp = [train_char_lm(train_dir + '/' + fname, order=i, add_k=0.05) for i in range(1,order_max+1)]\n models.append((fname[:-4], lms_temp))\n output = open('labels.txt', 'w')\n with open('cities_test.txt') as f:\n for line in f:\n results = []\n for model in models:\n log_prob = 0\n for i in range(len(line) - order_max):\n history, char = line[i:i + order_max], line[i + order_max]\n log_prob += math.log(calculate_prob_with_backoff(char, history, model[1], set_lambdas(model[1], 'val/af.txt')))\n results.append((model[0], log_prob))\n best = max(results, key=itemgetter(1))\n output.write(best[0] + '\\n')"
}
] | 2 |
anandkalpe18/Recommender-System
|
https://github.com/anandkalpe18/Recommender-System
|
17cd41b7dcd596c1ad64f4afd31ad526cae1d8a1
|
2c47650832ef5caebd19034e3d3a4292ecfadcda
|
b406aa30eb4ba08b961608d08a1cb29192a03297
|
refs/heads/master
| 2022-07-19T04:17:14.561703 | 2020-05-25T06:25:30 | 2020-05-25T06:25:30 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6842545866966248,
"alphanum_fraction": 0.6917923092842102,
"avg_line_length": 24.7391300201416,
"blob_id": "e86e07cc5218bc0813903211679833c38b71a8ee",
"content_id": "509d50af1daa9bab2e096c805455f41bbe05910f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1194,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 46,
"path": "/Movie_Recommender_System.py",
"repo_name": "anandkalpe18/Recommender-System",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\ndef index_title(index):\n return dataset[dataset.index==index][\"title\"].values[0]\n \ndef title_index(title):\n return dataset[dataset.title==title][\"index\"].values[0]\n \n \ndataset = pd.read_csv('movie_dataset.csv')\n\nfeatures = ['director','genres','cast','keywords']\n\nfor feature in features:\n dataset[feature]=dataset[feature].fillna(' ')\n \ndef combine_features(row):\n try:\n return row['keywords']+row['genres']+row['cast']+row['director']\n except:\n print('Error'),row\n \ndataset[\"Combined_Features\"]=dataset.apply(combine_features,axis=1)\n\ncv = CountVectorizer()\n\ncount_matrix = cv.fit_transform(dataset[\"Combined_Features\"])\n\ncosine_sim = cosine_similarity(count_matrix)\nUser_Liked_Movie = \"Spectre\"\n\nMovie_index = title_index(User_Liked_Movie)\n\nSimilar_Movies = list(enumerate(cosine_sim[Movie_index]))\n\nSorted_Movies = sorted(Similar_Movies,key= lambda x:x[1] , reverse = True)\n\ni=1\nfor movie in Sorted_Movies:\n print(index_title(movie[0]))\n i=i+1\n if i>11:\n break\n \n \n"
}
] | 1 |
sm5jasi/Class_grades
|
https://github.com/sm5jasi/Class_grades
|
400d3cbe530caedd64f707d03a0898bbf77568e3
|
7b6a50f981fe850f09174759d45f01ff2e9ad449
|
b5ede3919215964108c8294035944ddf07732b94
|
refs/heads/master
| 2021-01-10T03:24:10.281801 | 2015-12-08T20:34:28 | 2015-12-08T20:34:28 | 47,358,650 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6625000238418579,
"alphanum_fraction": 0.6625000238418579,
"avg_line_length": 22,
"blob_id": "4448f81ee00f57f8f0c5153338ee852613d56de4",
"content_id": "0d3691bdb53e488a8ea8182c29981ee99dac465f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 160,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 7,
"path": "/babbages_code.py",
"repo_name": "sm5jasi/Class_grades",
"src_encoding": "UTF-8",
"text": "import math\ndef statistics(a):\n\tmean = math.sum(a) / len(a)\n\tstd = math.std(a)\n\thigh_score = max(a)\n\tlow_score = min(a)\n\treturn mean, std, high_score, low_score"
},
{
"alpha_fraction": 0.5227272510528564,
"alphanum_fraction": 0.5340909361839294,
"avg_line_length": 20.75,
"blob_id": "86695e87ebba068d10ec6f6c2b7155044b450f7d",
"content_id": "5208f8e2dc3ecd94b5bc3692b7611929a8a0f600",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 176,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 8,
"path": "/adas_code.py",
"repo_name": "sm5jasi/Class_grades",
"src_encoding": "UTF-8",
"text": "\ndef read_data(f):\n \n import numpy as np\n \n g = np.loadtxt(f, delimiter = \",\", skiprows = 1, unpack = True, dtype = \"str\")\n grades = g[1]\n \n return grades \n"
},
{
"alpha_fraction": 0.7777777910232544,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 21.5,
"blob_id": "f8afc7edba8b076e9232bf09e06747a2fddd162f",
"content_id": "8ef91a4222a080b69b9a4506562c589f80451df5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 90,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 4,
"path": "/README.md",
"repo_name": "sm5jasi/Class_grades",
"src_encoding": "UTF-8",
"text": "# Class_grades\nin class exercise \n\nWe will create functions to determine a class' grades.\n"
}
] | 3 |
moriW/app_words
|
https://github.com/moriW/app_words
|
e136754ae6405ab0cc8ba94c2b1a54670cd0b9a2
|
357e19a8ebdcb5b91dceeee4a59c374525dcbd55
|
f744267ae9a6ccad756c8a3374f180045b30cc28
|
refs/heads/master
| 2023-09-05T09:27:16.564436 | 2021-11-19T09:38:24 | 2021-11-19T09:38:24 | 428,963,903 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.8615384697914124,
"alphanum_fraction": 0.8615384697914124,
"avg_line_length": 10,
"blob_id": "af47211f00240328cd84cf92df98857d6c7676ac",
"content_id": "5609e453f26905338a01e8e01b5faf1dc23e4e29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 65,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 6,
"path": "/requirements.txt",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "app-store-scraper\ngoogle-play-scraper\nsklearn\nkeybert\ndemoji\nnltk"
},
{
"alpha_fraction": 0.6351228356361389,
"alphanum_fraction": 0.6433120965957642,
"avg_line_length": 27.921052932739258,
"blob_id": "ea49a61c6d397707211a5237be460162683b1147",
"content_id": "e5bca1c7b439f1b3c0e5b68845f8ae4601f8d2a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1099,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 38,
"path": "/scraper/__init__.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "import logging\nimport itertools\nfrom typing import Optional\n\nimport demoji\n\nfrom .apple import scraper_apple\nfrom .google import scraper_google\n\n__all__ = [\"scraper\", \"scraper_google\", \"scraper_apple\"]\n\n\ndef content_filter(content: str) -> Optional[str]:\n content = demoji.replace(content)\n if len(content) < 20:\n return None\n content = \" \".join(filter(lambda x: len(x) < 15, content.split()))\n return content\n\n\ndef scraper(\n google_package: str,\n apple_name: str,\n lans: list[str] = [\"en\"],\n countries: list[str] = [\"us\"],\n count: int = 10000,\n):\n for lan, country in itertools.product(lans, countries):\n logging.info(f\"read reviews on {lan}, {country} @ google\")\n for review in scraper_google(google_package, lan, country, count):\n review = content_filter(review)\n if review: yield review\n\n for country in countries:\n logging.info(f\"read reviews on {country} @ apple\")\n for review in scraper_apple(apple_name, country, count):\n review = content_filter(review)\n if review: yield review\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 18.33333396911621,
"blob_id": "0d224c20daf44e07dff9e8032bc0f96d5ca30545",
"content_id": "cbf9ac303889fca1226409c6dfd462ad4e8cb7a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 3,
"path": "/nlp/__init__.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "from .tfidf import build_tfidf\n\n__all__ = [\"build_tfidf\"]"
},
{
"alpha_fraction": 0.581191897392273,
"alphanum_fraction": 0.5904865860939026,
"avg_line_length": 25.507246017456055,
"blob_id": "fac508d2a838fefa78f46bcb13660ac3f74a94cd",
"content_id": "56163d4d3c81ace2cc37810f482193a610bd559d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1829,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 69,
"path": "/entry.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "import os\nimport sys\nimport pickle\n\nfrom utils import logit\nfrom scraper import scraper\nfrom nlp import build_tfidf\n\n\nimport nltk\nfrom keybert import KeyBERT\n\nargs = sys.argv[1:]\napps = (args + [None, None])[:2]\ngoogle_package, apple_name = apps[0], apps[1]\n\n\nDOCUMENTS_FOLDER = \"documents\"\nKEYWORDS_FOLDER = \"keywords\"\n\n\nfor folder in [DOCUMENTS_FOLDER, KEYWORDS_FOLDER]:\n if not os.path.exists(folder):\n os.mkdir(folder)\n\ndocument_path = os.path.join(DOCUMENTS_FOLDER, apple_name)\nkeyword_path = os.path.join(KEYWORDS_FOLDER, apple_name)\n\n\n@logit\ndef scrap():\n if os.path.exists(document_path):\n return\n with open(document_path, \"w\") as _f:\n for review_content in scraper(google_package, apple_name, count=1000):\n _f.write(review_content.lower().strip() + \"\\n\")\n\n\n@logit\ndef nlp1():\n ps = nltk.PorterStemmer()\n keybert_model = KeyBERT()\n value_dict = {}\n with open(document_path, \"r\") as _f:\n content = _f.readlines()\n for raw_content, keyword_value_pair in zip(\n content, keybert_model.extract_keywords(content, top_n=100)\n ):\n keyword = [x[0] for x in keyword_value_pair]\n stem_tag = {\n ps.stem(word): tag\n for word, tag in nltk.pos_tag(nltk.tokenize.word_tokenize(raw_content))\n if word in keyword\n }\n\n for keyword, value in keyword_value_pair:\n stem = ps.stem(keyword)\n key = f\"{stem} {stem_tag.get(stem, None)}\"\n value_dict[key] = value_dict.get(key, {\"count\": 0, \"value\": 0})\n value_dict[key][\"count\"] += 1\n value_dict[key][\"value\"] += value\n\n with open(keyword_path, \"wb\") as _f:\n pickle.dump(value_dict, _f)\n\n\nif __name__ == \"__main__\":\n scrap()\n nlp1()\n"
},
{
"alpha_fraction": 0.7088607549667358,
"alphanum_fraction": 0.7151898741722107,
"avg_line_length": 30.700000762939453,
"blob_id": "0f51bddb618c10fb2186c86efd1246858ef2972e",
"content_id": "35b5b464b75b1424f570fd21ba72aedce5be31cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 316,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 10,
"path": "/nlp/tfidf.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "from sklearn.feature_extraction.text import TfidfVectorizer, ENGLISH_STOP_WORDS\n\n\ndef build_tfidf(texts: list[str]):\n vectorizer = TfidfVectorizer(max_df=0.5)\n vectorizer.fit_transform(texts)\n\n for word in vectorizer.get_feature_names_out():\n if word not in ENGLISH_STOP_WORDS:\n yield word"
},
{
"alpha_fraction": 0.6530120372772217,
"alphanum_fraction": 0.6746987700462341,
"avg_line_length": 25,
"blob_id": "bc52872c5772981685cf27bc8d7431942afe56e1",
"content_id": "aa83f9691ddd888355113f6b3ff8c620e0821396",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 415,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 16,
"path": "/scraper/apple.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n# \n#\n# @file: apple\n# @time: 2021/11/17\n# @author: Mori\n#\n\nfrom typing import Iterator\nfrom app_store_scraper import AppStore\n\ndef scraper_apple(app: str, country: str, count: int) -> Iterator[str]:\n app_store = AppStore(app_name=app, country=country)\n app_store.review(how_many=count, sleep=1)\n for review in app_store.reviews:\n yield f\"{review['title']}. {review['review']}\""
},
{
"alpha_fraction": 0.5927152037620544,
"alphanum_fraction": 0.6076158881187439,
"avg_line_length": 20.571428298950195,
"blob_id": "c576fae5f2ae402a4e7fe11bcf8ab5644b3024b8",
"content_id": "38db6ae158097b3cc267003727084fee8e1eaba4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 28,
"path": "/utils/common.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n#\n#\n# @file: common\n# @time: 2021/11/18\n# @author: Mori\n#\n\nimport time\nimport logging\nfrom functools import wraps\n\nlogging.basicConfig(\n level=logging.INFO, format=\"%(asctime)s %(name)s %(levelname)s:%(message)s\"\n)\n\n\ndef logit(func):\n @wraps(func)\n def _wrapper_(*args, **kwargs):\n start = time.time()\n logging.info(f\"starting job - {func.__name__}\")\n result = func(*args, **kwargs)\n duration = time.time() - start\n logging.info(f\"finish job - {func.__name__} in {round(duration, 3)} second\")\n return result\n\n return _wrapper_\n"
},
{
"alpha_fraction": 0.6304348111152649,
"alphanum_fraction": 0.6304348111152649,
"avg_line_length": 14.666666984558105,
"blob_id": "942f4619b689ed8be89628cde6923ccab46cd47f",
"content_id": "f3ae501b2a728acad2438e2045b82bb2340d948c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 3,
"path": "/utils/__init__.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "from .common import logit\n\n__all__ = [\"logit\"]"
},
{
"alpha_fraction": 0.5480093955993652,
"alphanum_fraction": 0.5667447447776794,
"avg_line_length": 21.473684310913086,
"blob_id": "e72307281f269f74ef9f38f88f260e0688f6ac6e",
"content_id": "15f316f39947bf97b33373363a2c4546e99c7b0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 854,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 38,
"path": "/scraper/google.py",
"repo_name": "moriW/app_words",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n#\n#\n# @file: scraper\n# @time: 2021/11/17\n# @author: Mori\n#\n\nimport logging\nfrom typing import Iterable\nfrom google_play_scraper import reviews\n\n\ndef scraper_google(\n app_name: str, lan: str = \"en\", country: str = \"us\", count: int = 10000\n) -> Iterable[str]:\n continuation_token, _count, offset = None, 0, int(count / 10)\n\n while True:\n logging.info(f\"loading from google {lan}, {country}, {_count}...\")\n _result, continuation_token = reviews(\n app_name,\n count=offset,\n continuation_token=continuation_token,\n lang=lan,\n country=country,\n )\n\n for review in _result:\n yield review[\"content\"]\n\n _count += len(_result)\n\n if continuation_token is None:\n break\n\n if _count >= count:\n break\n"
}
] | 9 |
Take-it-easy-yxl/yxl
|
https://github.com/Take-it-easy-yxl/yxl
|
b08df0c340c3b67fb1a49d07dd81be01dcdb9cc2
|
cdf07572311937fbd97d974e85386c833a9a3b29
|
dd4cba6ebbff317d77f0db6d64766981cbe34fca
|
refs/heads/master
| 2020-03-22T02:39:25.217938 | 2018-07-02T03:12:33 | 2018-07-02T03:12:33 | 139,384,794 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4796992540359497,
"alphanum_fraction": 0.5398496389389038,
"avg_line_length": 13.871794700622559,
"blob_id": "cd1ffcd0b306ab4c64fd6533e27b5b850991ae59",
"content_id": "f6a3b742ff9f2691996ed78688606a012161c592",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 843,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 39,
"path": "/作业代码/第一题.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\nctrl + 方法字体\r\nctrl enter 选中运行\r\n第一题\r\n1.定义一个天气列表。写出里面一周每个温度\r\n2.打印出7天的天气,并且如果是星期三的话,打印星期三是X度\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n#数据类型\r\nx=3#int\r\ny='男厕所'#str\r\na=1.19838493#float\r\nb=True#bool\r\nd=[True,False,False,False,False]#list\r\nc=['男厕所','女厕所','中性']#[type,...]\r\nprint(c[0])\r\nprint(d[2])\r\n## print(\"今天是:\"+f)\r\n#TypeError: must be str, not int\r\nf=28\r\nprint(\"今天是:\"+str(f))\r\nfloat(f)\r\nstr(f)\r\nint(f)\r\n\r\n\r\n第一题:\r\na=['14','18','23','19','21','18','16']\r\nprint(a[0])\r\nprint(a[1])\r\nprint(a[2])\r\nprint(a[3])\r\nprint(a[4])\r\nprint(a[5])\r\nprint(a[6])\r\nprint(\"星期三温度是:\"+str(a[2]))\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"
},
{
"alpha_fraction": 0.5235037803649902,
"alphanum_fraction": 0.5824809670448303,
"avg_line_length": 32.059478759765625,
"blob_id": "b9f785847aeb663a01bba70a909f8b117f63d4a0",
"content_id": "dd51d2dae17d63388b0511e73701d5951e5a82fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10326,
"license_type": "no_license",
"max_line_length": 213,
"num_lines": 269,
"path": "/作业代码/十四题作业2.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 27 09:10:48 2018\r\nK12(小学到高中12年的简称)--\r\n高考--高考派(统计全中国大学招生情况,例如北京大学(3000)在北京招多少人?在重庆?在全国?)\r\n全中国有多少所大学?\r\n全中国有多少个城市?\r\n在某个城市文科招的人数?理科招生的人数?\r\n====\r\n全国大学招生人数排行:例如\r\n郑州大学 8000\r\n桂林大学 6000\r\n.....\r\n西藏藏医学院:5\r\n=\r\n家长帮班级项目:\r\n注意点:同一时间,访问量过大,可能会导致本次项目无法进行,因为北京那边服务器奔溃。导致全国都无法访问。\r\n导致对方程序员加班。所以我们整个班级,需要有一套策略,要拿到所有数据但不会导致奔溃。\r\n策略例如:\r\n======\r\n题目十四:家长帮大数据爬虫项目\r\n1.根据all_school.txt获取全中国学校网址编号:1304,生成一个2300列表\r\n2.根据http://www.gaokaopai.com/daxue-zhaosheng-学校编号.html 获取全国城市的编号 例如北京:11\r\n3.班级团队(需要下载142600(2300*31*2)次):\r\n 中国划分区域-分组(城市)\r\n 区域分组员\r\n 如何下载策略-分时间下载\r\n 执行人物2300-分配到自己的任务一般是2300\r\n 保存数据---组长全部合并--班长统计\r\n4.待定\r\n\r\n\r\n@author: Administrator\r\n\"\"\"\r\nimport urllib.request as r\r\nurl='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\ndata='id=2948&type=2&city=50&state=1'.encode()\r\nreq=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\nd=r.urlopen(req).read().decode('utf-8','ignore')\r\nf=open('./a.txt','a')\r\nf.write(d+\"\\n\")\r\nf.close()\r\nfor i in range(len(a)):\r\n data='id={}&type=2&city=33&state=1'.format(a[i])\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n d=r.urlopen(req).read().decode('utf-8','ignore')\r\n f=open('./a.txt','a')\r\n f.write(d+\"\\n\")\r\nf.close()\r\n\r\nf=open('./all_school.txt','r',encoding='utf-8')\r\ns=f.read()\r\nimport re\r\ns1=re.compile('http://www.gaokaopai.com/daxue-jianjie-(.*?).html',re.S).findall(s)\r\nf.close() \r\nm=[]\r\nimport urllib.request as r \r\nfor i in range(1985,2300):\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=31&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m.append(p)\r\n a=m[i]\r\n if a.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=34&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=p\r\n else:\r\n a=i\r\n print('{}次输出成功'.format(a))\r\n\r\n#再次检验是否有错\r\nfor i in range(2300):\r\n a=m[i]\r\n if a.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=31&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=p\r\n else:\r\n a=i\r\n print('{}次输出成功'.format(a))\r\n\r\nf=open('./上海文科.txt','w',encoding='utf-8')\r\nfor i in range(len(m)):\r\n p=m[i]\r\n f.write(p+\"\\n\")\r\nf.close() \r\n\r\nf=open('./all_school.txt','r',encoding='utf-8')\r\ns=f.read()\r\nimport re\r\ns1=re.compile('http://www.gaokaopai.com/daxue-jianjie-(.*?).html',re.S).findall(s)\r\nf.close() \r\nm=[]\r\nimport urllib.request as r \r\nfor i in range(0,2300):\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=33&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m.append(p)\r\n a=m[i]\r\n if a.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=33&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=p\r\n else:\r\n a=i\r\n print('{}次输出成功'.format(a))\r\n\r\n#再次检验是否有错\r\nfor i in range(0,2300):\r\n a=m[i]\r\n if a.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=33&state=1'.format(s1[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=p\r\n else:\r\n a=i\r\n print('{}次输出成功'.format(a))\r\n\r\nf=open('./浙江文科1.txt','w',encoding='utf-8')\r\nfor i in range(len(m)):\r\n p=m[i]\r\n f.write(p+\"\\n\")\r\nf.close() \r\n \r\n \r\n\r\nm=[]\r\nimport urllib.request as r \r\nfor i in range(2300):\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=33&state=1'.format(a[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m.append(p)\r\n b=m[i]\r\n if b.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=1&city=33&state=1'.format(a[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n p=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=p\r\n else:\r\n b=i\r\n print('{}次输出成功'.format(b))\r\n continue\r\n\r\nf=open('./修改华东地区汇总.txt','w',encoding='utf-8')\r\nfor i in range(len(m)):\r\n p=m[i]\r\n f.write(p+\"\\n\")\r\nf.close() \r\n\r\nm=[]\r\nimport urllib.request as r\r\nurl='file:./浙江理科.txt'\r\ndata=r.urlopen(url).read().decode('utf-8')\r\ndata=data.split()\r\nimport json\r\nfor i in range(2300):\r\n a=json.loads(data[i])\r\n m.append(a)\r\n\r\nn=0\r\nfor j in range(2300):\r\n b1=m1[j]['data']\r\n b2=m1[j]['status']\r\n if b2==0:\r\n print('第{}的学校不在该地区招生'.format(j))\r\n else:\r\n b3=m1[j]['data'][0]['subject']\r\n b4=m1[j]['data'][0]['school']\r\n print('采取-{}-{}类-的人数'.format(b4,b3))\r\n for k in range(len(b1)):\r\n b4=m1[j]['data'][k]['plan']\r\n b6=m1[j]['data'][0]['school']\r\n b4=int(b4)\r\n n=n+b4\r\n print(n)\r\n print('{}采取完成'.format(b6))\r\n\r\n\r\nls1=['上海理科','上海文科','江苏理科','江苏文科','浙江理科','浙江文科','安徽理科','安徽文科']\r\nb=0\r\nfor i in range(len(m)):\r\n d=0\r\n for x in range(len(m[i])):\r\n if int(m[i]['status'])==1:\r\n l2=len(m[i]['data'])\r\n for c in range(l2):\r\n \r\n d=d+int(m[i]['data'][c]['plan'])\r\n print('江苏的招生人数是:{}'.format(d))\r\nprint('华东地区文理科的招生人数是:{}'.format(b))\r\n\r\nn=0\r\nfor i in range(2300):\r\n b1=m[i]['status']\r\n if b1==1:\r\n b2=m[i]['data']\r\n for j in range(len(b2)):\r\n b3=m[i]['data'][j]['plan']\r\n b3=int(b3)\r\n n=n+b3\r\n print('现在招生人数为{}'.format(n))\r\nm=[]\r\nimport urllib.request as r\r\nurl='file:./上海文科.txt'\r\ndata=r.urlopen(url).read().decode('utf-8')\r\ndata=data.split('\\n')\r\nimport json\r\nfor i in range(2300):\r\n a=json.loads(data[i])\r\n m.append(a)\r\nc=0\r\nfor i in range(len(m)):\r\n b1=m[i]['status']\r\n b2=m[i]['data'][0]['city'] \r\n if b1==1:\r\n b4=m[i]['data']\r\n for j in range(len(b4)):\r\n b3=m[i]['data'][j]['plan']\r\n b3=int(b3)\r\n c=c+b3\r\nprint('全国对于{}的招生总人数为{}'.format(b2,c))\r\n\r\nf=open('./修改华东地区汇总.txt','a',encoding='utf-8')\r\nf1=open('./上海文科.txt','r',encoding='utf-8')\r\nd1=f1.read() \r\nf2=open('./上海理科.txt','r',encoding='utf-8')\r\nd2=f2.read() \r\nf3=open('./安徽 文.txt','r',encoding='utf-8')\r\nd3=f3.read() \r\nf4=open('./安徽理科.txt','r',encoding='utf-8') \r\nd4=f4.read() \r\nf5=open('./江苏文科.txt','r',encoding='utf-8') \r\nd5=f5.read()\r\nf6=open('./江苏理科.txt','r',encoding='utf-8') \r\nd6=f6.read()\r\nf7=open('./浙江文科1.txt','r',encoding='utf-8') \r\nd7=f7.read()\r\nf8=open('./浙江理科.txt','r',encoding='utf-8') \r\nd8=f8.read()\r\nf.write('{}{}{}{}{}{}{}{}\\n'.format(d1,d2,d3,d4,d5,d6,d7,d8))\r\nf.close()\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"
},
{
"alpha_fraction": 0.5604166388511658,
"alphanum_fraction": 0.6118055582046509,
"avg_line_length": 39.82352828979492,
"blob_id": "69f8d21f6e8aed296e9d403c1559b4b351d352d0",
"content_id": "fb7d9a459304ece25377aa164d88e94f4dfeec6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1580,
"license_type": "no_license",
"max_line_length": 353,
"num_lines": 34,
"path": "/作业代码/第八题.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 24 22:07:11 2018\r\n\r\n@author: Administrator\r\n\r\n商品名,价格,付款,店铺名,地址\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n\r\nf=open('./上海.csv','w')\r\nf.write('店铺名,商品名,价格,销量,地址\\n')\r\nfor i in range(0,100):\r\n import urllib.request as r\r\n url2='https://s.taobao.com/search?initiative_id=tbindexz_20170306&ie=utf8&spm=a21bo.2017.201856-taobao-item.2&sourceId=tb.index&search_type=item&ssid=s5-e&commend=all&imgfile=&q=t%E6%81%A4%E7%94%B7&suggest=history_1&_input_charset=utf-8&wq=&suggest_query=&source=suggest&loc=%E6%9D%AD%E5%B7%9E&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s=0&ajax=true'\r\n a=44*i\r\n url=url2.replace('0&ajax=true',str(a)+'&ajax=true')\r\n data=r.urlopen(url).read().decode('utf-8')\r\n import json\r\n data=json.loads(data)\r\n l=len(data['mods']['itemlist']['data']['auctions'])\r\n for a in range(0,l):\r\n nick=data['mods']['itemlist']['data']['auctions'][a]['nick']#店铺名\r\n raw_title=data['mods']['itemlist']['data']['auctions'][a]['raw_title']#商品名\r\n view_price=data['mods']['itemlist']['data']['auctions'][a]['view_price']#价格\r\n view_sales=data['mods']['itemlist']['data']['auctions'][a]['view_sales']#销量\r\n item_loc=data['mods']['itemlist']['data']['auctions'][a]['item_loc']#地址\r\n f.write('{},{},{},{},{}\\n'.format(nick,raw_title,view_price,view_sales,item_loc))\r\n print('第{}页已获取数据'.format(i+1))\r\nf.close()\r\nprint('关键词为“t恤男”上海地区前100页数据获取完成!')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5747472047805786,
"alphanum_fraction": 0.6438917517662048,
"avg_line_length": 35.63541793823242,
"blob_id": "0e9f4dbb86f6653b0dc59e2ad69798a911269d4a",
"content_id": "c568ed585c9b5ef36ce0885fb65d79a9e3eac73d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4379,
"license_type": "no_license",
"max_line_length": 207,
"num_lines": 96,
"path": "/作业代码/十四题作业.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 27 09:10:48 2018\r\nK12(小学到高中12年的简称)--\r\n高考--高考派(统计全中国大学招生情况,例如北京大学(3000)在北京招多少人?在重庆?在全国?)\r\n全中国有多少所大学?\r\n全中国有多少个城市?\r\n在某个城市文科招的人数?理科招生的人数?\r\n====\r\n全国大学招生人数排行:例如\r\n郑州大学 8000\r\n桂林大学 6000\r\n.....\r\n西藏藏医学院:5\r\n=\r\n家长帮班级项目:\r\n注意点:同一时间,访问量过大,可能会导致本次项目无法进行,因为北京那边服务器奔溃。导致全国都无法访问。\r\n导致对方程序员加班。所以我们整个班级,需要有一套策略,要拿到所有数据但不会导致奔溃。\r\n策略例如:\r\n======\r\n题目十四:家长帮大数据爬虫项目\r\n1.根据all_school.txt获取全中国学校网址编号:1304,生成一个2300列表\r\n2.根据http://www.gaokaopai.com/daxue-zhaosheng-学校编号.html 获取全国城市的编号 例如北京:11\r\n3.班级团队(需要下载142600(2300*31*2)次):\r\n 中国划分区域-分组(城市)\r\n 区域分组员\r\n 如何下载策略-分时间下载\r\n 执行人物2300-分配到自己的任务一般是2300\r\n 保存数据---组长全部合并--班长统计\r\n4.待定\r\n\r\n\r\n@author: Administrator\r\n\"\"\"\r\nimport urllib.request as r\r\nurl='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\ndata='id=2948&type=2&city=50&state=1'.encode()\r\nreq=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\nd=r.urlopen(req).read().decode('utf-8','ignore')\r\nf=open('./a.txt','a')\r\nf.write(d+\"\\n\")\r\nf.close()\r\nfor i in range(len(a)):\r\n data='id={}&type=2&city=33&state=1'.format(a[i])\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n d=r.urlopen(req).read().decode('utf-8','ignore')\r\n f=open('./a.txt','a')\r\n f.write(d+\"\\n\")\r\nf.close()\r\n\r\nm=[]\r\nimport urllib.request as r\r\nurl='file:./all_school.txt'\r\ndata=r.urlopen(url).read().decode('utf-8')\r\nimport re\r\nc=re.compile('http://www.gaokaopai.com/daxue-jianjie-(.*?).html',re.S).findall(data)\r\nb=re.compile('(.*?)http:/').findall(data)\r\nurl='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\nfor i in range(len(c)):\r\n data='id={}&type=2&city=33&state=1'.format(c[i])\r\n data1=data.encode()\r\n req=r.Request(url,data=data1,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n d=r.urlopen(req).read().decode('utf-8','ignore')\r\n m.append(d)\r\n print('输出次数{}'.format(i))\r\n \r\nfor i in range(len(m)):\r\n a=m[i]\r\n if a.startswith('<!DOCTYPE html>'):\r\n print('第{}存在错误'.format(i))\r\n url='http://www.gaokaopai.com/university-ajaxGetMajor.html'\r\n data='id={}&type=2&city=34&state=1'.format(c[i])\r\n data=data.encode()\r\n req=r.Request(url,data=data,headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36','X-Requested-With':'XMLHttpRequest'})\r\n d=r.urlopen(req).read().decode('utf-8','ignore')\r\n m[i]=d\r\n \r\n else:\r\n continue\r\n \r\nf=open('/浙江理科.txt','w',encoding='utf-8')\r\nfor i in range(len(m)):\r\n p=m[i]\r\n f.write(p+\"\\n\")\r\nf.close()\r\n\r\nimport urllib.request as r\r\nreq=r.Request('http://www.gaokaopai.com/daxue-0-0-0-0-0-0-0.html',headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'})\r\nmyurl=r.urlopen(req)\r\nprint(myurl.getcode())\r\ndata=myurl.read().decode('utf-8')\r\nimport re\r\ns3=re.compile('<span><a href=\"http://www.gaokaopai.com/daxue-(.*?)-0-0-0-0-0-0.html\">(.*?)</a></span>').findall(data)\r\nprint(s3)\r\ns1=re.compile('<span><a href=\"http://www.gaokaopai.com/daxue-(.*?)-0-0-0-0-0-0.html\">').findall(data)\r\ns2=re.compile('<span><a href=\"http://www.gaokaopai.com/daxue-..-0-0-0-0-0-0.html\">(.*?)</a></span>').findall(data)\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"
},
{
"alpha_fraction": 0.6584234833717346,
"alphanum_fraction": 0.6908810138702393,
"avg_line_length": 30.350000381469727,
"blob_id": "07b3db80b3a953b78ac62eff60c81bab959b4c28",
"content_id": "44a0c0c92b3924e0d48e7ca49d9c59cdb39f32f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 805,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 20,
"path": "/作业代码/第三题.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "1# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 20 16:13:19 2018\r\n第三题:\r\n1.通过复制联网代码获得天气(老家)字典数据\r\n2.打印温度temp,天气情况description,天气气压pre\r\n@author: Administrator\r\n\"\"\"\r\nimport urllib.request as r#导入联网工具包,命令为r\r\nurl='http://api.openweathermap.org/data/2.5/weather?q=jilin&mode=json&units=metric&lang=zh_cn&APPID=6a67ed641c0fda8b69715c43518b6996'\r\ndata=r.urlopen(url).read().decode('utf-8')\r\n#讲str类型转换为dict\r\nimport json\r\ndata=json.loads(data)\r\ndata['main']['temp']\r\ndata['weather'][0]['description']\r\ndata['main']['pressure']\r\nprint('今天重庆的温度是'+str(data['main']['temp']))\r\nprint('今天重庆的天气情况是'+str(data['weather'][0]['description']))\r\nprint('今天重庆的天气气压是'+str(data['main']['pressure']))\r\n"
},
{
"alpha_fraction": 0.5957156419754028,
"alphanum_fraction": 0.6261950731277466,
"avg_line_length": 48.409420013427734,
"blob_id": "b2707da1f555ea49c6293db1c5f886b6cdf710b4",
"content_id": "7188e996cc5b540334c8650597312102ef5e51dd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14831,
"license_type": "no_license",
"max_line_length": 208,
"num_lines": 276,
"path": "/作业代码/第四题.py",
"repo_name": "Take-it-easy-yxl/yxl",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 21 14:14:52 2018\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport urllib.request as r#导入联网工具包,命令为r\r\nurl='http://api.openweathermap.org/data/2.5/forecast?q=chongqing,cn&mode=json&lang=zh_cn&&APPID=6a67ed641c0fda8b69715c43518b6996&units=metric'\r\ndata=r.urlopen(url).read().decode('utf-8')\r\n#讲str类型转换为dict\r\nimport json\r\ndata=json.loads(data)\r\n#data字典-》list列表-》index 0 字典-》main字典-》temp变量\r\ndata['list'][0]['main']['temp']\r\n#data字典-》list列表-》index 0 字典-》main字典-》temp_max变量\r\n\r\n#data字典-》list列表-》index 0 字典-》main字典-》temp_min变量\r\ntime=data['list'][0]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][0]['main']['temp']\r\nwea=data['list'][0]['weather'][0]['description']\r\npre=data['list'][0]['main']['pressure']\r\ntemp_max=data['list'][0]['main']['temp_max']\r\ntemp_min=data['list'][0]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][0]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][0]['main']['temp']\r\nwea=data['list'][0]['weather'][0]['main']\r\npre=data['list'][0]['main']['pressure']\r\ntemp_max=data['list'][0]['main']['temp_max']\r\ntemp_min=data['list'][0]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][2]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][2]['main']['temp']\r\nwea=data['list'][2]['weather'][0]['description']\r\npre=data['list'][2]['main']['pressure']\r\ntemp_max=data['list'][2]['main']['temp_max']\r\ntemp_min=data['list'][2]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][2]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][2]['main']['temp']\r\nwea=data['list'][2]['weather'][0]['main']\r\npre=data['list'][2]['main']['pressure']\r\ntemp_max=data['list'][2]['main']['temp_max']\r\ntemp_min=data['list'][2]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][4]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][4]['main']['temp']\r\nwea=data['list'][4]['weather'][0]['description']\r\npre=data['list'][4]['main']['pressure']\r\ntemp_max=data['list'][4]['main']['temp_max']\r\ntemp_min=data['list'][4]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][4]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][4]['main']['temp']\r\nwea=data['list'][4]['weather'][0]['main']\r\npre=data['list'][4]['main']['pressure']\r\ntemp_max=data['list'][4]['main']['temp_max']\r\ntemp_min=data['list'][4]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\nprint('2018-06-21有持续小雨,记得带伞')\r\n\r\ntime=data['list'][8]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][8]['main']['temp']\r\nwea=data['list'][8]['weather'][0]['description']\r\npre=data['list'][8]['main']['pressure']\r\ntemp_max=data['list'][8]['main']['temp_max']\r\ntemp_min=data['list'][8]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][8]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][8]['main']['temp']\r\nwea=data['list'][8]['weather'][0]['main']\r\npre=data['list'][8]['main']['pressure']\r\ntemp_max=data['list'][8]['main']['temp_max']\r\ntemp_min=data['list'][8]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][10]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][10]['main']['temp']\r\nwea=data['list'][10]['weather'][0]['description']\r\npre=data['list'][10]['main']['pressure']\r\ntemp_max=data['list'][10]['main']['temp_max']\r\ntemp_min=data['list'][10]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][10]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][10]['main']['temp']\r\nwea=data['list'][10]['weather'][0]['main']\r\npre=data['list'][10]['main']['pressure']\r\ntemp_max=data['list'][10]['main']['temp_max']\r\ntemp_min=data['list'][10]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][12]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][12]['main']['temp']\r\nwea=data['list'][12]['weather'][0]['description']\r\npre=data['list'][12]['main']['pressure']\r\ntemp_max=data['list'][12]['main']['temp_max']\r\ntemp_min=data['list'][12]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][12]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][12]['main']['temp']\r\nwea=data['list'][12]['weather'][0]['main']\r\npre=data['list'][12]['main']['pressure']\r\ntemp_max=data['list'][12]['main']['temp_max']\r\ntemp_min=data['list'][12]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\nprint('2018-06-22小雨转大雨,记得带伞,增加衣物')\r\n\r\ntime=data['list'][16]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][16]['main']['temp']\r\nwea=data['list'][16]['weather'][0]['description']\r\npre=data['list'][16]['main']['pressure']\r\ntemp_max=data['list'][16]['main']['temp_max']\r\ntemp_min=data['list'][16]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][16]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][16]['main']['temp']\r\nwea=data['list'][16]['weather'][0]['main']\r\npre=data['list'][16]['main']['pressure']\r\ntemp_max=data['list'][16]['main']['temp_max']\r\ntemp_min=data['list'][16]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][18]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][18]['main']['temp']\r\nwea=data['list'][18]['weather'][0]['description']\r\npre=data['list'][18]['main']['pressure']\r\ntemp_max=data['list'][18]['main']['temp_max']\r\ntemp_min=data['list'][18]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][18]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][18]['main']['temp']\r\nwea=data['list'][18]['weather'][0]['main']\r\npre=data['list'][18]['main']['pressure']\r\ntemp_max=data['list'][18]['main']['temp_max']\r\ntemp_min=data['list'][18]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][20]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][20]['main']['temp']\r\nwea=data['list'][20]['weather'][0]['description']\r\npre=data['list'][20]['main']['pressure']\r\ntemp_max=data['list'][20]['main']['temp_max']\r\ntemp_min=data['list'][20]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][20]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][20]['main']['temp']\r\nwea=data['list'][20]['weather'][0]['main']\r\npre=data['list'][20]['main']['pressure']\r\ntemp_max=data['list'][20]['main']['temp_max']\r\ntemp_min=data['list'][20]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\nprint('2018-06-23有持续小雨,记得带伞')\r\n\r\ntime=data['list'][24]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][24]['main']['temp']\r\nwea=data['list'][24]['weather'][0]['description']\r\npre=data['list'][24]['main']['pressure']\r\ntemp_max=data['list'][24]['main']['temp_max']\r\ntemp_min=data['list'][24]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][24]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][24]['main']['temp']\r\nwea=data['list'][24]['weather'][0]['main']\r\npre=data['list'][24]['main']['pressure']\r\ntemp_max=data['list'][24]['main']['temp_max']\r\ntemp_min=data['list'][24]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][26]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][26]['main']['temp']\r\nwea=data['list'][26]['weather'][0]['description']\r\npre=data['list'][26]['main']['pressure']\r\ntemp_max=data['list'][26]['main']['temp_max']\r\ntemp_min=data['list'][26]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][26]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][26]['main']['temp']\r\nwea=data['list'][26]['weather'][0]['main']\r\npre=data['list'][26]['main']['pressure']\r\ntemp_max=data['list'][26]['main']['temp_max']\r\ntemp_min=data['list'][26]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][28]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][28]['main']['temp']\r\nwea=data['list'][28]['weather'][0]['description']\r\npre=data['list'][28]['main']['pressure']\r\ntemp_max=data['list'][28]['main']['temp_max']\r\ntemp_min=data['list'][28]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][28]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][28]['main']['temp']\r\nwea=data['list'][28]['weather'][0]['main']\r\npre=data['list'][28]['main']['pressure']\r\ntemp_max=data['list'][28]['main']['temp_max']\r\ntemp_min=data['list'][28]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\nprint('2018-06-24中雨转多云,可以适当增减衣物')\r\n\r\ntime=data['list'][32]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][32]['main']['temp']\r\nwea=data['list'][32]['weather'][0]['description']\r\npre=data['list'][32]['main']['pressure']\r\ntemp_max=data['list'][32]['main']['temp_max']\r\ntemp_min=data['list'][32]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][32]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][32]['main']['temp']\r\nwea=data['list'][32]['weather'][0]['main']\r\npre=data['list'][32]['main']['pressure']\r\ntemp_max=data['list'][32]['main']['temp_max']\r\ntemp_min=data['list'][32]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][34]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][34]['main']['temp']\r\nwea=data['list'][34]['weather'][0]['description']\r\npre=data['list'][34]['main']['pressure']\r\ntemp_max=data['list'][34]['main']['temp_max']\r\ntemp_min=data['list'][34]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][34]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][34]['main']['temp']\r\nwea=data['list'][34]['weather'][0]['main']\r\npre=data['list'][34]['main']['pressure']\r\ntemp_max=data['list'][34]['main']['temp_max']\r\ntemp_min=data['list'][34]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\n\r\ntime=data['list'][36]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][36]['main']['temp']\r\nwea=data['list'][36]['weather'][0]['description']\r\npre=data['list'][36]['main']['pressure']\r\ntemp_max=data['list'][36]['main']['temp_max']\r\ntemp_min=data['list'][36]['main']['temp_min']\r\nprint('{},城市{},温度是:{},天气情况是:{},气压是:{},最高温度:{},最低温度:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\ntime=data['list'][36]['dt_txt']\r\nname=data['city']['name']\r\ntemp=data['list'][36]['main']['temp']\r\nwea=data['list'][36]['weather'][0]['main']\r\npre=data['list'][36]['main']['pressure']\r\ntemp_max=data['list'][36]['main']['temp_max']\r\ntemp_min=data['list'][36]['main']['temp_min']\r\nprint('time:{},Please enter the name of the city to be inquired:{},temperature:{},the weather is:{},pressure:{},maximum temperature:{},minimum temperature:{}'.format(time,name,temp,wea,pre,temp_max,temp_min))\r\nprint('2018-06-25多云,适合外出')"
}
] | 6 |
aritramullick/titanic-survivor
|
https://github.com/aritramullick/titanic-survivor
|
2b428a8658a884b815753f2cbbe96376277309eb
|
1752a8a8d3ebbb4a13fd22eaad7dfa1d9ed51cc5
|
30cac2d9f20c664e726931e74f9fd0bb8f7b6fe7
|
refs/heads/master
| 2022-11-12T12:40:35.965308 | 2020-06-27T08:43:00 | 2020-06-27T08:43:00 | 275,332,640 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6405965685844421,
"alphanum_fraction": 0.6591487526893616,
"avg_line_length": 27.93684196472168,
"blob_id": "d9a6728231bad5efe66891b0c096424d87529a1d",
"content_id": "131d2b76301b232013a7e61859a82db87fa6b0d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2749,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 95,
"path": "/main.py",
"repo_name": "aritramullick/titanic-survivor",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nfrom sklearn import metrics\nfrom sklearn import svm\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import MinMaxScaler\n\ndf = pd.read_csv('train.csv')\ndf = df.drop([\"Name\", \"Ticket\", \"SibSp\", \"Parch\"], axis=1)\ndf = df.drop(['Cabin'], axis = 1)\n\nle = LabelEncoder()\ndf['Sex'] = le.fit_transform(df['Sex'])\ndf['Embarked'] = le.fit_transform(df['Embarked'].astype(str))\n# print(df)\n\ndf1 = df[df['Survived'] == 0]\ndf2 = df[df['Survived'] == 1]\n\ndf1[\"Age\"] = df1[\"Age\"].fillna(value=df1[\"Age\"].mean())\ndf2[\"Age\"] = df2[\"Age\"].fillna(value=df2[\"Age\"].mean())\n\nframes = [df1, df2]\ndf = pd.concat(frames)\n\ndf = df.sort_values(by='PassengerId')\nprint(df)\n\nscaler = MinMaxScaler(feature_range=(0, 5))\ndf['Age'] = scaler.fit_transform(df[['Age']])\ndf['Fare'] = scaler.fit_transform(df[['Fare']])\n# print(df)\n\nX = df.iloc[:, 2:]\nY = df.iloc[:, 1]\nprint(Y)\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=1)\nprint(X_train)\n\nk_range = range(1, 70)\nscores = {}\nscores_list = []\n\nfor k in k_range:\n knn = KNeighborsClassifier(n_neighbors=k)\n knn.fit(X_train, Y_train)\n y_pred = knn.predict(X_test)\n scores[k] = metrics.accuracy_score(Y_test, y_pred)\n scores_list.append(scores[k])\n\nfor k in k_range:\n print(f\"{k} score:{scores[k]}\")\n\nclf = svm.SVC(kernel='rbf')\nclf.fit(X_train, Y_train)\n\ny_pred = clf.predict(X_test)\nprint(\"SVM Accuracy:\", metrics.accuracy_score(Y_test, y_pred))\nprint(f\"Best KNN found: {scores[4]}\")\n# k = 4 for KNN is found to be the best model accuracy-wise\ndf = pd.read_csv('test.csv')\ndf = df.drop(['Name', 'SibSp', 'Parch', 'Ticket'], axis=1)\ndf = df.drop(['Cabin'], axis = 1)\n\ndf['Sex'] = le.fit_transform(df['Sex'])\ndf['Embarked'] = le.fit_transform(df['Embarked'].astype(str))\n\ndf1 = df[df['Pclass'] == 1]\ndf2 = df[df['Pclass'] == 2]\ndf3 = df[df['Pclass'] == 3]\n\ndf1[\"Age\"] = df1[\"Age\"].fillna(value=df1[\"Age\"].mean())\ndf2[\"Age\"] = df2[\"Age\"].fillna(value=df2[\"Age\"].mean())\ndf3[\"Age\"] = df3[\"Age\"].fillna(value=df3[\"Age\"].mean())\nframes = [df1, df2, df3]\ndf = pd.concat(frames)\ndf = df.sort_values(by='PassengerId')\ndf[\"Fare\"] = df[\"Fare\"].fillna(value=df[\"Fare\"].mean())\n\nscaler = MinMaxScaler(feature_range=(0, 5))\ndf['Age'] = scaler.fit_transform(df[['Age']])\ndf['Fare'] = scaler.fit_transform(df[['Fare']])\n\nfinal_X = df.iloc[:, 1:]\nfinal_model = KNeighborsClassifier(n_neighbors=4)\nfinal_model.fit(X_train, Y_train)\nfinal_pred = final_model.predict(final_X)\n\npassengers = df.iloc[:, 0]\npassengers = passengers.to_frame()\nprint(passengers)\npassengers['Survived'] = final_pred\nprint(passengers)\npassengers.to_csv('result.csv')\n"
}
] | 1 |
hanibounoua/support-vector-machine
|
https://github.com/hanibounoua/support-vector-machine
|
55f6c44058c1d5ec113a473fda801f06ef2d5efb
|
ad303e0a09842290065351deb6f28ff546fd4740
|
59d7f85cc589da06e533ee4bd16c038c1e5c80e3
|
refs/heads/master
| 2022-04-05T01:52:03.161643 | 2020-02-29T20:06:57 | 2020-02-29T20:06:57 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6580381393432617,
"alphanum_fraction": 0.6798365116119385,
"avg_line_length": 33.9523811340332,
"blob_id": "82595015c82c2f3cf22b3d78fe1316f855895930",
"content_id": "6a8d4f25ee8f732aa60e1f05f1b9d187ec66d217",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 734,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 21,
"path": "/test.py",
"repo_name": "hanibounoua/support-vector-machine",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, confusion_matrix\nimport matplotlib.pyplot as plt\n\nfrom SVM import SVMc\n\n\ndef run():\n X, y = datasets.make_blobs(n_samples=100, n_features=2, centers = 2, cluster_std = 1.05, random_state = 123)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .33, random_state=123)\n model = SVMc()\n model.fit(X_train, y_train)\n y_predicted = model.predict(X_test)\n AUC = roc_auc_score(y_test, y_predicted)\n con_mat = confusion_matrix(y_test, y_predicted)\n return {\"Model\": model, \"AUC\": AUC, \"Confusion Matrix\": con_mat}\n\nif __name__ == \"__main__\":\n run()\n"
},
{
"alpha_fraction": 0.8571428656578064,
"alphanum_fraction": 0.8571428656578064,
"avg_line_length": 23.5,
"blob_id": "16d2072b57f27c69f31953d0694f67c5f9a539e2",
"content_id": "f33b850c1dfd9b1b47e24441734219809ec4735b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 49,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 2,
"path": "/README.md",
"repo_name": "hanibounoua/support-vector-machine",
"src_encoding": "UTF-8",
"text": "# SupportVectorMachine_Py\nSupport Vector Machine\n"
},
{
"alpha_fraction": 0.49562937021255493,
"alphanum_fraction": 0.5069929957389832,
"avg_line_length": 37.779659271240234,
"blob_id": "d2a4607b81918df77ca2e78e60a58d1f5f4f484f",
"content_id": "99279a17302541b66aa38e06e5492c52ecec30ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2288,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 59,
"path": "/SVM.py",
"repo_name": "hanibounoua/support-vector-machine",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\n\n\nclass SVMc:\n def __init__(self, Lambda = .5, C = 1, kernel = 'leaner', learningRate = .001, n_iter = 1000):\n\n # Model's Hyper-Parameters:\n self.Lambda = Lambda # Ponderation Parameter for on the Hinge Loss function\n self.C = C # The Cost Parameter of the mis classified points on the Hinge Loss function.\n self.kernel = kernel # Not linear transformation of D\n self.lr = learningRate # learning Rate Hyper-Parameter that control convergence of training algorithms\n self.n_iter = n_iter # Number of iteration on training algorithm\n\n # Model's Parameters:\n self.omega = None\n self.b = None\n\n def fit(self, X, y):\n\n n_sample, n_feature = X.shape\n y_ = np.where(y == 0, -1, 1) # Here I ve used the same nomencalture as I found.\n # On tutorial, So this variable is used to define positive and negative class.\n self.omega = np.zeros(n_feature)\n self.b = 0\n\n # Gradian Descent ---------------------------------------------------------\n\n for _ in range(self.n_iter):\n for ind, x in enumerate(X):\n\n if y_[ind]*(np.dot(self.omega, x) - self.b) >= 1:\n self.omega -= self.lr * 2 * self.Lambda * self.omega\n else:\n self.omega -= self.lr * ((2 * self.Lambda * self.omega) - self.C * np.dot(x, y_[ind]))\n self.b -= self.lr * self.C * y[ind]\n\n def fit_update(self, X, y):\n\n n_sample, n_feature = X.shape\n y_ = np.where(y <= 0, -1, 1)\n\n # Gradian Descent ---------------------------------------------------------\n\n for _ in range(self.n_iter):\n for ind, x in enumerate(X):\n\n if y_[ind]*(np.dot(self.omega, x) - self.b) >= 1:\n self.omega -= self.lr * 2 * self.Lambda * self.omega\n else:\n self.omega -= self.lr * ((2 * self.Lambda * self.omega) - self.C * np.dot(x, y_[ind]))\n self.b -= self.lr * self.C * y[ind]\n\n def predict(self, X):\n n_sample = X.shape[0]\n y = np.zeros(n_sample)\n for ind, x_i in enumerate(X):\n y[ind] = np.where(np.sign(np.dot(self.omega, x_i) - self.b) > 0, 1, 0)\n return y\n"
}
] | 3 |
marshallward/mosaic
|
https://github.com/marshallward/mosaic
|
d3b28474654c740b3c4fb928ec02f514ae8d225f
|
ada5ef3e421eace4100e378565a3a89f17d1bbca
|
39f470255e0bcde158953d65531eb4973ce3377c
|
refs/heads/master
| 2021-01-19T09:44:35.441091 | 2013-12-13T07:36:04 | 2013-12-13T07:36:04 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.47623318433761597,
"alphanum_fraction": 0.5067264437675476,
"avg_line_length": 21.755102157592773,
"blob_id": "048dd188940c03750f4828dfc2a99996cd1cb232",
"content_id": "962d41759b89b2656eb9d74d752b675d2a66dc49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1115,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 49,
"path": "/latlon.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport numpy as np\n\nr_Earth = 6.371009e6\n\ndef grid(lon_min, lon_max, lat_min, lat_max, d_lon,\n d_lat=None, dense_grid=True):\n\n if not d_lat:\n d_lat = d_lon\n\n # Double grid points for B-grid\n if dense_grid:\n d_lon = 0.5 * d_lon\n d_lat = 0.5 * d_lat\n\n N_lat = int(1 + np.round((lat_max - lat_min)/d_lat))\n lat_axis = np.deg2rad(np.linspace(lat_min, lat_max, N_lat))\n\n N_lon = int(1 + np.round((lon_max - lon_min)/d_lon))\n lon_axis = np.deg2rad(np.linspace(lon_min, lon_max, N_lon))\n\n # Create the grids\n lon, lat = np.meshgrid(lon_axis, lat_axis)\n x = r_Earth * np.cos(lat) * lon\n y = r_Earth * lat\n\n g = Grid()\n\n g.nxp = N_lon\n g.nyp = N_lat\n g.nx = N_lon - 1\n g.ny = N_lat - 1\n\n g.x = np.rad2deg(lon)\n g.y = np.rad2deg(lat)\n g.dx = x[:, 1:] - x[:, :-1]\n g.dy = y[1:, :] - y[:-1, :]\n g.area = (lon[:-1, 1:] - lon[:-1, :-1]) \\\n * (np.sin(lat[1:, :-1]) - np.sin(lat[:-1, :-1])) * r_Earth**2\n g.angle_dx = np.zeros([g.nyp, g.nxp])\n\n return g\n\n\nclass Grid():\n pass\n"
},
{
"alpha_fraction": 0.6031981110572815,
"alphanum_fraction": 0.6117855906486511,
"avg_line_length": 27.61864471435547,
"blob_id": "e9d23dda5c7af7b7ee5f130d1383e260777c7355",
"content_id": "ca42df52889602082dfebcc446e2d647a8b901bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3377,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 118,
"path": "/hgrid.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport netCDF4 as nc\nimport numpy as np\nimport sys\n\nfrom mosaic import mercator as merc\n\n# Parameters\nstring_len = 255\ngrid_version = '0.2'\ntagname = '$Name: siena_201203 $'\n\n\"\"\"\nReproduction of make_hgrid.c\nContact: Marshall Ward ([email protected])\n\"\"\"\n\nmake_hgrid_desc = \"\"\"\nDescription of make_hgrid here.\n\"\"\"\n\ndef save(grid, grid_name=None):\n \n # Parse input arguments\n history = ' '.join(sys.argv)\n \n # Default parameters\n # TODO: Derive parameters from grid\n if not grid_name:\n grid_name = 'horizontal_grid.nc'\n center = None\n geometry = 'spherical'\n projection = None\n arcx = 'small_circle'\n north_pole_tile = '0.0 90.0'\n discretization = 'logically_rectangular'\n conformal = 'true'\n north_pole_arcx = 'small_circle'\n \n # TODO: Mosaic tile implementation\n tile_name = 'tile1'\n \n # Create output file\n grid_nc = nc.Dataset(grid_name, 'w')\n \n # Global attributes\n grid_nc.grid_version = grid_version\n grid_nc.code_version = tagname\n grid_nc.history = history\n \n grid_nc.createDimension('string', string_len)\n grid_nc.createDimension('nx', grid.nx)\n grid_nc.createDimension('ny', grid.ny)\n grid_nc.createDimension('nxp', grid.nxp)\n grid_nc.createDimension('nyp', grid.nyp)\n \n # Mosaic tile properties\n tile_nc = grid_nc.createVariable('tile', 'S1', ('string',))\n tile_nc[:len(tile_name)] = list(tile_name)\n tile_nc.standard_name = 'grid_tile_spec'\n tile_nc.geometry = geometry\n if north_pole_tile:\n tile_nc.north_pole_tile = north_pole_tile\n if projection:\n tile_nc.projection = projection\n tile_nc.discretization = discretization\n tile_nc.conformal = conformal\n \n # Grid variables\n x_nc = grid_nc.createVariable('x', 'f8', ('nyp', 'nxp'))\n x_nc[:] = grid.x\n x_nc.standard_name = 'geographic_longitude'\n x_nc.units = 'degree_east'\n \n y_nc = grid_nc.createVariable('y', 'f8', ('nyp', 'nxp'))\n y_nc[:] = grid.y\n y_nc.standard_name = 'geographic_latitude'\n y_nc.units = 'degree_north'\n \n dx_nc = grid_nc.createVariable('dx', 'f8', ('nyp', 'nx'))\n dx_nc[:] = grid.dx\n dx_nc.standard_name = 'grid_edge_x_distance'\n dx_nc.units = 'meters'\n \n dy_nc = grid_nc.createVariable('dy', 'f8', ('ny', 'nxp'))\n dy_nc[:] = grid.dy\n dy_nc.standard_name = 'grid_edge_y_distance'\n dy_nc.units = 'meters'\n \n area_nc = grid_nc.createVariable('area', 'f8', ('ny', 'nx'))\n area_nc[:] = grid.area\n area_nc.standard_name = 'grid_cell_area'\n area_nc.units = 'm2'\n \n angle_dx_nc = grid_nc.createVariable('angle_dx', 'f8', ('nyp', 'nxp'))\n angle_dx_nc[:] = grid.angle_dx\n angle_dx_nc.standard_name = 'grid_vertex_x_angle_WRT_geographic_east'\n angle_dx_nc.units = 'degrees_east'\n \n if not conformal:\n angle_dy_nc = grid_nc.createVariable('angle_dy', 'f8', ('nyp', 'nxp'))\n angle_dy_nc[:] = grid.angle_dy\n angle_dy_nc.standard_name = 'grid_vertex_y_angle_WRT_geographic_north'\n angle_dy_nc.units = 'degrees_north'\n \n arcx_nc = grid_nc.createVariable('arcx', 'S1', ('string',))\n arcx_nc[:len(arcx)] = list(arcx)\n arcx_nc.standard_name = 'grid_edge_x_arc_type'\n if north_pole_arcx:\n arcx_nc.north_pole = north_pole_arcx\n \n grid_nc.close()\n\n\nclass Grid(object):\n pass\n"
},
{
"alpha_fraction": 0.5138248801231384,
"alphanum_fraction": 0.5476190447807312,
"avg_line_length": 23.11111068725586,
"blob_id": "6c274d17f3832849619922dfd605923dac186751",
"content_id": "96c8a7555f13f6ad97e94de00af9089ab9b42d76",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1302,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 54,
"path": "/stress.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport netCDF4 as nc\nimport numpy as np\nimport sys\n\n#---\ndef save(tau_x, grid):\n # TODO: Promote tau to 2D vector\n \n history = ' '.join(sys.argv)\n \n # Default parameters\n stress_name = 'stress.nc'\n tau_x_name = 'taux'\n tau_y_name = 'tauy'\n \n # Testing\n grid_name = 'horizontal_grid.nc'\n grid_nc = nc.Dataset(grid_name, 'r')\n x_grid = grid_nc.variables['x'][1::2, 1::2]\n y_grid = grid_nc.variables['y'][1::2, 1::2]\n \n x = grid.x[0, :]\n y = grix.y[:, 0]\n t = np.zeros(1)\n \n nx = x.size\n ny = y.size\n nt = t.size\n \n # Create output file\n stress_nc = nc.Dataset(stress_name, 'w')\n \n stress_nc.createDimension('x', nx)\n stress_nc.createDimension('y', ny)\n stress_nc.createDimension('time', None)\n \n x_nc = stress_nc.createVariable('x', 'f8', ('x',))\n x_nc[:] = x\n \n y_nc = stress_nc.createVariable('y', 'f8', ('y',))\n y_nc[:] = y\n \n time_nc = stress_nc.createVariable('time', 'f8', ('time',))\n time_nc[:] = t\n time_nc.calendar = 'no_leap'\n time_nc.units = 'seconds since 0001-01-01 00:00:00'\n \n taux_nc = stress_nc.createVariable('taux', 'f8', ('time', 'y', 'x'))\n taux_nc[:] = tau_x\n \n stress_nc.close()\n"
},
{
"alpha_fraction": 0.5550765991210938,
"alphanum_fraction": 0.5742337107658386,
"avg_line_length": 21.94505500793457,
"blob_id": "f66d5ab51cf2e95c2bffd6580fd20dd2c96f932c",
"content_id": "336254b79ab8da8d209e90a2fbfa9e2a2872317d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2088,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 91,
"path": "/mercator.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nMercator grid generation\n========================\n\nMercator grids are generated under the assumption of dx = dy,\n\n.. math::\n \\cos \\phi d \\lambda = d \\phi\n\nThe integral of this relation is\n\n\\lambda(\\phi) = \\tan \\left( \\frac{\\phi}{2} + \\frac{\\pi}{4} \\right)\n\nThis mapping, and its inverse, are implemented in the `mercator_axis` and\n`latitude_axis` functions, respectively.\n\nTo generate the grid:\n\n - Define a uniform longitude axis (lambda) over all latitudes\n - Map lambda to phi for each latitude\n\nFeatures of Mercator grids (in contrast to spherical grids):\n -\n\n\"\"\"\n\nimport numpy as np\n\nr_Earth = 6.371009e6\n\ndef mercator_axis(lat):\n return np.log(np.tan(lat/2. + np.pi/4.))\n\n\ndef latitude_axis(y):\n return 2.*np.arctan(np.exp(y)) - np.pi/2.\n\n\ndef grid(lon_min, lon_max, lat_min, lat_max, d_lon_eq, dense_grid=True):\n\n # Double grid points for B-grid\n if dense_grid:\n d_lon = 0.5*d_lon_eq\n else:\n d_lon = d_lon_eq\n\n y_min = mercator_axis(np.deg2rad(lat_min))\n y_max = mercator_axis(np.deg2rad(lat_max))\n d_y = np.deg2rad(d_lon)\n\n # Adjust y_min and y_max as multiples of d_y\n # (so that the equator lies on the grid)\n y_min = np.round(y_min/d_y)*d_y\n y_max = np.round(y_max/d_y)*d_y\n\n N_y = int(1 + np.round((y_max - y_min)/d_y))\n y = np.linspace(y_min, y_max, N_y)\n lat_axis = latitude_axis(y)\n\n # Longitude axis\n N_lon = int(1 + np.round((lon_max - lon_min)/d_lon))\n lon_axis = np.deg2rad(np.linspace(lon_min, lon_max, N_lon))\n\n # Create the grids\n lon, lat = np.meshgrid(lon_axis, lat_axis)\n x = r_Earth * np.cos(lat) * lon\n y = r_Earth * lat\n\n g = Grid()\n\n g.nxp = N_lon\n g.nyp = N_y\n g.nx = N_lon - 1\n g.ny = N_y - 1\n\n g.x = np.rad2deg(lon)\n g.y = np.rad2deg(lat)\n g.dx = x[:,1:] - x[:,:-1]\n g.dy = y[1:,:] - y[:-1,:]\n g.area = (lon[:-1,1:] - lon[:-1,:-1]) \\\n * (np.sin(lat[1:,:-1]) - np.sin(lat[:-1,:-1])) * r_Earth**2\n g.angle_dx = np.zeros([g.nyp, g.nxp])\n\n return g\n\n\nclass Grid():\n pass\n"
},
{
"alpha_fraction": 0.4637477993965149,
"alphanum_fraction": 0.5064798593521118,
"avg_line_length": 21.84000015258789,
"blob_id": "95713e8bd5a8e240b5081254c583a5a78ac53919",
"content_id": "9ae0fc7f0eaf11b70e18ed0f1de6e61156022087",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2855,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 125,
"path": "/topog.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport netCDF4 as nc\nimport numpy as np\nimport sys\n\ngrid_version = '0.2'\ncode_version = '$Name: siena_z1l $'\n\n\"\"\"\nEmulation of make_topog.c\n\"\"\"\ndef main():\n\n # Testing parameters\n grid_file = 'horizontal_grid.nc'\n \n grid_nc = nc.Dataset(grid_file, 'r')\n x_grid = grid_nc.variables['x'][1::2, 1::2]\n y_grid = grid_nc.variables['y'][1::2, 1::2]\n \n # Testing\n x = x_grid[0,:]\n y = y_grid[:,0]\n \n nx = x.size\n ny = y.size\n\n depth = np.zeros([ny, nx])\n depth = andy_topog(x_grid, y_grid)\n \n save_topog(depth)\n\n\ndef example_topog(x, y):\n \"\"\"\n Example of a complex depth function\n Created by Andy Hogg for MITgcm sector modelling\n \"\"\"\n \n # Arbitrary parameters\n D = 4000.\n dc = 59.\n nx = x.shape[1]\n rx = 0.25 # Base resolution\n shelf_depth = 800.\n sws = 3.\n dy_end = 0.5*(y[-2,0] - y[-1,0])\n y_end = y[-1,0] + dy_end\n \n # Western shelf\n h_w = D * (2.**(-0.4 * x**2)\n * (1. - 0.5 * 2.**(-0.003 * np.abs(-y - dc)**4)) - 0.9) / 0.9\n\n # Eastern shelf\n h_e = D * (2.**(-0.4 * (x - nx*rx)**2)\n * (1. - 0.5 * 2**(-0.003 * np.abs(-y - dc)**4)) - 0.9) / 0.9\n\n h = np.maximum(np.minimum(0., h_w), np.minimum(0., h_e))\n \n # Southern shelf\n h_s = -D*np.ones(h.shape)\n \n # Define masks\n m1 = y < -y_end + sws\n m2 = np.logical_and(-y_end + sws <= y, y < -y_end + 2*sws)\n m3 = np.logical_and(-y_end + 2*sws <= y, y < -y_end + 3*sws)\n \n h_s1 = -shelf_depth * (1. + ((y[m1] - (-y_end + sws))/sws)**3)\n h_s[m1] = h_s1\n \n h_s2 = -shelf_depth - (0.5 * (D - shelf_depth)\n * ((y[m2] - (-y_end + sws))/sws)**3)\n h_s[m2] = h_s2\n \n h_s3 = -D - (0.5 * (D - shelf_depth)\n * ((y[m3] - (-y_end + 3*sws))/sws)**3)\n h_s[m3] = h_s3\n\n h = np.maximum(h, h_s)\n\n # Flip sign for MOM\n h = -h\n h[h == 0.] = 0.\n\n return h\n\n\ndef save(depth, topog_fname=None):\n \n # Parse input arguments\n history = ' '.join(sys.argv)\n \n if not topog_fname:\n topog_fname = 'topog.nc'\n depth_name = 'depth'\n \n # Create output file\n topog_nc = nc.Dataset(topog_fname, 'w')\n \n # Global attributes\n topog_nc.grid_version = grid_version\n topog_nc.code_version = code_version\n topog_nc.history = history\n \n # Testing\n ntiles = 1\n ny, nx = depth.shape\n\n topog_nc.createDimension('ntiles', ntiles)\n topog_nc.createDimension('nx', nx)\n topog_nc.createDimension('ny', ny)\n \n depth_nc = topog_nc.createVariable(depth_name, 'f8', ('ny', 'nx'))\n depth_nc[:] = depth\n depth_nc.standard_name = 'topographic depth at T-cell centers'\n depth_nc.units = 'meters'\n \n topog_nc.close()\n\n\n#---\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.6024914979934692,
"alphanum_fraction": 0.6149490475654602,
"avg_line_length": 19.534883499145508,
"blob_id": "3b4a973fab324df25e753d8dda6831a35e7a7987",
"content_id": "85af90eb0471256a67c9b6589c3bcdb77d6c93c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 883,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 43,
"path": "/vgrid.py",
"repo_name": "marshallward/mosaic",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# coding: utf-8\n\nimport netCDF4 as nc\nimport numpy as np\nimport sys\nimport argparse\n\ngrid_version = '0.2'\ncode_version = '$Name: siena_201203 $'\n\n\"\"\"\nEmulation of make_vgrid.c\nContact: Marshall Ward ([email protected])\n\"\"\"\n\ndef save(zeta, grid_name=None):\n \n history = ' '.join(sys.argv)\n \n # Get nzv from zeta:\n nzv = zeta.size\n\n # Default tags\n if not grid_name:\n grid_name = 'vertical_grid.nc'\n \n # Create output file\n vgrid_nc = nc.Dataset(grid_name, 'w')\n \n # Global attributes\n vgrid_nc.grid_version = grid_version\n vgrid_nc.code_version = code_version\n vgrid_nc.history = history\n \n vgrid_nc.createDimension('nzv', nzv)\n \n zeta_nc = vgrid_nc.createVariable('zeta', 'f8', ('nzv',))\n zeta_nc[:] = zeta\n zeta_nc.standard_name = 'vertical_grid_vertex'\n zeta_nc.units = 'meters'\n\n vgrid_nc.close()\n"
}
] | 6 |
abe1272001/movie_crawler
|
https://github.com/abe1272001/movie_crawler
|
7b9a89399b9356b22644b9472cf34882d1c1df1c
|
0226fdbc2a401086390ce04e089a701189ba3f36
|
e0a247027d13c93e9e93de7d9cad35c9af5c8484
|
refs/heads/master
| 2023-07-08T09:05:06.904929 | 2021-08-19T06:20:18 | 2021-08-19T06:20:18 | 397,087,865 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4991181790828705,
"alphanum_fraction": 0.5225268602371216,
"avg_line_length": 36.806060791015625,
"blob_id": "75db2024a5942eb76cbeed44bad1a97c15d1c3e8",
"content_id": "955988b570baefa582e7bccf03a6e5f3114c065d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6479,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 165,
"path": "/GetAmbassadorTimeTable.py",
"repo_name": "abe1272001/movie_crawler",
"src_encoding": "UTF-8",
"text": "import requests\nimport datetime\nimport re\nimport json\nfrom bs4 import BeautifulSoup\nfrom urllib.parse import parse_qs\nimport urllib.parse as urlparse\nimport time \nimport os\n\n# https://www.ambassador.com.tw/home/TheaterList #影城頁面\n# theaterInfos = [ # init data structure\n# {\n# 'crawler_theater_name': '國賓大戲院', \n# 'crawler_theater_id': '84b87b82-b936-4a39-b91f-e88328d33b4e', \n# 'address': '台北市成都路88號', \n# 'tel': '02-2361-1223', \n# 'datesTable': []\n# }\n# ]\n\n# 匯出到指定資料夾的 function, 還需測試 \n# def write_json(target_path, target_file, data): \n# if not os.path.exists(target_path):\n# try:\n# os.makedirs(target_path)\n# except Exception as e:\n# print(e)\n# raise\n# with open(os.path.join(target_path, target_file), 'w', encoding='utf-8') as f:\n# json.dump(data, f, ensure_ascii=False, indent = 2)\n\n\n\"\"\"\n取得影城資訊及 ID\nReturn:\n array: array of theater infos\n\"\"\"\ndef getTheaterInfos():\n theaterInfos = []\n r_theater = requests.get('https://www.ambassador.com.tw/home/TheaterList')\n soup_theater = BeautifulSoup(r_theater.text, \"html.parser\")\n theater_cells = soup_theater.select('div.theater > div.cell')\n for cell in theater_cells:\n theater_info_block = cell.find('div', class_=\"theater-info\")\n a_tag_href = cell.find(\"a\").get('href')\n parsed_url = urlparse.urlparse(a_tag_href)\n theater_ID = parse_qs(parsed_url.query)['ID'][0]\n theater_name = theater_info_block.find('h6').text\n theater_address = theater_info_block.find('p').text\n theater_phone = theater_info_block.find('p').find_next_sibling('p').text\n theaterInfos.append({\n 'crawler_theater_name': theater_name,\n 'crawler_theater_id': theater_ID,\n 'address': theater_address,\n 'tel': theater_phone,\n 'datesTable': []\n })\n return theaterInfos\n\n\"\"\"\nThis is get next few date function\n可控制取得天數 n + 1 天\n\nParam:\n int: how many days\nReturn:\n array: array of dates. ex: ['2021/08/17', '2021/08/18', '2021/08/19']\n\"\"\"\ndef getDates(n):\n today_after_6_days = []\n x = datetime.datetime.now()\n t_year = x.year\n t_month = x.strftime(\"%m\")\n t_day = x.strftime(\"%d\")\n today_date = time.strftime(\"%Y/%m/%d\", time.localtime())\n today_after_6_days.append(today_date)\n # n = 5 #選擇後 5 天, 將日期存成 ary\n for x in range(n):\n d = x + 1\n date = datetime.datetime(int(t_year), int(t_month), int(t_day)) + datetime.timedelta(days=d)\t# 2015-10-29 00:00:00\n time_format = date.strftime('%Y/%m/%d')\t# '2021/08/18'\n today_after_6_days.append(time_format)\n return today_after_6_days\n\n\n#https://www.ambassador.com.tw/home/Showtime?ID=84b87b82-b936-4a39-b91f-e88328d33b4e&DT=2021/08/13\n#取得包含今日之後的 6 天日期 ex: 2021/08/13\n# for loop theaters\n #for loop dates\ntheaterInfos = getTheaterInfos()\ndates = getDates(5) # 取得包含今日的六天日期\ntoday = dates[0]\nprint(dates)\nprint(theaterInfos)\nfor theater in theaterInfos:\n print(f\"======================================= {theater['crawler_theater_name']} ==============================================\")\n for d in dates:\n r = requests.get(f\"https://www.ambassador.com.tw/home/Showtime?ID={theater['crawler_theater_id']}&DT={d}\")\n soup = BeautifulSoup(r.text, \"html.parser\")\n movies = soup.find_all('div', class_='showtime-item')\n # print(movies)\n if(len(movies) == 0): # 若當日無電影則繼續下一天\n print(theater['crawler_theater_name'] + ', ' + str(d) + '無電影' )\n continue\n\n moviesInfo = {\n 'date': d,\n 'movies' :[]\n }\n print(f\"***({d})***\")\n for movie in movies:\n movie_title_eng = movie.select_one('h3 a span').getText() # 電影名稱\n movie_title = movie.select_one('h3 a').getText().replace(movie_title_eng, '') # 電影名稱英文\n movie_level = movie.select_one('.info span').getText() # 電影分級\n movie_duration = movie.select_one('.info span').find_next_sibling('span').getText() # 電影時長\n print(f\"-----------------------------{movie_title}--------------------------------------------\")\n types = movie.find_all('p', class_='tag-seat')\n timeTable = []\n for type in types:\n hall_type = re.findall(r'[(](.*?)[)]', type.getText()) \n time_doms = type.find_next_siblings('ul')[0].find_all('h6')\n hall_doms = type.find_next_siblings('ul')[0].find_all('span', class_='float-left info') # 影廳節點\n times = []\n \n for index, t in enumerate(time_doms):\n # try:\n # print(hall_doms[index].text.split()[0])\n # except:\n # print(f\"https://www.ambassador.com.tw/home/Showtime?ID={theater['id']}&DT={d}\")\n # break\n \n times.append({\n 'time': t.text.strip(),\n 'hall': hall_doms[index].text.split()[0],\n 'capacity': hall_doms[index].text.split()[1]\n })\n # print(times)\n data = {\n 'type': hall_type[0],\n 'times': times\n }\n timeTable.append(data)\n print(data)\n \n movieData = {\n 'title' : movie_title,\n 'title_eng': movie_title_eng,\n 'level' : movie_level,\n 'duration' : movie_duration,\n 'timeTable': timeTable\n }\n moviesInfo['movies'].append(movieData)\n \n print('-------------------------------------------------------------------------')\n # 將結果存回 movieTheaterInfos\n theater['datesTable'].append(moviesInfo) \n # break\n\nprint('Crawler finished! Well Done')\n# write_json('/json', 'Ambassador.json', theaterInfos) #未測試\nwith open('Ambassador.json', 'w', encoding='utf-8') as f:\n json.dump(theaterInfos, f, ensure_ascii=False, indent = 2)\nprint('JSON dump finished')\n################################################################"
}
] | 1 |
LastBreach/Showcases
|
https://github.com/LastBreach/Showcases
|
d4788b51e5c915fbb02941cb2c0e560b1b17dce4
|
0e263b5915ab1b3d304c89391814baa32f30e332
|
e057783525e34cde3db0c3543ed82ca73657842f
|
refs/heads/master
| 2016-09-06T17:04:31.579238 | 2015-07-04T16:21:49 | 2015-07-04T16:21:49 | 38,538,724 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7961432337760925,
"alphanum_fraction": 0.7961432337760925,
"avg_line_length": 70.4000015258789,
"blob_id": "b107e5d7f1bfcce6edb47aff64978fa0314f42c6",
"content_id": "36436778324cb4c1f7ed7ee98f01f5ae954f5120",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 5,
"path": "/README.md",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "# LastBreach Security Showcases #\r\nThese showcases are created by LastBreach to explain a multitude threats, vulnerabilities and security issues.\r\n\r\nAll showcases and detailed information on their topics can be found on the official [LastBreach blog](https://www.lastbreach.com/en/blog/).\r\nThe source code for all showcases can be found in this git repository. \r\n"
},
{
"alpha_fraction": 0.5775347948074341,
"alphanum_fraction": 0.5854870676994324,
"avg_line_length": 32.53333282470703,
"blob_id": "bfd6df410564e4706c151e9163b2c7615e438060",
"content_id": "d2007d34a66a12ce18c4e9128d042ed255bff759",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1006,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 30,
"path": "/authentication/login_brute_force/index.py",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request, make_response\nimport md5\napp = Flask(__name__, static_folder='../../assets', static_url_path='')\n\nuser_db=[\"admin:password:[email protected]\",\"user:s3cr3t:[email protected]\",\"bob:b0b:[email protected]\"]\n\[email protected]('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\[email protected]('/login', methods=['POST'])\ndef download():\n usr = request.form['usr']\n pwd = request.form['pwd']\n for entry in user_db:\n db_usr=entry.split(\":\")[0]\n db_pwd=entry.split(\":\")[1]\n if db_usr==usr:\n if db_pwd==pwd:\n status=\"Login successful\"\n return render_template('intern.html', status=status)\n else:\n status=\"Wrong username or password!\"\n return render_template('index.html', status=status)\n else:\n status=\"Wrong username or password!\"\n return render_template('index.html', status=status)\n\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n"
},
{
"alpha_fraction": 0.5957762002944946,
"alphanum_fraction": 0.6180066466331482,
"avg_line_length": 36.48611068725586,
"blob_id": "2425d60fd910728c73972ec5c50d2153376b7cc1",
"content_id": "5c645cf6755d06d2bdfbca5d999b28ececffbcbe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2699,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 72,
"path": "/authentication/password_reset/index.py",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request, make_response\nimport md5\napp = Flask(__name__, static_folder='../../assets', static_url_path='')\n\nuser_db=[\"admin:admin:[email protected]\",\"user:password:[email protected]\",\"bob:s3cr3tb0b:[email protected]\"]\n\[email protected]('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\n# send cleartext password\[email protected]('/forgot1', methods=['POST'])\ndef forgot1():\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\[email protected]('/reset1', methods=['GET'])\ndef reset1():\n token = request.args['token']\n user = request.args['user']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\n# send guessable link\[email protected]('/forgot2', methods=['POST'])\ndef forgot2():\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\n\[email protected]('/reset2', methods=['POST'])\ndef reset2():\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\n# send link with user reset time based activation\[email protected]('/forgot3', methods=['POST'])\ndef forgot3():\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\[email protected]('/reset3', methods=['POST'])\ndef reset3():\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('index.html', status1=\"Sent, check your mail!\", status2=\"\", status3=\"\")\n return render_template('index.html', status1=\"\", status2=\"\", status3=\"\")\n\n\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n"
},
{
"alpha_fraction": 0.5770446062088013,
"alphanum_fraction": 0.5840646028518677,
"avg_line_length": 36.98666763305664,
"blob_id": "30d7ab7154d3ffd2e8a7eaca5e4ae15ad7353c63",
"content_id": "60418df8f3d9c094cdc7ade6704ab198a7d741bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2849,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 75,
"path": "/authentication/login_data_enumeration/index.py",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request, make_response\nimport md5\napp = Flask(__name__, static_folder='../../assets', static_url_path='')\n\nuser_db=[\"admin:admin:[email protected]\",\"user:password:[email protected]\",\"bob:s3cr3tb0b:[email protected]\"]\n\[email protected]('/', methods=['GET'])\ndef index():\n return render_template('index.html')\n\[email protected]('/login', methods=['POST'])\ndef download():\n usr = request.form['usr']\n pwd = request.form['pwd']\n for entry in user_db:\n db_usr=entry.split(\":\")[0]\n db_pwd=entry.split(\":\")[1]\n if db_usr==usr:\n if db_pwd==pwd:\n status=\"Login successful\"\n return render_template('intern.html', status=status)\n else:\n status=\"Wrong password!\"\n return render_template('index.html', status=status)\n else:\n status=\"Wrong username!\"\n return render_template('index.html', status=status)\n\[email protected]('/forgot', methods=['GET','POST'])\ndef forgot():\n if request.method == \"POST\":\n email = request.form['email']\n for entry in user_db:\n db_email=entry.split(\":\")[2]\n if db_email==email:\n return render_template('forgot.html', status=\"Password reset link was sent\")\n return render_template('forgot.html', status=\"Email not found!\")\n return render_template('forgot.html', status=\"\")\n\[email protected]('/register', methods=['GET','POST'])\ndef register():\n status=\"\"\n pwd_status=\"\"\n user_status=\"\"\n mail_status=\"\"\n\n if request.method == \"POST\":\n user = request.form['user']\n mail = request.form['mail']\n pwd1 = request.form['pwd1']\n pwd2 = request.form['pwd2']\n\n if user==\"\" or user==None:\n return render_template('register.html', status=\"No user specified!\")\n if mail==\"\" or mail==None:\n return render_template('register.html', status=\"No email specified!\")\n if \"@\" not in mail or \".\" not in mail:\n return render_template('register.html', status=\"Please specify a valid email address!\")\n if not (pwd1==pwd2 and pwd1!=\"\" and pwd1!=None):\n return render_template('register.html', status=\"Password missmatch!\")\n for entry in user_db:\n db_user=entry.split(\":\")[0]\n db_mail=entry.split(\":\")[2]\n if db_user==user:\n return render_template('register.html', status=\"user not available!\")\n if db_mail==mail:\n return render_template('register.html', status=\"email is already registered!\")\n db_entry=\"%s:%s:%s\" % (user, pwd1, mail)\n user_db.append(db_entry)\n return render_template('register.html', status=\"Thanks for registering!\")\n return render_template('register.html', status=status)\n\n\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n"
},
{
"alpha_fraction": 0.4770408272743225,
"alphanum_fraction": 0.5561224222183228,
"avg_line_length": 31.66666603088379,
"blob_id": "55fb4eeaeb56d6a5b95c14223dbf0099c290c2e1",
"content_id": "836d10381945df2a70fc4a691e7cf1ff72441575",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 784,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 24,
"path": "/access_control/entity_enumeration/index.py",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request\napp = Flask(__name__, static_folder='../../assets', static_url_path='')\n\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n status=\"\"\n if request.method == \"POST\":\n try:\n document = request.form['doc']\n if document in [\"123452\",\"123456\",\"123547\",\"123458\",\"123459\"]:\n status=\"Document sent for approval!\"\n elif document in [\"123460\",\"123461\",\"123466\",\"123450\",\"123453\"]:\n status=\"Access denied!\"\n else:\n status=\"Document not found!\"\n except:\n return render_template('index.html', status=\"\")\n return render_template('index.html', status=status)\n\n\n\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n"
},
{
"alpha_fraction": 0.5202572345733643,
"alphanum_fraction": 0.6032154560089111,
"avg_line_length": 37.875,
"blob_id": "72593d42735a7dde69d10a839a4128b1c04889da",
"content_id": "2ed6c3cb9fbf1b1897b2040fe19d1e10128f8d92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1555,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 40,
"path": "/access_control/privilege_escalation/index.py",
"repo_name": "LastBreach/Showcases",
"src_encoding": "UTF-8",
"text": "from flask import Flask, render_template, request, make_response\nimport md5\napp = Flask(__name__, static_folder='../../assets', static_url_path='')\n\n# Fake \"databases\" containing all document IDs and their relations (to keep it simple - it's a showcase!)\ndocs=[\"123452\",\"123456\",\"123547\",\"123458\",\"123459\",\"123460\",\"123461\",\"123466\",\"123450\",\"123453\"]\nuserdocs=[\"123452\",\"123456\",\"123547\",\"123458\",\"123459\"]\ndenydocs=[[\"123460\",\"123461\",\"123466\",\"123450\",\"123453\"]]\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n status=\"\"\n linkname=\"\"\n if request.method == \"POST\":\n try:\n req_docid = request.form['doc']\n docsum=md5.new(req_docid).hexdigest() #md5\n if req_docid in userdocs:\n status=\"/download?doc=%s\" % docsum\n linkname=\"Download Link\"\n else:\n status=\"Document not found!\"\n except:\n return render_template('index.html', status=\"\", linkname=\"\")\n return render_template('index.html', status=status, linkname=linkname)\n\[email protected]('/download', methods=['GET'])\ndef download():\n req_docsum = request.args['doc']\n for doc in docs:\n docsum=md5.new(doc).hexdigest()\n if docsum==req_docsum:\n csv=\"Private userdata for employee nr. %s\" % doc\n response = make_response(csv)\n response.headers[\"Content-Disposition\"] = \"attachment; filename=report.csv\"\n return response\n return \"404 - page not found!\"\n\nif __name__ == '__main__':\n app.run(port=80, debug=True)\n"
}
] | 6 |
mattmahoneyus/raspberry-alarm
|
https://github.com/mattmahoneyus/raspberry-alarm
|
774d3495044169e55e2617eb864052a5906a3ad1
|
48d4af212dba93acc329bb58118985355ce97e93
|
6f92e3a958e919b261f8e355ffc57cc249bcce8e
|
refs/heads/master
| 2020-03-28T02:41:35.181595 | 2018-09-06T01:10:56 | 2018-09-06T01:10:56 | 147,590,063 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6291413903236389,
"alphanum_fraction": 0.6355594396591187,
"avg_line_length": 30.156757354736328,
"blob_id": "3d93453b07d7ff7ef4c309c6e9b94c46bf8111d0",
"content_id": "a7a9ae4618c6522068801b2342e050141ee1423b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5765,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 185,
"path": "/alarm.py",
"repo_name": "mattmahoneyus/raspberry-alarm",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport time\nimport math\nimport subprocess\nimport gpiozero\nfrom twilio.rest import Client\nfrom datetime import datetime\nfrom argparse import ArgumentParser\n\nsendText = None\ntakePicture = None\ndebug = None\nledOn = None\nswitchEnabled = None\nemailPicture = None\nnumberOfPictures = 3\npictureDir = \"/home/pi/Pictures\"\n\ncurrentTime = time.time()\n\n# Pin definitions\nled = gpiozero.LED(24)\nsensor1 = gpiozero.MotionSensor(22)\nsensor2 = gpiozero.MotionSensor(23)\nswitch1 = gpiozero.LED(17)\n \ndef exec_cmd(cmd):\n print \"Cmd: {}\".format(cmd)\n p = subprocess.Popen(\"/bin/bash\", shell=True, stdin=subprocess.PIPE,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n p.stdin.write(cmd)\n stdout, stderr = p.communicate()\n return stdout, stderr\n\ndef sendTextMessage(sendText, msg):\n account_sid = \"<your-account-sid>\"\n auth_token = \"<your-auth-token>\"\n client = Client(account_sid, auth_token)\n\n if sendText:\n try:\n print \"***Sending Text: {}\".format(msg)\n message = client.api.account.messages.create(\n to=\"<your-cell-number>\",\n from_=\"<your-twilio-number>\",\n body=msg)\n except Exception as ex:\n print(ex)\n\n else:\n print \"*** Text NOT Sent: {}\".format(msg)\n\ndef takeAPicture(takePicture, dir):\n if (takePicture):\n try:\n for p in range(numberOfPictures):\n\t file = \"{}/motion-{}.jpg\".format(dir, datetime.now().isoformat())\n cmd = \"raspistill -rot -hf -ex night -sh 100 -o {}\".format(file)\n exec_cmd(cmd)\n print \"Image file: {}\".format(file)\n\n if (emailPicture):\n sendPicture(file)\n\n except Exception as ex:\n print (ex)\n else:\n print \"Image NOT taken.\"\n\t\n\t\n# Switch: On == LED.off # Off == LED.on\ndef switchOnOff(switch, enabled, on=False):\n if enabled:\n\tif on:\n print \"Turn switch on\"\n switch.off()\n return True\n else:\n print \"Turn switch off\"\n switch.on()\n return False\n\ndef sendPicture(imageToSend):\n import os\n import smtplib\n from email.MIMEMultipart import MIMEMultipart\n from email.MIMEText import MIMEText\n from email.mime.image import MIMEImage\n\n gmailUser = '<[email protected]>'\n gmailPassword = '<your-password>'\n recipient = '<your-email-recipient>'\n message='<Your Message>'\n\n msg = MIMEMultipart()\n msg['From'] = gmailUser\n msg['To'] = recipient\n msg['Subject'] = 'Your Subject'\n msg.attach(MIMEText(message))\n img_data = open(imageToSend, 'rb').read()\n image = MIMEImage(img_data, name=os.path.basename(imageToSend))\n msg.attach(image)\n\n mailServer = smtplib.SMTP('smtp.gmail.com', 587)\n mailServer.ehlo()\n mailServer.starttls()\n mailServer.ehlo()\n mailServer.login(gmailUser, gmailPassword)\n print \"Sending Picture: {}\".format(imageToSend)\n mailServer.sendmail(gmailUser, recipient, msg.as_string())\n mailServer.close()\n\n\n## Main\n\nparser = ArgumentParser()\nparser.add_argument(\"-t\", \"--text\", action=\"store_true\", dest=\"sendText\", default=False, help=\"Send text\")\nparser.add_argument(\"-p\", \"--picture\", action=\"store_true\", dest=\"takePicture\", default=False, help=\"Take picture\")\nparser.add_argument(\"-d\", \"--debug\", action=\"store_true\", dest=\"debug\", default=False, help=\"Debug mode - No Delays\")\nparser.add_argument(\"-l\", \"--led\", action=\"store_true\", dest=\"ledOn\", default=False, help=\"Turn on LED\")\nparser.add_argument(\"-s\", \"--switch\", action=\"store_true\", dest=\"switchEnabled\", default=False, help=\"Enable Switch\")\nparser.add_argument(\"-e\", \"--email\", action=\"store_true\", dest=\"emailPicture\", default=False, help=\"Email picture\")\n\nsendText = parser.parse_args().sendText\ntakePicture = parser.parse_args().takePicture\ndebug = parser.parse_args().debug\nledOn = parser.parse_args().ledOn\nswitchEnabled = parser.parse_args().switchEnabled\nemailPicture = parser.parse_args().emailPicture\n\nif debug:\n print \"sendText: {}\".format(sendText)\n print \"takePicture: {}\".format(takePicture)\n print \"debug: {}\".format(debug)\n print \"ledOn: {}\".format(ledOn)\n print \"switchEnabled: {}\".format(switchEnabled)\n print \"emailPicture: {}\".format(emailPicture)\n\nstartDelay = 0 if debug else 30\ntextDelay = 0 if debug else (60 * 15)\nswitchIsOn = switchOnOff(switch1, True, on=False)\n\nprint \"Start delay: {}\".format(time.ctime())\ntime.sleep(startDelay)\nprint \"Begin sensor: {}\".format(time.ctime())\n\ntry:\n while True:\n if sensor1.motion_detected or sensor2.motion_detected:\n motion = \"\"\n if sensor1.motion_detected:\n motion = \"Motion-1\"\n if sensor2.motion_detected:\n motion = \"{} Motion-2\".format(motion)\n \n print \"{} detected {}\".format(motion, time.ctime())\n\n if ledOn:\n led.on()\n\n switchIsOn = switchOnOff(switch1, switchEnabled, on=True)\n\n \t elapsedTime = math.ceil(time.time() - currentTime)\n #print \"tDelay: {} eTIme: {}\".format(textDelay,elapsedTime)\n if elapsedTime > textDelay:\n sendTextMessage(sendText, \"{} tripped. Time: {}\".format(motion, time.ctime()))\n takeAPicture(takePicture, pictureDir)\n currentTime = time.time()\n #else:\n\t #print \"Time before sending a text: {}\".format(textDelay-elapsedTime)\n else:\n if ledOn:\n\t led.off()\n if switchEnabled and switchIsOn:\n switchIsOn = switchOnOff(switch1, switchEnabled, on=False)\n \n time.sleep(3)\n\nexcept KeyboardInterrupt:\n print \"Keyboard interrupt\"\n \nfinally: \n print \"In Finally\"\n switchIsOn = switchOnOff(switch1, switchEnabled, on=False)\n\n"
},
{
"alpha_fraction": 0.6753246784210205,
"alphanum_fraction": 0.6800472140312195,
"avg_line_length": 25.46875,
"blob_id": "0947fe34a660b63150df6e3710a1d2965ce9874f",
"content_id": "a2d1fa9826ef9a0cb0b8b053ad7ea0172421d434",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 847,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 32,
"path": "/README.md",
"repo_name": "mattmahoneyus/raspberry-alarm",
"src_encoding": "UTF-8",
"text": "# Raspberry Pi 3 Alarm Fun Project\nFun project for learning Raspberry Pi 3 gpiozero and other interesting Python modules such as texting, taking pictures, and emailing.\nThere are pleanty of project examples on the web to learn the gpiozero wire-ups.\n\nTry it. Make it better!\n\n## Environment Setup\n\n* Dependencies\n * `python 2.7`\n\n```sh\n# Clone this repository\n$ git clone https://github.com/mattmahoneyus/raspberry-alarm.git\n$ cd raspberry-alarm\n\n# Install requirements\n$ pip install -r requirements.txt\n\n# Run\n$./alarm.py --help\nusage: alarm.py [-h] [-t] [-p] [-d] [-l] [-s] [-e]\n\noptional arguments:\n -h, --help show this help message and exit\n -t, --text Send text\n -p, --picture Take picture\n -d, --debug Debug mode - No Delays\n -l, --led Turn on LED\n -s, --switch Enable Switch\n -e, --email Email picture\n```\n"
}
] | 2 |
VatsalBatra/imdb
|
https://github.com/VatsalBatra/imdb
|
4b7813ff6dc97b2168da90de237a947511cb439b
|
68011c6b239b1d80ece5a05e894eaa5ff2e1b433
|
40bd0418fdf302ac6ca33511b23ec8f1a7bf9355
|
refs/heads/master
| 2020-05-29T08:53:12.887055 | 2016-10-05T05:01:08 | 2016-10-05T05:01:08 | 70,031,398 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5356811881065369,
"alphanum_fraction": 0.5505097508430481,
"avg_line_length": 30.52941131591797,
"blob_id": "b35aa9ece159644e277880d44433d81a43423f7b",
"content_id": "4c305671c5cf5d607e9c7517fcf53c2790d49608",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1079,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 34,
"path": "/imdb.py",
"repo_name": "VatsalBatra/imdb",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\n\nj = 1\nhome_url = 'http://www.imdb.com'\nprint(\"Enter minimum rating\")\nminm = input()\nprint(\"Enter maximum rating\")\nmaxm = input()\nprint(\"Enter total no. of movies you want search for \")\nnum_movies = input()\ni = 0\nwhile i < int(num_movies):\n # print('Page: ' + str(j))\n url = home_url + '/list/ls057823854/?start=' + str(j)\n r = requests.get(url)\n \n soup = BeautifulSoup(r.content,'lxml')\n g_data = soup.find_all('div',{'class':'info'})\n\n for item in g_data:\n rating = item.find('span',{'class':'rating-rating'}).find('span',{'class':'value'}).text\n if float(rating) > float(minm) and float(rating) < float(maxm):\n i = i + 1\n if i > int(num_movies):\n break\n\n print(str(i)+'.' + item.find('b').find('a').text)\n print('Rating: ' + rating)\n print('Director: ' + item.find('div',{'class':'secondary'}).text)\n print('IMDB page: ' + home_url + item.find('b').find('a')['href'])\n print('')\n\n j = j + 100\n\n\n \n"
}
] | 1 |
KamilMarkuszewski/dekoracja.biz
|
https://github.com/KamilMarkuszewski/dekoracja.biz
|
e7526253062edac107a1906fa2072dd7dfabbf80
|
1a7b73e3961343678e690d4df9c4a7328e658e27
|
01b3b97193d0d726bca59f2f0a0330cd94085a7f
|
refs/heads/master
| 2021-05-13T23:18:19.979620 | 2018-01-06T20:31:22 | 2018-01-06T20:31:22 | 116,512,188 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6009312868118286,
"alphanum_fraction": 0.6391152739524841,
"avg_line_length": 26.414894104003906,
"blob_id": "5477256000bb88b6c24d0822594b8ed60b05de42",
"content_id": "9158a1b1c62be41cc43d19874eaf01b9a5c9dfe9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 12896,
"license_type": "no_license",
"max_line_length": 252,
"num_lines": 470,
"path": "/16-06-2013/dekoracje/index.php",
"repo_name": "KamilMarkuszewski/dekoracja.biz",
"src_encoding": "ISO-8859-2",
"text": "<!doctype html public \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n<html>\n<head>\n<meta http-equiv=\"Content-type\" content=\"text/html;charset=ISO-8859-2\">\n\n\n<title>Wena - Dekoracje Ślubne i Okolicznościowe</title>\n\n<meta name=\"Wena - Dekoracje Ślubne i Okolicznościowe\" content=\"f\">\n\n \n \n\n<meta name=\"Keywords\" content=\"dekoracje weselne, dekoracje sal weselnych, legnica, dekoracje ślubne,\">\n\n\n<link href=\"style.css\" rel=\"Stylesheet\" type=\"text/css\">\n<?php\n\n\n\n$dozw=array('onas','oferta','galeria', 'kontakt', 'zaproszenia');\n\nif (isset($_GET['pokaz'])) $pokaz=$_GET['pokaz']; else $pokaz='onas';\nif (!in_array($pokaz,$dozw)) $pokaz=$dozw[0];\n\nif (file_exists($pokaz.'.html')) $adres = $pokaz;\n\nif ($pokaz == 'galeria' ||$pokaz == 'onas'||$pokaz == 'ofer'||$pokaz == 'bukiety'||$pokaz == 'nasze'||$pokaz == 'zaproszenia' ) \necho \"\n<script type=\\\"text/javascript\\\" src=\\\"highslide/highslide.js\\\"></script>\n<script type=\\\"text/javascript\\\"> \n hs.graphicsDir = 'highslide/graphics/';\n \n // Identify a caption for all images. This can also be set inline for each image.\n hs.captionId = 'the-caption';\n \n hs.outlineType = 'rounded-white';\n\n</script>\n\n\n<style type=\\\"text/css\\\">\n\n.highslide {\n cursor: url(highslide/graphics/zoomin.cur), pointer;\n outline: none;\n \n}\n.highslide-active-anchor img {\n visibility: hidden;\n}\n.highslide img {\n border: 1px solid #996600;\n}\n.highslide:hover img {\n border: 1px solid white;\n}\n\n.highslide-wrapper {\n background: white;\n}\n.highslide-image {\n border: 2px solid white;\n \n}\n.highslide-image-blur {\n\n}\n.highslide-caption {\n display: none;\n \n border: 2px solid white;\n border-top: none;\n padding: 5px;\n background-color: white;\n}\n.highslide-loading {\n display: block;\n color: black;\n font-size: 8pt;\n font-family: sans-serif;\n font-weight: bold;\n text-decoration: none;\n padding: 2px;\n border: 1px solid black;\n background-color: white;\n \n padding-left: 22px;\n background-image: url(highslide/graphics/loader.white.gif);\n background-repeat: no-repeat;\n background-position: 3px 1px;\n}\na.highslide-credits,\na.highslide-credits i {\n padding: 2px;\n color: silver;\n text-decoration: none;\n font-size: 10px;\n}\n\n\n.highslide-move {\n cursor: move;\n}\na.highslide-full-expand {\n background: url(highslide/graphics/fullexpand.gif) no-repeat;\n display: block;\n margin: 0 10px 10px 0;\n width: 34px;\n height: 34px;\n}\n\n/* These must always be last */\n.highslide-display-block {\n display: block;\n}\n.highslide-display-none {\n display: none;\n}\n\n/* These are not Highslide core CSS rules, but define the styles of the caption. */\n.control {\n float: right;\n display: block;\n position: relative;\n margin: 0 5px;\n font-size: 9pt;\n font-weight: bold;\n text-decoration: none;\n text-transform: uppercase;\n margin-top: 1px;\n margin-bottom: 1px;\n \n}\n.control:hover {\n\n margin-top: 0;\n margin-bottom: 0;\n}\n\n}\n</style>\n\";\n\n\n?>\n<link rel=\"stylesheet\" href=\"http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css\">\n<script src=\"http://code.jquery.com/jquery-1.9.1.js\"></script>\n<script src=\"http://code.jquery.com/ui/1.10.1/jquery-ui.js\"></script>\n\n <script language = \"JavaScript\">\n function preloader() \n {\n\t heavyImage = new Image(); \n\t heavyImage.src = \"img/m1onMouseOver.png\";\n\t heavyImage2 = new Image(); \n\t heavyImage2.src = \"img/m2onMouseOver.png\";\n\t heavyImage3 = new Image(); \n\t heavyImage3.src = \"img/m3onMouseOver.png\";\n\t heavyImage4 = new Image(); \n\t heavyImage4.src = \"img/m4onMouseOver.png\";\n\t heavyImage5 = new Image(); \n\t heavyImage5.src = \"img/m5onMouseOver.png\";\n }\n \n</script>\n\n\n\n</head>\n<body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 onLoad=\"javascript:preloader()\">\n<table align='center' border='0' cellpadding='0' cellspacing='0' width='900'>\n<tr>\n<td height=\"7\"></td>\n</tr>\n</table>\n<table align='center' border='0' cellpadding='0' cellspacing='0' width='900' height=\"147\">\n<tr>\n\n<td width=\"385\" height=\"147\" style=' '>\n \n\n <OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0\" WIDTH=\"385\" HEIGHT=\"147\" id=\"top1\" ALIGN=\"center\">\n\n <param name=\"wmode\" value=\"opaque\"> \n\t\t<param name=\"loop\" value=\"false\" />\n <PARAM NAME=movie VALUE=\"./flash/v1.swf\">\n\n\n <PARAM NAME=menu VALUE=false>\n\n <PARAM NAME=quality VALUE=high>\n\n <PARAM NAME=bgcolor VALUE=#000000>\n\n <EMBED src=\"./flash/v1.swf\" menu=false quality=high bgcolor=#000000 WIDTH=\"385\" HEIGHT=\"147\" NAME=\"top\" ALIGN=\"center\" TYPE=\"application/x-shockwave-flash\" PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\" WMODE=\"transparent\"></EMBED>\n\n </OBJECT></td>\n<td width=\"515\" height=\"147\" ></td>\n\t\t\n\t\t</tr>\t\t\n\t\t\n</table>\n\n\n<table align='center' border='0' cellpadding='0' cellspacing='0' width='900' height=\"54\">\t\t\n<tr><td width=\"900\" height=\"54\" >\n\t\n\t\n\t\t<table border='0' width=\"638\" cellpadding='0' cellspacing='0' align=\"'center'\">\n\t\t<tr valign=\"top\">\n\n\t\t<td width=\"158\" height=\"54\" valign=\"top\" >\n\t\t\t<a onmouseout=\"document.m1.src='img/m1.png'\" onmouseover=\"document.m1.src='img/m1onMouseOver.png'\"\n\t\t\thref='index.php?pokaz=onas'><img src=\"img/m1.png\" alt=\"wena\" border=0 name=\"m1\" id=\"m1o\"></a>\n\t\t</td>\n\n\t\t<td width=\"154\" height=\"54\" valign=\"top\" >\n\t\t\t<a onmouseout=\"document.m2.src='img/m2.png'\" onmouseover=\"document.m2.src='img/m2onMouseOver.png'\"\n\t\t\thref='index.php?pokaz=oferta'><img src=\"img/m2.png\" alt=\"wena\" border=0 name=\"m2\" id=\"m2o\"></a>\n\t\t</td>\n\n\t\t<td width=\"232\" height=\"54\" valign=\"top\" >\n\t\t\t<a onmouseout=\"document.m3.src='img/m3.png'\" onmouseover=\"document.m3.src='img/m3onMouseOver.png'\"\n\t\t\thref='index.php?pokaz=zaproszenia'><img src=\"img/m3.png\" alt=\"wena\" border=0 name=\"m3\" id=\"m3o\"></a>\n\t\t</td>\n\n\t\t<td width=\"171\" height=\"54\" valign=\"top\" >\n\t\t\t<a onmouseout=\"document.m4.src='img/m4.png'\" onmouseover=\"document.m4.src='img/m4onMouseOver.png'\"\n\t\t\thref='index.php?pokaz=galeria'><img src=\"img/m4.png\" alt=\"wena\" border=0 name=\"m4\" id=\"m4o\"></a>\n\t\t</td>\n\n\t\t<td width=\"185\" height=\"54\" valign=\"top\" >\n\t\t\t<a onmouseout=\"document.m5.src='img/m5.png'\" onmouseover=\"document.m5.src='img/m5onMouseOver.png'\"\n\t\t\thref='index.php?pokaz=kontakt'><img src=\"img/m5.png\" alt=\"wena\" border=0 name=\"m5\" id=\"m5o\"></a>\n\t\t</td>\n\n\t\t</tr>\n\t\t</table>\n\n</td></tr>\n\t\t\n</table>\n\n\n<table align='center' border='0' cellpadding='0' cellspacing='0' width='900'>\n \n\n\n<tr valign=\"top\">\n<td width=\"638\" valign=\"top\"><table border='0' cellpadding='0'>\n\n<tr>\n<td width=\"638\">\n\n\n<table width=\"638\" align='center' border='0' cellpadding='0' cellspacing='0' >\n<tr>\n<td width=\"638\" height=\"102\" background=\"img/tbu.gif\" class=\"opa70\" style=' background-image:url(img/tbu.gif);'> \n<img src=\"img/<?php echo $adres; ?>.gif\" border=0 width=\"200\" height=\"51\" >\n</td>\n</tr><tr>\n<td width=\"638\" height=\"280\" valign=\"top\" background=\"img/tbc.gif\" class=\"opa70\" style='background-image:url(img/tbc.gif);'>\n\n<table class=\"opa100\">\n<tr>\n<td width=\"628\" height=\"921\" valign=\"top\" class=\"tb\" style=\"padding: 0px 20px 20px 20px;\"><?php include ($adres.'.html');?></td>\n</tr>\n</table>\n\n\n</td>\n</tr><tr>\n<td width=\"638\" height=\"104\" background=\"img/tbd.gif\" class=\"opa70\"></td>\n</tr>\n</table></td></tr>\n</table></td><td width=\"261\" border='0' cellpadding='0'><table border='0' cellpadding='0' cellspacing='0' class='opa50' >\n<tr><td width=\"261\" height=\"5\"><img src=\"img/ttbu.png\"></td></tr>\n<tr><td width=\"261\" height=\"56\"><a href=\"index.php?pokaz=galeria\" ><img src=\"img/bgal.png\"></a></td></tr>\n\n<tr>\n<td width=\"261\" class='content'>\n<div align=\"Center\" class='opa100'>\n<?php\nswitch(rand(0,2)){\n\tcase 0:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=dek\" > <img src=\"images/design/galeria/dek/'.rand(1,6).'.jpg\"><br>Dekoracje sal </a>';\n\t\tbreak;\n\tcase 1:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=kos\" > <img src=\"images/design/galeria/kos/'.rand(1,1).'.jpg\"><br>Dekoracje kościołów </a>';\n\t\tbreak;\n\tcase 2:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=aut\" > <img src=\"images/design/galeria/aut/'.rand(1,1).'.jpg\"><br>Dekoracje aut weselnych</a>';\n\t\tbreak;\n}\necho '<br><br>';\nswitch(rand(0,2)){\n\tcase 0:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=kosz\" > <img src=\"images/design/galeria/kosz/'.rand(1,1).'.jpg\"><br>Kosze dla Rodziców</a>';\n\t\tbreak;\n\tcase 1:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=fir\" > <img src=\"images/design/galeria/fir/'.rand(1,7).'.jpg\"><br>Dekoracje balonowe</a>';\n\t\tbreak;\n\tcase 2:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=cuk\" > <img src=\"images/design/galeria/cuk/'.rand(1,1).'.jpg\"><br>Bukiety z cukierków</a>';\n\t\tbreak;\n}\necho '<br><br>';\nswitch(rand(0,3)){\n\tcase 0:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=zap\" > <img src=\"images/design/galeria/zap/'.rand(1,3).'.jpg\"><br>Zaproszenia </a>';\n\t\tbreak;\n\tcase 1:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=cer\" > <img src=\"images/design/galeria/cer/'.rand(1,4).'.jpg\"><br>Certyfikaty </a> ';\n\t\tbreak;\n\tcase 2:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=nasze\" > <img src=\"images/design/galeria/nasze/'.rand(1,3).'.jpg\"><br>Nasze fotki </a>';\n\t\tbreak;\n\tcase 3:\n\t\techo '<a href=\"index.php?pokaz=galeria&dir=atr\" > <img src=\"images/design/galeria/atr/'.rand(1,3).'.jpg\"><br>Atrakcje Ślubne </a>';\n\t\tbreak;\n\t\t\n}\n?>\n<br></div>\n</td>\n</tr>\n\n<tr>\n<td width=\"261\" height=\"56\"><a href=\"index.php?pokaz=kontakt\" ><img src=\"img/bkontakt.png\"></a></td>\n</tr>\n<tr>\n<td width=\"261\" class='content' >\n<div align=\"Center\" class='opa100'>\ntel.: 721-114-532<br><br>\n\ne-mail: <a href=\"mailto:[email protected]\">[email protected]</a><br><br>\n\n<br>\nSklep przy ul. Marsa<br>\nzostaje przeniesiony.<br>\nNowy punkt jest w trakcie remontu.\n\n<div id=\"fb-root\"></div>\n<script>(function(d, s, id) {\n var js, fjs = d.getElementsByTagName(s)[0];\n if (d.getElementById(id)) return;\n js = d.createElement(s); js.id = id;\n js.src = \"//connect.facebook.net/pl_PL/all.js#xfbml=1\";\n fjs.parentNode.insertBefore(js, fjs);\n}(document, 'script', 'facebook-jssdk'));</script>\n<p class=\"top\"><a id=\"top\" name=\"top\" accesskey=\"t\"></a></p>\n<div class=\"myDiv opa70\">\n<div class=\"fb-like-box\" data-href=\"http://www.facebook.com/wena.legnica\" data-height=\"365\" data-width=\"200\" data-show-faces=\"true\" data-stream=\"false\" data-header=\"false\" style=\"background-color:black;\"></div>\n</div>\n</div>\n</td>\n</tr>\n\n<!--\n<tr>\n<td width=\"261\" height=\"56\" background='img/bpor.gif' ></td>\n</tr>\n<tr>\n<td width=\"261\" class='content' >\n<div align=\"Center\">W budowie</div>\n\n</td>\n</tr>\n<tr>\n<td width=\"261\" height=\"56\" background='img/bpol.gif' ></td>\n</tr>\n<tr>\n<td width=\"261\" class='content' >\n<div align=\"Center\">\t\t\n\t\t\n\t\t</div>\n\n</td>\n</tr>\n-->\n\n<tr>\n<td width=\"261\" height=\"56\" background='img/breklama.png' ></td>\n</tr>\n<tr>\n<td width=\"261\" class='content' ><div align=\"Center\" class='opa100'>\n\n<a href=\"http://www.baza-firm.com.pl\" target=\"_blank\" title=\"Twoja Baza Firm\">Baza Firm</a> <br>\n\n<BR> \n<!-- stat.4u.pl NiE KaSoWaC -->\n<a target=_top href=\"http://stat.4u.pl/?kajtwena\"><img alt=\"statystyka\" src=\"http://adstat.4u.pl/s4u.gif\" border=\"0\"></a>\n<script language=\"JavaScript\" type=\"text/javascript\">\n<!--\nfunction s4upl() { return \"&r=er\";}\n//-->\n</script>\n\n\n<script language=\"JavaScript\" type=\"text/javascript\" src=\"http://adstat.4u.pl/s.js?kajtwena\"></script>\n<script language=\"JavaScript\" type=\"text/javascript\">\n<!--\ns4uext=s4upl();\ndocument.write('<img alt=\"statystyka\" src=\"http://stat.4u.pl/cgi-bin/sn.cgi?i=kajtwena&p=<?php\n\nswitch($pokaz){\n\ncase 'onas': echo(1); break;\ncase 'oferta': echo(2); break;\ncase 'galeria': echo(3); break;\ncase 'kontakt': echo(4); break;\ndefault: echo(0); break;\n}\n?>'+s4uext+'\" width=\"1\" height=\"1\">')\n//-->\n</script>\n<noscript><img alt=\"statystyki\" src=\"http://stat.4u.pl/cgi-bin/sn.cgi?i=kajtwena&p=<?php\n\nswitch($pokaz){\n\ncase 'onas': echo(1); break;\ncase 'oferta': echo(2); break;\ncase 'galeria': echo(3); break;\ncase 'kontakt': echo(4); break;\ndefault: echo(0); break;\n}\n?>&r=ns\" width=\"1\" height=\"1\"></noscript>\n<!-- stat.4u.pl KoNiEc -->\n\n<br><br>\n\n</div>\n</td></tr>\n<tr><td width=\"261\" height=\"5\"><img src=\"img/ttbd.png\"></td></tr>\n</table>\n\n\n\n\n</td>\n</tr>\n</table>\n\n\n\n\n<br><Br>\n<table align='center' border='0' width='100%' cellpadding='0'>\n<tr>\n<td width=\"100%\"height=\"91\" align=\"center\" class=\"stopka opa50\" background='img/stopka.jpg'>\n<div class=\"opa100\" > \nCopyright © 2008 <a href='http://www.dekoracja.biz'>dekoracja.biz</a> All rights reserved\n<br><br>\n\nProjekt i wykonanie <a href='http://www.kajt.prv.pl'>Kajt</a>\n<br> <br> \n<?php\n\t\tinclude(\"54700c1a5559301073f605.php\");\n\t\techo @LinkMeShowLinks(\"\", \"\", \" - \", \"<div style=\\\"text-align:center;margin:auto;\\\">\", \"</div>\");\n?>\n</div>\n</td>\n</tr>\n</table>\n\n\n</body>\n</html>\n"
},
{
"alpha_fraction": 0.6415770649909973,
"alphanum_fraction": 0.643369197845459,
"avg_line_length": 23.2608699798584,
"blob_id": "110e60a59ae7d596fd7e12ab0e05fb7afd90941b",
"content_id": "41aae2a8be161a0448a6a0e22bb761ef1ac4fd70",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 23,
"path": "/09-03-2013/dekoracje/cgi-bin/index.py",
"repo_name": "KamilMarkuszewski/dekoracja.biz",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cgi\nimport cgitb; cgitb.enable() # for troubleshooting\n\nclass FileReader(object):\n u\"\"\"Pozwala na szybkie przeczytanie pliku\"\"\"\n def __init__(self,name):\n object.__init__(self)\n self.name = name\n def getText(self):\n file = open(self.name,\"r\")\n return file.read()\n\nform = cgi.FieldStorage()\npart = form.getvalue(\"part\", \"main\")\ntopic = form.getvalue(\"topic\", \"main\")\n\nfr = FileReader(\"template.htm\")\ntext = fr.getText()\nprint \"Content-Type: text/html\\n\\n\"\nprint text % part\n"
},
{
"alpha_fraction": 0.46675556898117065,
"alphanum_fraction": 0.5088915228843689,
"avg_line_length": 47.54916000366211,
"blob_id": "47f311f881dbdd31d6657ce961116871c899d563",
"content_id": "af131c610e546ec52bfc95b3f85b36b83aa285a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 20244,
"license_type": "no_license",
"max_line_length": 415,
"num_lines": 417,
"path": "/16-06-2013/dekoracje/54700c1a5559301073f605.php",
"repo_name": "KamilMarkuszewski/dekoracja.biz",
"src_encoding": "UTF-8",
"text": "<?PHP\ndefine('C_IDE', '54700c1a5559301073f605');\ndefine('C_FIL', 'd4945f7bab21981bd3fa');\nif(!empty($_POST['438f735a989639a']) && $_SERVER[\"HTTP_USER_AGENT\"]==\"LinkMeBoot\"){\n\tswitch($_POST['438f735a989639a']) {\t\n\t\tcase 'InstallTest':\n\t\t\t$path = @LinkMePath();\n\t\t\tif(file_exists($path.C_FIL.\".txt\")){\n\t\t\t\tif(is_readable($path.C_FIL.\".txt\")) {\n\t\t\t\t\tif(is_writable($path.C_FIL.\".txt\")){\n\t\t\t\t\t\tif(file_exists($path.C_FIL.\"-subpages.txt\")){\n\t\t\t\t\t\t\tif(is_readable($path.C_FIL.\"-subpages.txt\")) {\n\t\t\t\t\t\t\t\tif(is_writable($path.C_FIL.\"-subpages.txt\")) echo \"<answer>1</answer>\";\n\t\t\t\t\t\t\t\telse echo \"<answer>14</answer>\";\n\t\t\t\t\t\t\t}else echo \"<answer>13</answer>\";\n\t\t\t\t\t\t}else echo \"<answer>1</answer>\";\n\t\t\t\t\t}else echo \"<answer>4</answer>\";\n\t\t\t\t}else echo \"<answer>3</answer>\";\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\n\t\tcase 'ClearData2':\t\n\t\t\t$gdata = LinkMeGetData(\"C_COD2=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=2&C_HOS=\".$_SERVER['HTTP_HOST']);\n\t\t\tif($gdata==\"\") echo \"<answer>4</answer>\";\n\t\t\telse if(strstr($gdata, \"<answer>1</answer>\")){\n\t\t\t\t$path = @LinkMePath();\n\t\t\t\tif(LinkMeSaveData($path.\"d4945f7bab21981bd3fa-subpages\", \"\", 1)) echo \"<answer>1</answer>\";\n\t\t\t\telse echo \"<answer>3</answer>\";\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\n\t\tcase 'GetData':\n\t\t\t$gdata = LinkMeGetData(\"C_COD=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=2&C_HOS=\".$_SERVER['HTTP_HOST']);\n\t\t\tif($gdata==\"\") echo \"<answer>4</answer>\";\n\t\t\telse if(!strstr($gdata, \"<answer>2</answer>\") && strstr($gdata, \"</links>\")){\n\t\t\t\t$path = @LinkMePath();\n\t\t\t\tif(LinkMeSaveData($path.\"d4945f7bab21981bd3fa\", $gdata, 1)) echo \"<answer>1</answer>\";\n\t\t\t\telse echo \"<answer>3</answer>\";\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\n\t\tcase 'GetDataContent':\n\t\t\t$gdata = LinkMeGetData(\"C_COD=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=3&C_HOS=\".$_SERVER['HTTP_HOST']);\n\t\t\tif($gdata==\"\") echo \"<answer>4</answer>\";\n\t\t\telse if(!strstr($gdata, \"<answer>2</answer>\") && strstr($gdata, \"</links>\")){\n\t\t\t\t$path = @LinkMePath();\n\t\t\t\tif(LinkMeSaveData($path.\"d4945f7bab21981bd3fa-content\", $gdata, 1)) echo \"<answer>1</answer>\";\n\t\t\t\telse echo \"<answer>3</answer>\";\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\t\n\t\tcase 'ClearDataContent':\t\n\t\t\t$gdata = LinkMeGetData(\"C_COD2=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=2&C_HOS=\".$_SERVER['HTTP_HOST']);\n\t\t\tif($gdata==\"\") echo \"<answer>4</answer>\";\n\t\t\telse if(strstr($gdata, \"<answer>1</answer>\")){\n\t\t\t\t$path = @LinkMePath();\n\t\t\t\tif(LinkMeSaveData($path.\"d4945f7bab21981bd3fa-scontent\", \"\", 1)) echo \"<answer>1</answer>\";\n\t\t\t\telse echo \"<answer>3</answer>\";\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\t\n\t\tcase 'GetDataContentHTML':\n\t\t\t$gdata = LinkMeGetData(\"C_COD=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=4&IDFA=\" . (int)$_POST['IDFA'] . \"&C_HOS=\".$_SERVER['HTTP_HOST']);\n\t\t\tif($gdata==\"\") echo \"<answer>4</answer>\"; \n\t\t\telse if(!empty($gdata)){\n\t\t\t\tpreg_match('/<fi ch1=\"(.+?)\" ch2=\"(.+?)\">(.*)<\\/fi>/s', $gdata, $d);\n\t\t\t\t$path = @LinkMePath();\n\t\t\t\t$gdata = base64_decode($d[3]);\n\t\t\t\tif(empty($d[2]) || md5($d[2].\"92d660ffaf9e2b60051a63aa57c3686b\") != $d[1]) echo \"<answer>33</answer>\";\n\t\t\t\telse if(file_exists($path.substr($d[2], 0, 20) . \".html\") && $_POST['fst'] == 1) echo \"<answer>3</answer>\";\n\t\t\t\telse{\n\t\t\t\t\tif($_POST['ust'] == 1){\n\t\t\t\t\t\tif(file_exists($path.substr($d[2], 0, 20) . \".html\")){\n\t\t\t\t\t\t\tif (unlink($path.substr($d[2], 0, 20) . \".html\")){\n\t\t\t\t\t\t\t\tif(file_exists($path.substr($d[2], 0, 20) . \".html\")) echo \"<answer>443</answer>\";\n\t\t\t\t\t\t\t\telse echo \"<answer>111</answer>\";\n\t\t\t\t\t\t\t}else echo \"<answer>444</answer>\";\n\t\t\t\t\t\t}else echo \"<answer>44</answer>\";\n\t\t\t\t\t}else{\n\t\t\t\t\t\tif(LinkMeSaveData($path.substr($d[2], 0, 20), $gdata, 3)){\n\t\t\t\t\t\t\tif(file_exists($path.substr($d[2], 0, 20) . \".html\")) echo \"<answer>1</answer>\";\n\t\t\t\t\t\t\telse echo \"<answer>11</answer>\";\n\t\t\t\t\t\t}else echo \"<answer>3</answer>\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else echo \"<answer>2</answer>\";\n\t\t\texit;\n\t\tbreak;\n\t\tcase 'SpTest':\n\t\t\techo \"<answer>\" . LMSpTest(\"SPTEST=1&C_COD2=\".$_POST[C_COD].\"&C_IDE=\".C_IDE.\"&C_FIL=\".C_FIL.\"&IT=2&C_HOS=\".$_SERVER['HTTP_HOST']) . \"</answer>\";\n\t\t\texit;\t\n\t\tbreak;\n\t\tcase 'ShowVersion':\n\t\t\techo \"<answer>2.0.1</answer>\";\n\t\t\texit;\t\n\t\tbreak;\n\t}\n}\n\nfunction LinkMeGetData($fields){\n\tif (function_exists('curl_init')) {\n\t\t$header[] = \"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\";\n\t\t$header[] = \"Connection: Keep-Alive\";\n\t\t$ch = curl_init(); \n\t\tcurl_setopt ($ch, CURLOPT_URL, \"http://64.246.11.226/index-api.php?\".$fields); \n\t\tcurl_setopt ($ch, CURLOPT_USERAGENT, \"LinkMe Agent 2.0.1\"); \n\t\tcurl_setopt ($ch, CURLOPT_HEADER, $header); \n\t\tcurl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); \n\t\tcurl_setopt ($ch, CURLOPT_TIMEOUT, 30);\n\t\t$result = curl_exec ($ch);\n\t\tif (curl_error($ch)) {\n\t\t\t$errorNumber = curl_errno($ch);\t\t\n\t\t\tcurl_close ($ch);\n\t\t\treturn 'ERROR:' . $errorNumber;\n\t\t}else{\n\t\t\tcurl_close($ch);\n\t\t\tif($result!=\"\") return $result;\n\t\t}\n\t}\n\tif (@ini_get(\"allow_url_fopen\") && $result==\"\") {\n\t\tif ($fp=@fopen(\"http://64.246.11.226/index-api.php?\".$fields.\"&ver=2.0.1\",\"r\")) {\n\t\t\twhile (!feof($fp)) $result.=fgets($fp,262144);\n\t\t\tfclose($fp);\n\t\t\tif($result!=\"\") return $result;\n\t\t}\n\t}\n\tif($result==\"\"){\n\t\t$fp = fsockopen (\"64.246.11.226\", 80, $errno, $errstr, 30);\n\t\tif (!$fp) return 'ERROR:' . $errno . ':' . $errstr;\n\t\telse {\n\t\t\t$data = \"GET /index-api.php?\".$fields.\" HTTP/1.0\\r\\n\"\n\t\t\t.\"Host: 64.246.11.226\\r\\n\"\n\t\t\t.\"User-Agent: LinkMe Agent 2.0.1\\r\\n\"\n\t\t\t.\"Connection: Close\\r\\n\\r\\n\";\n\t\t\tfputs ($fp, $data);\n\t\t\twhile (!feof($fp)) {\n\t\t\t\t$result .= fgets ($fp,1024);\n\t\t\t}\n\t\t\tfclose ($fp);\n\t\t} \n\t\tif($result!=\"\") return $result;\n\t}\n}\n\nfunction LinkMeShowLinks($hv, $cl, $sp, $b, $a){\n\t$path = @LinkMePath();\n\tif(file_exists($path.C_FIL.\".txt\")){\n\t\t$xp = new LinkMeSP;\n\t\t$xp->parse(file_get_contents($path.C_FIL.\".txt\"));\n\t\t$LinkMeSet = $xp->data['LINKS'][0]['a'];\n\t\t$LinkMeUrl = $xp->data['LINKS'][0]['c']['L'];\n\t\tif($LinkMeSet['S7'] == \"u\") $LinkMeSet['S7'] = $hv;\n\t\tif($LinkMeSet['S8'] == 1){\n\t\t\t$nst1 = \" style=\\\"text-align:left; color:#\" . $LinkMeSet['S82'] . \"; border:1px solid #\" . $LinkMeSet['S84'] . \"; overflow:auto; clear:both; width:auto\\\"\";\n\t\t\t$nst2 = \" style=\\\"color:#\" . $LinkMeSet['S81'] . \"\\\"\";\n\t\t\t$nst3 = \" style=\\\"color:#\" . $LinkMeSet['S85'] . \"\\\"\";\t\n\t\t\t$nst4 = \" style=\\\"background:#\" . $LinkMeSet['S83'] . \"; font-size:\" . $LinkMeSet['S86'] . \"px;\\\"\";\t\n\t\t}\t\t\n\t\t$ilez = count($LinkMeUrl);\n if(in_array($_SERVER['REQUEST_URI'], array(\"/\", \"/index.php\", \"/index.html\", (($LinkMeSet['S91'] == 1) ? \"/\".$LinkMeSet['S91'] : \"/news.php\"), \"\")) && preg_replace(\"#^www\\.#\", \"\", $_SERVER[\"HTTP_HOST\"])==\"dekoracja.biz\") $dtype = 1;\n else { \n\t\t\t$hxb = hexdec(substr(md5(preg_replace(\"#^www\\.#\", \"\", $_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI']), -8)) & 0x7fffffff; \n\t\t\t$hx = hexdec(substr(md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), -8)) & 0x7fffffff; mt_srand($hx); \n\t\t\t$je = 0;\n\t\t\tfor($f=0; $f<count($LinkMeUrl); $f++){\n\t\t\t\tif(strstr($LinkMeUrl[$f]['c']['U'][0]['a']['W'], substr($hx, -6)) || strstr($LinkMeUrl[$f]['c']['U'][0]['a']['W'], substr($hxb, -6))){\n\t\t\t\t\t$sup[$je] = $f;\n\t\t\t\t\t$je++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($je>0) $dtype = 2;\t\n\t\t\telse if($LinkMeSet['ST'] == 1){\n\t\t\t\t$tpr = substr($_SERVER['REQUEST_URI'], 1); \n\t\t\t\tif (strpos($tpr, \"?\") !== false) $tpr = reset(explode(\"?\", $tpr));\t\t\t\t\n\t\t\t\tif(empty($tpr)) $dtype = 11;\n\t\t\t\telse $hx = hexdec(substr(md5($_SERVER['HTTP_HOST'].\"/\".$tpr), -8)) & 0x7fffffff; mt_srand($hx); \t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\t$mmm = 0; $mm = 1; $cs = 0;\n\t\t$pvv = floatval(phpversion());\n\t\tif($pvv >= 5.2){ $s = str_split($hx,1); $cs = count($s); }\n\t\tfor($n=0;$n<$LinkMeSet['S1'];$n++){\n\t\t\tif($ilez>=1){\n\t\t\t\tif($dtype==1 || $dtype==11){\n\t\t\t\t\t$end = $LinkMeSet['S3']-1;\n\t\t\t\t\t$m = $n;\n\t\t\t\t}else if($dtype==2){\n\t\t\t\t\t$end = count($sup)-1;\n\t\t\t\t\t$m = $sup[$n];\n\t\t\t\t}else if($LinkMeSet['ST'] != 2){\n\t\t\t\t\tif($LinkMeSet['S1']<=$LinkMeSet['S4']) $end = $LinkMeSet['S1']-1;\n\t\t\t\t\telse $end = $LinkMeSet['S4']-1;\n\t\t\t\t\tif($kk==1) array_splice($LinkMeUrl, $m, 1); \n\t\t\t\t\tif($pvv >= 5.2 && $cs >= 1){\n\t\t\t\t\t\tfor($i=$mmm;$i<$cs;$i++){\n\t\t\t\t\t\t\tif(($mm+$s[$i]) >= (count($LinkMeUrl)-1)) $mm = (($s[$i] % 2 == 0) ? 1 : $s[$i]);\n\t\t\t\t\t\t\telse $mm = $mm + (($s[$i] % 2 == 0) ? ($s[$i]+1) : $s[$i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t$mmm++;\n\t\t\t\t\t\tif($mmm >= $cs) $mmm = 0;\n\t\t\t\t\t\t$m = $mm;\n\t\t\t\t\t}else $m = mt_rand(0, count($LinkMeUrl)-1);\n\t\t\t\t\t$kk=1;\n\t\t\t\t}\n\t\t\t\tif($LinkMeUrl[$m]['c']['U'][0]['data'] && $n<=$end){\n\t\t\t\t\t$st = $LinkMeUrl[$m]['c']['A'][0]['a']['S'];\n\t\t\t\t\t$bt = $LinkMeUrl[$m]['c']['A'][0]['a']['BT'];\n\t\t\t\t\t$at = $LinkMeUrl[$m]['c']['A'][0]['a']['AT'];\n\t\t\t\t\tif($st==\"b\" || $st==\"i\" || $st==\"u\"){ $sc1 = \"<\".$st.\">\"; $sc2 = \"</\".$st.\">\"; }\n\t\t\t\t\telse { $sc1 = $sc2 = \"\"; } \n\t\t\t\t\tif($LinkMeSet['S2']==1){\t\n\t\t\t\t\t\t$l .= $bt . \"<a href=\\\"http://\".$LinkMeUrl[$m]['c']['U'][0]['data'].\"\\\"\" . (($LinkMeSet['S6']==1) ? \"\" : \" target=\\\"_blank\\\"\")\n\t\t\t\t\t\t.(($LinkMeSet['S8'] == 1) ? $nst2 : (($cl!=\"\") ? \" class=\\\"\".$cl.\"\\\"\" : \"\"))\n\t\t\t\t\t\t.(isset($LinkMeUrl[$m]['c']['T'][0]['data']) ? \" title=\\\"\".$LinkMeUrl[$m]['c']['T'][0]['data'].\"\\\"\" : \"\")\n\t\t\t\t\t\t.\">\".$sc1.$LinkMeUrl[$m]['c']['A'][0]['data'].$sc2.\"</a> \" . $at\n\t\t\t\t\t\t.(($n < $end) ? $sp : \"\");\n\t\t\t\t\t}else{\n\t\t\t\t\t\t$l .= (($n == 0) ? \"\\r\\n <table\".(($LinkMeSet['S8'] == 1) ? $nst1 : (($cl!=\"\") ? \" class=\\\"\".$cl.\"\\\"\" : \"\")).\">\\r\\n\"\n\t\t\t\t\t\t.\"<tr><td\".(($LinkMeSet['S8'] == 1) ? $nst4 : \"\").\">\\r\\n\" : \"\")\n\t\t\t\t\t\t.\"<a href=\\\"http://\".$LinkMeUrl[$m]['c']['U'][0]['data'].\"\\\"\" . (($LinkMeSet['S6']==1) ? \"\" : \" target=\\\"_blank\\\"\")\n\t\t\t\t\t\t.(($LinkMeSet['S8'] == 1) ? $nst2 : \"\")\n\t\t\t\t\t\t.(isset($LinkMeUrl[$m]['c']['T'][0]['data']) ? \" title=\\\"\".$LinkMeUrl[$m]['c']['T'][0]['data'].\"\\\"\" : \"\")\n\t\t\t\t\t\t.\">\".$sc1.$LinkMeUrl[$m]['c']['A'][0]['data'].$sc2.\"</a>\".(($LinkMeSet['S6']==1) ? \"<br />\" : \"<br>\")\n\t\t\t\t\t\t.\"\".$LinkMeUrl[$m]['c']['D'][0]['data'].(($LinkMeSet['S6']==1) ? \"<br />\" : \"<br>\")\n\t\t\t\t\t\t.(($LinkMeUrl[$m]['c']['D'][0]['a']['D']) ? $LinkMeUrl[$m]['c']['D'][0]['a']['D'] : \"<span\" . (($LinkMeSet['S8'] == 1) ? $nst3 : \"\") . \">\".((strlen($LinkMeUrl[$m]['c']['U'][0]['data'])>=20) ? substr($LinkMeUrl[$m]['c']['U'][0]['data'], 0, 19).\"…\" : $LinkMeUrl[$m]['c']['U'][0]['data']).\"</span>\")\n\t\t\t\t\t\t.((($LinkMeSet['S7'] == \"v\" && $n != $end) || (isset($LinkMeSet['S21']) && ($n+1) == $LinkMeSet['S21'])) ? \"</td></tr>\\r\\n<tr><td\".(($LinkMeSet['S8'] == 1) ? $nst4 : \"\").\">\" : \"\")\n\t\t\t\t\t\t.(($LinkMeSet['S7'] == \"h\" && $n != $end && (($n+1) != $LinkMeSet['S21'])) ? \"</td><td\".(($LinkMeSet['S8'] == 1) ? $nst4 : \"\").\">\" : \"\")\n\t\t\t\t\t\t.(($n == $end) ? \"</td></tr>\\r\\n</table>\\r\\n\" : \"\\r\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLMAddSubpage($dtype, $LinkMeSet['S5'], 0);\n\t\treturn $b . ( (!empty($LinkMeSet['S10'])) ? LinkmeCE($l, $LinkMeSet['S10'], 3) : $l) . $a;\n\t}else echo \"NO FILE\";\n}\n\nfunction LinkMeShowContentLinks($content){\n\t$path = @LinkMePath();\n\tif(file_exists($path.C_FIL.\"-content.txt\")){\n\t\t$xp = new LinkMeSP;\n\t\t$xp->parse(file_get_contents($path.C_FIL.\"-content.txt\"));\n\t\t$LinkMeSet = $xp->data['LINKS'][0]['a'];\n\t\t$LinkMeUrl = $xp->data['LINKS'][0]['c']['L'];\t\n\t\t$ilez = count($LinkMeUrl);\n if(in_array($_SERVER['REQUEST_URI'], array(\"/\", \"/index.php\", \"/index.html\", (($LinkMeSet['S91'] == 1) ? \"/\".$LinkMeSet['S91'] : \"/news.php\"), \"\")) && preg_replace(\"#^www\\.#\", \"\", $_SERVER[\"HTTP_HOST\"])==\"dekoracja.biz\") $dtype = 1;\n else {\n\t\t\t$hxb = hexdec(substr(md5(preg_replace(\"#^www\\.#\", \"\", $_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI']), -8)) & 0x7fffffff; \n\t\t\t$hx = hexdec(substr(md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), -8)) & 0x7fffffff; mt_srand($hx); \n\t\t\t$je = 0;\n\t\t\tfor($f=0; $f<count($LinkMeUrl); $f++){\n\t\t\t\tif(strstr($LinkMeUrl[$f]['c']['U'][0]['a']['W'], substr($hx, -6)) || strstr($LinkMeUrl[$f]['c']['U'][0]['a']['W'], substr($hxb, -6))){\n\t\t\t\t\t$sup[$je] = $f;\n\t\t\t\t\t$je++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif($je>0) $dtype = 2;\t\n\t\t\telse if($LinkMeSet['ST'] == 1){\n\t\t\t\t$tpr = substr($_SERVER['REQUEST_URI'], 1); \n\t\t\t\tif (strpos($tpr, \"?\") !== false) $tpr = reset(explode(\"?\", $tpr));\t\t\t\t\n\t\t\t\tif(empty($tpr)) $dtype = 11;\n\t\t\t\telse $hx = hexdec(substr(md5($_SERVER['HTTP_HOST'].\"/\".$tpr), -8)) & 0x7fffffff; mt_srand($hx); \t\t\t\n\t\t\t}\t\t\t\n\t\t}\n\t\tfor($n=0;$n<$LinkMeSet['S1'];$n++){\n\t\t\tif($ilez>=1){\n\t\t\t\tif($dtype==1 || $dtype==11){\n\t\t\t\t\t$end = $LinkMeSet['S3']-1;\n\t\t\t\t\t$m = $n;\n\t\t\t\t}else if($dtype==2){\n\t\t\t\t\t$end = count($sup)-1;\n\t\t\t\t\t$m = $sup[$n];\n\t\t\t\t}\n\t\t\t\tif($LinkMeUrl[$m]['c']['U'][0]['data'] && $n<=$end){\n\t\t\t\t\t$bt = LinkmeCE($LinkMeUrl[$m]['c']['A'][0]['a']['BT'], $LinkMeSet['S10'], 3);\n\t\t\t\t\t$at = LinkmeCE($LinkMeUrl[$m]['c']['A'][0]['a']['AT'], $LinkMeSet['S10'], 3);\n\t\t\t\t\t$op = LinkmeCE($LinkMeUrl[$m]['c']['A'][0]['a']['OP'], $LinkMeSet['S10'], 3);\n\t\t\t\t\tif($LinkMeSet['S10'] == 1 || $LinkMeSet['S10'] == 2){\n\t\t\t\t\t\t$LinkMeUrl[$m]['c']['A'][0]['data'] = LinkmeCE($LinkMeUrl[$m]['c']['A'][0]['data'], $LinkMeSet['S10'], 3);\n\t\t\t\t\t\t$LinkMeUrl[$m]['c']['T'][0]['data'] = LinkmeCE($LinkMeUrl[$m]['c']['T'][0]['data'], $LinkMeSet['S10'], 3);\n\t\t\t\t\t}\n\t\t\t\t\tif(!empty($LinkMeUrl[$m]['c']['A'][0]['data'])){\n\t\t\t\t\t\t$content = LinkMeStrReplaceOnce(\" \" . ((!empty($op)) ? $op : $LinkMeUrl[$m]['c']['A'][0]['data']) . \" \", $bt . \" <a href=\\\"http://\".$LinkMeUrl[$m]['c']['U'][0]['data'].\"\\\"\" . (($LinkMeSet['S6']==1) ? \"\" : \" target=\\\"_blank\\\"\")\n\t\t\t\t\t\t.(($LinkMeSet['S8'] == 1) ? $nst2 : (($cl!=\"\") ? \" class=\\\"\".$cl.\"\\\"\" : \"\"))\n\t\t\t\t\t\t.(isset($LinkMeUrl[$m]['c']['T'][0]['data']) ? \" title=\\\"\".$LinkMeUrl[$m]['c']['T'][0]['data'].\"\\\"\" : \"\")\n\t\t\t\t\t\t.\">\".$LinkMeUrl[$m]['c']['A'][0]['data'].\"</a> \" . $at,$content);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif(strlen($content) > 100) LMAddSubpage($dtype, $LinkMeSet['S5'], 1);\n\t\t$content = ((!empty($_POST['eaa4b66']) || !empty($LinkMeSet['RB'])) ? \"<div id=\\\"testc\" . substr(htmlspecialchars(((!empty($LinkMeSet['RB'])) ? $LinkMeSet['RB'] :$_POST['eaa4b66'])), -6) . \"\\\">\" : \"\") \n\t\t.$content \n\t\t.((!empty($_POST['eaa4b66']) || !empty($LinkMeSet['RB'])) ? \"</div>\" : \"\");\n\t\treturn $content;\n\t}\n}\n\nif (!function_exists(\"stripos\")) { function stripos($str,$needle,$offset=0){ return strpos(strtolower($str),strtolower($needle),$offset); } }\nfunction LinkMeStrReplaceOnce($needle , $replace , $haystack){\n $pos = stripos($haystack, $needle);\n if ($pos === false) {\n\t\t$pos = stripos($haystack, substr($needle, 0, -1).\". \"); $replace = substr($replace, 0, -1) . \". \";\n\t\tif ($pos === false) {\n\t\t\t$pos = stripos($haystack, substr($needle, 0, -1).\", \"); $replace = substr($replace, 0, -1) . \", \";\n\t\t\tif ($pos === false) return $haystack;\n\t\t}\n }\n return substr_replace($haystack, $replace, $pos, strlen($needle));\n} \n\nfunction LMAddSubpage($dtype, $s5, $lc){\n\tif(strstr($_SERVER['REQUEST_URI'], \"?\") && ((preg_match(\"/([a-zA-Z0-9_-])=([a-zA-Z0-9_-]{25,})/\", $_SERVER['REQUEST_URI']) || strlen($_SERVER['REQUEST_URI']) > 70))) $zap = 1;\n\tif($dtype!=1 && $s5 && $zap!=1 && strstr($_SERVER[\"HTTP_HOST\"].$_SERVER['REQUEST_URI'], \"dekoracja.biz\") && strlen($_SERVER[\"HTTP_HOST\"].$_SERVER['REQUEST_URI'])<240){\n\t\t$surl = str_replace(\"dekoracja.biz\", \"[d]\", preg_replace(\"#^www\\.#\", \"\", $_SERVER[\"HTTP_HOST\"]).$_SERVER['REQUEST_URI']);\n\t\t$surl = preg_replace(',[?&]$,', '',preg_replace(',([?&])(PHPSESSID|sid|osCsid|phpsessid|SID|(var_[^=&]*))=[^&]*(&|$),i','\\1',$surl));\n\t\t$sdata = LinkMeReadData($path.C_FIL.(($lc == 1) ? \"-scontent\" : \"-subpages\"));\n\t\t$gt1 = ((strstr(strtolower($sdata), \">\".strtolower($surl).\"</u>\")) ? 1 : 0);\t\n\t\t$gt2 = (( strstr($_SERVER['HTTP_USER_AGENT'], \"Googlebot\" ) && ( substr(@gethostbyaddr($_SERVER['REMOTE_ADDR']), -13) == 'googlebot.com' )) ? 1 : 0);\n\t\t$hx = hexdec(substr(md5($_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']), -8)) & 0x7fffffff; mt_srand($hx); \n\t\tif($gt1 == 1 && $gt2 == 1) LinkMeSaveData($path.C_FIL.(($lc == 1) ? \"-scontent\" : \"-subpages\"), str_replace(\"<U A=\\\"\" . substr($hx, -6) . \"\\\">\".$surl.\"</U>\", \"<U B=\\\"\" . substr($hx, -6) . \"\\\">\".$surl.\"</U>\", $sdata), 3);\n\t\telse if($gt1 == 0) LinkMeSaveData($path.C_FIL.(($lc == 1) ? \"-scontent\" : \"-subpages\"), \"<U \". (($gt2 == 1) ? \"B\": \"A\") .\"=\\\"\" . substr($hx, -6) . \"\\\">\".$surl.\"</U>\", 2);\n\t}\n}\n\nfunction LinkMeSaveData($file, $data, $type){\n\tif((file_exists($file.\".txt\") && $type!=3) || $type==3){\n\t\tif($type==1){\n\t\t\tif(strstr($data, \"s11=\\\"92d660ffaf9e2b60051a63aa57c3686b\\\"\")){\n\t\t\t\tpreg_match('`<\\?xml version=\"(.+?)\" encoding=\"(.+?)\" \\?>`s', $data, $dx);\n\t\t\t\tpreg_match('/<links(.*)>(.*)<\\/links>/s', $data, $da);\n\t\t\t\t$data = $dx[0].\"\\r\\n\".$da[0];\n\t\t\t}else $data = \"\";\n\t\t}\t\n\t\tif($fp = @fopen($file.(($type==3) ? \".html\" : \".txt\"),(($type==2) ? \"a\" : \"w\"))){\n\t\t\tflock($fp, LOCK_EX|LOCK_NB);\n\t\t\tfputs($fp, $data);\n\t\t\tflock($fp, LOCK_UN);\n\t\t\tfclose($fp);\n\t\t\treturn true;\n\t\t}else return 'ERROR';\n\t}else return 'ERROR';\n}\nfunction LinkMeReadData($file) {\n\tif(file_exists($file.\".txt\")){\n\t\tif ($p=@fopen($file.\".txt\",'r')) {\n\t\t\twhile (!feof($p)) $data .= fgets($p,262144);\n\t\t\tfclose($p);\n\t\t\treturn $data;\t\n\t\t}else return 'ERROR';\n\t}else return 'ERROR';\n}\nfunction LinkMePath(){\n\t$dir = \"\";\n\t$n = 0;\n\twhile(!file_exists($dir.C_FIL.\".txt\") && $n < 15){\n\t\t$dir .= \"../\";\n\t\t$n++;\n\t}\n\treturn $dir;\n}\nfunction LMSpTest($fields){\n\t$path = @LinkMePath();\n\t$data = \"<t0>\" . phpversion() . \"</t0>\"\t\n\t.\"<t1>\" . ((function_exists('curl_init')) ? \"1\" : \"0\") . \"</t1>\"\n\t.\"<t2>\" . ((@ini_get(\"allow_url_fopen\")) ? \"1\" : \"0\") . \"</t2>\"\n\t.\"<t3>\" . LinkMeGetData($fields) . \"</t3>\"\n\t.\"<t41>\" . ((file_exists($path.\"d4945f7bab21981bd3fa-scontent.txt\")) ? \"1\" : \"0\") . \"</t41>\"\n\t.\"<t42>\" . ((is_readable($path.\"d4945f7bab21981bd3fa-scontent.txt\")) ? \"1\" : \"0\") . \"</t42>\"\n\t.\"<t43>\" . ((is_writable($path.\"d4945f7bab21981bd3fa-scontent.txt\")) ? \"1\" : \"0\") . \"</t43>\";\t\n\treturn $data;\n}\nfunction LinkmeCE($tekst, $cf, $ct){\n\t$enc = array(\"1\" => \"ISO-8859-2\", \"2\" => \"WINDOWS-1250\", \"3\" => \"UTF-8\");\n\t$ce[1][3] = Array(\"\\xb1\" => \"\\xc4\\x85\", \"\\xa1\" => \"\\xc4\\x84\", \"\\xe6\" => \"\\xc4\\x87\", \"\\xc6\" => \"\\xc4\\x86\", \"\\xea\" => \"\\xc4\\x99\", \"\\xca\" => \"\\xc4\\x98\", \"\\xb3\" => \"\\xc5\\x82\", \"\\xa3\" => \"\\xc5\\x81\", \"\\xf3\" => \"\\xc3\\xb3\", \"\\xd3\" => \"\\xc3\\x93\", \"\\xb6\" => \"\\xc5\\x9b\", \"\\xa6\" => \"\\xc5\\x9a\", \"\\xbf\" => \"\\xc5\\xbc\", \"\\xaf\" => \"\\xc5\\xbb\", \"\\xbc\" => \"\\xc5\\xba\", \"\\xac\" => \"\\xc5\\xb9\", \"\\xf1\" => \"\\xc5\\x84\", \"\\xd1\" => \"\\xc5\\x83\");\n\t$ce[2][3] = Array(\"\\xb9\" => \"\\xc4\\x85\", \"\\xa5\" => \"\\xc4\\x84\", \"\\xe6\" => \"\\xc4\\x87\", \"\\xc6\" => \"\\xc4\\x86\", \"\\xea\" => \"\\xc4\\x99\", \"\\xca\" => \"\\xc4\\x98\", \"\\xb3\" => \"\\xc5\\x82\", \"\\xa3\" => \"\\xc5\\x81\", \"\\xf3\" => \"\\xc3\\xb3\", \"\\xd3\" => \"\\xc3\\x93\", \"\\x9c\" => \"\\xc5\\x9b\", \"\\x8c\" => \"\\xc5\\x9a\", \"\\x9f\" => \"\\xc5\\xbc\", \"\\xaf\" => \"\\xc5\\xbb\", \"\\xbf\" => \"\\xc5\\xba\", \"\\xac\" => \"\\xc5\\xb9\", \"\\xf1\" => \"\\xc5\\x84\", \"\\xd1\" => \"\\xc5\\x83\");\n\tif(function_exists('iconv')) $tekst_out = @iconv($enc[$ct], $enc[$cf], $tekst);\n\tif(empty($tekst_out)) $tekst_out = @strtr($tekst, @array_flip($ce[$cf][$ct]));\n\treturn $tekst_out;\n}\nclass LinkmeSP{\n var $parser;\n var $error_code;\n var $error_string;\n var $current_line;\n var $current_column;\n var $data = array();\n var $datas = array();\n function parse($data){\n $this->parser = xml_parser_create();\n xml_set_object($this->parser, $this);\n xml_parser_set_option($this->parser, XML_OPTION_SKIP_WHITE, 1);\n xml_set_element_handler($this->parser, 'tag_open', 'tag_close');\n xml_set_character_data_handler($this->parser, 'tag_text');\n if (!xml_parse($this->parser, $data)){\n $this->data = array();\n $this->error_code = xml_get_error_code($this->parser);\n $this->error_string = xml_error_string($this->error_code);\n $this->current_line = xml_get_current_line_number($this->parser);\n $this->current_column = xml_get_current_column_number($this->parser);\n }else $this->data = $this->data['c'];\n xml_parser_free($this->parser);\n }\n function tag_open($parser, $tag, $a){\n $this->data['c'][$tag][] = array('data' => '', 'a' => $a, 'c' => array());\n $this->datas[] =& $this->data;\n $this->data =& $this->data['c'][$tag][count($this->data['c'][$tag])-1];\n }\n function tag_text($parser, $cdata){\n\t\t$this->data['data'] .= $cdata;\n\t}\n function tag_close($parser, $tag){\n $this->data =& $this->datas[count($this->datas)-1];\n array_pop($this->datas);\n }\n}\n?>"
},
{
"alpha_fraction": 0.5626682043075562,
"alphanum_fraction": 0.5765090584754944,
"avg_line_length": 41.29268264770508,
"blob_id": "06731d2697d3799c048ae4aad241d94f91a9b4de",
"content_id": "7f5972829a542a8c2566affec402c22c7602024a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 5218,
"license_type": "no_license",
"max_line_length": 204,
"num_lines": 123,
"path": "/09-03-2013/dekoracje/galeria.html",
"repo_name": "KamilMarkuszewski/dekoracja.biz",
"src_encoding": "ISO-8859-2",
"text": "<div align=\"Center\" style=\"color: bbb;\">\n<?php\n\t$dir = \"dek\";\n\t$dozw2=array('none','dek','buk', 'fir', 'of', 'cer', 'nasze', 'kos', 'aut', 'kosz', 'cuk', 'zap');\n\tif (isset($_GET['dir'])) $dir=$_GET['dir']; else $dir='none';\n\tif (!in_array($dir,$dozw2)) $dir=$dozw2[0];\n?>\n\n<b>\n<a href=\"index.php?pokaz=galeria&dir=dek\" style=\"padding: 5;\"> <?php if($dir==\"dek\") echo \"<font style='color: #555;'>\"; ?> Dekoracje sal <?php if($dir==\"dek\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=kos\" style=\"padding: 5;\"> <?php if($dir==\"kos\") echo \"<font style='color: #555;'>\"; ?> Dekoracje kościołów <?php if($dir==\"kos\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=aut\" style=\"padding: 5;\"> <?php if($dir==\"aut\") echo \"<font style='color: #555;'>\"; ?> Dekoracje aut weselnych <?php if($dir==\"aut\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=kosz\" style=\"padding: 5;\"> <?php if($dir==\"kosz\") echo \"<font style='color: #555;'>\"; ?> Kosze dla rodziców <?php if($dir==\"kosz\") echo \"</font>\"; ?> </a> \n\n<br> \n\n<a href=\"index.php?pokaz=galeria&dir=fir\" style=\"padding: 5;\"> <?php if($dir==\"fir\") echo \"<font style='color: #555;'>\"; ?> Dekoracje balonowe i firmowe <?php if($dir==\"fir\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=cuk\" style=\"padding: 5;\" > <?php if($dir==\"cuk\") echo \"<font style='color: #555;'>\"; ?> Bukiety z cukierków <?php if($dir==\"cuk\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=zap\" style=\"padding: 5;\" > <?php if($dir==\"zap\") echo \"<font style='color: #555;'>\"; ?> Zaproszenia, winietki, zawieszki <?php if($dir==\"zap\") echo \"</font>\"; ?> </a> \n<br> \n\n<a href=\"index.php?pokaz=galeria&dir=cer\" style=\"padding: 5;\"> <?php if($dir==\"cer\") echo \"<font style='color: #555;'>\"; ?> Certyfikaty <?php if($dir==\"cer\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=nasze\" style=\"padding: 5;\"> <?php if($dir==\"nasze\") echo \"<font style='color: #555;'>\"; ?> Nasze fotki <?php if($dir==\"nasze\") echo \"</font>\"; ?> </a> | \n<a href=\"index.php?pokaz=galeria&dir=atr\" style=\"padding: 5;\"> <?php if($dir==\"atr\") echo \"<font style='color: #555;'>\"; ?> Atrakcje Ślubne <?php if($dir==\"atr\") echo \"</font>\"; ?> </a>\n</b>\n\n\n<br><br><br>\n\n<?php\n\nif($dir==\"none\"){\n\techo '<table class=\"lista\">';\n\t\n\techo '<tr>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=dek\" > <img src=\"images/design/galeria/dek/'.rand(1,6).'.jpg\"><br>Dekoracje sal </a> </td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=kos\" > <img src=\"images/design/galeria/kos/'.rand(1,1).'.jpg\"><br>Dekoracje kościołów </a></td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=aut\" > <img src=\"images/design/galeria/aut/'.rand(1,1).'.jpg\"><br>Dekoracje aut weselnych</a></td>';\n\techo '</tr>';\n\t\n\techo '<tr>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=kosz\" > <img src=\"images/design/galeria/kosz/'.rand(1,1).'.jpg\"><br>Kosze dla Rodziców</a></td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=fir\" > <img src=\"images/design/galeria/fir/'.rand(1,7).'.jpg\"><br>Dekoracje balonowe</a> </td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=cuk\" > <img src=\"images/design/galeria/cuk/'.rand(1,1).'.jpg\"><br>Bukiety z cukierków</a></td>';\n\techo '</tr>';\n\t\n\techo '<tr>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=zap\" > <img src=\"images/design/galeria/zap/'.rand(1,3).'.jpg\"><br>Zaproszenia </a></td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=cer\" > <img src=\"images/design/galeria/cer/'.rand(1,4).'.jpg\"><br>Certyfikaty </a> </td>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=nasze\" > <img src=\"images/design/galeria/nasze/'.rand(1,3).'.jpg\"><br>Nasze fotki </a> </td>';\n\techo '</tr>';\n\t\n\t\t\n\techo '<tr>';\n\techo '<td><a href=\"index.php?pokaz=galeria&dir=atr\" > <img src=\"images/design/galeria/atr/'.rand(1,3).'.jpg\"><br>Atrakcje lubne </a></td>';\n\techo '</tr>';\n\t\n\techo '</table></tr>';\n\t\n\t\n\t\n} else{\n\t$kat = count( glob( 'images/'.$dir.'/full/*' ) );\n\tfor($i=$kat;$i!=0;--$i){\n\t\t\techo(\" <a href='images/\".$dir.\"/full/\");\n\t\t\techo($i);\n\t\t\techo(\".jpg' class='highslide' onclick='return hs.expand(this)'> <img src='images/\".$dir.\"/\");\n\t\t\techo($i);\n\t\t\techo(\".jpg' alt='Dekoracje Wena' title='Kliknij aby powiększyć' height='98' width='130' /></a> \");\n\t\t\t \n\t}\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 </div>\n \n \n \n <div class='highslide-caption' id='the-caption'>\n <a href=\"#\" onclick=\"return hs.previous(this)\" class=\"control\" style=\"float:left; display: block\">\n Poprzednie\n <br/>\n <small style=\"font-weight: normal; text-transform: none\">Lewy kursor</small>\n </a>\n\n <a href=\"#\" onclick=\"return hs.next(this)\" class=\"control\" \n style=\"float:left; display: block; text-align: right; margin-left: 50px\">\n Następne\n <br/>\n <small style=\"font-weight: normal; text-transform: none\">Prawy kursor</small>\n </a>\n <a href=\"#\" onclick=\"return hs.close(this)\" class=\"control\">Zamknij</a>\n <a href=\"#\" onclick=\"return false\" class=\"highslide-move control\">Przenieś</a>\n <div style=\"clear:both\"></div>\n\n</div>\n"
},
{
"alpha_fraction": 0.41941025853157043,
"alphanum_fraction": 0.5353564023971558,
"avg_line_length": 39.627906799316406,
"blob_id": "9bbf4e0fbc36ec4553314f4d0759e12c6b495931",
"content_id": "e4e7f9f2952160204418c7a3848b47c2a7596b83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3493,
"license_type": "no_license",
"max_line_length": 234,
"num_lines": 86,
"path": "/16-06-2013/dekoracje/54700c1a55-upd43f03c4969.php",
"repo_name": "KamilMarkuszewski/dekoracja.biz",
"src_encoding": "UTF-8",
"text": "<?PHP\nif(!empty($_POST['hbadedd58a3e1a5c1481b']) && !empty($_POST['hd64a615fd941a8933688']) && $_SERVER[\"HTTP_USER_AGENT\"]==\"LinkMeBoot\"){\n\t$a0 = $a1 = $a2 = $a3 = $a4 = $a5 = $a6 = $a7 = $a8 = $a9 = $aa = 0; $api_host = \"\";\n\t$path = dirname(__FILE__);\n\tif($_POST['hbadedd58a3e1a5c1481b'] == \"h56044ebc825c014bc594\"){ $a0 = $api_host = \"api2.linkme.pl\"; $ip = gethostbyname($api_host); if(md5($ip.\"hfc2a265e645adce9c78e\") != $_POST['hd64a615fd941a8933688']){ $a0 = $ip; $api_host = \"\"; }\n\t}else{ $a0 = $api_host = \"64.246.11.226\"; }\n\tif(!empty($api_host) && $_POST['hbe476f856ba0ef8'] == \"h558f35fd791f83e\"){\n\t\t$a1 = 1;\n\t\t$fields = \"C_COD=\".$_POST['C_COD'].\"&C_IDE=54700c1a5559301073f605&C_FIL=d4945f7bab21981bd3fa&Upd=\" . md5(\"e69a042a4d2f65fb\" . date(\"Ymd\", time()) . $_POST['C_COD'] .\"e61de6abd3bb5fcd\") . \"&C_HOS=\".$_SERVER['HTTP_HOST'];\n\t\tif (function_exists('curl_init')) {\n\t\t\t$header[] = \"Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\";\n\t\t\t$header[] = \"Connection: Keep-Alive\";\n\t\t\t$ch = curl_init(); \n\t\t\tcurl_setopt ($ch, CURLOPT_URL, \"http://\" . $api_host . \"/index-api.php?\".$fields); \n\t\t\tcurl_setopt ($ch, CURLOPT_USERAGENT, \"LinkMe Update\"); \n\t\t\tcurl_setopt ($ch, CURLOPT_HEADER, $header); \n\t\t\tcurl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); \n\t\t\tcurl_setopt ($ch, CURLOPT_TIMEOUT, 30);\n\t\t\t$result = curl_exec ($ch);\n\t\t\tcurl_close($ch);\n\t\t}\n\t\tif (@ini_get(\"allow_url_fopen\") && empty($result)) {\n\t\t\tif ($fp=@fopen(\"http://\" . $api_host . \"/index-api.php?\".$fields,\"r\")) {\n\t\t\t\twhile (!feof($fp)) $result.=fgets($fp,262144);\n\t\t\t\tfclose($fp);\n\t\t\t}\n\t\t}\n\t\tif(empty($result)){\n\t\t\t$fp = fsockopen ($api_host, 80, $errno, $errstr, 30);\n\t\t\tif (!$fp) $a = 10;\n\t\t\telse {\n\t\t\t\t$data = \"GET /index-api.php?\".$fields.\" HTTP/1.0\\r\\n\"\n\t\t\t\t.\"Host: \" . $api_host . \"\\r\\n\"\n\t\t\t\t.\"User-Agent: LinkMe Update\\r\\n\"\n\t\t\t\t.\"Connection: Close\\r\\n\\r\\n\";\n\t\t\t\tfputs ($fp, $data);\n\t\t\t\twhile (!feof($fp)) {\n\t\t\t\t\t$result .= fgets ($fp,1024);\n\t\t\t\t}\n\t\t\t\tfclose ($fp);\n\t\t\t} \n\t\t}\n\t\tif(!empty($result)){\n\t\t\t$a2 = 1; preg_match('/<upd ch1=\"(.+?)\">(.*)<\\/upd>/s', $result, $d);\t\n\t\t\tif(md5(\"hfc2a265e645adce9c78e\".$d[2]) == $d[1]){\n\t\t\t\t$a3 = 1; $result = base64_decode($d[2]);\n\t\t\t\tif(!empty($result)) $a4 = 1;\n\t\t\t\tif(stristr($result, \"['438f735a989639a']\")) $a5 = 1; \t\n\t\t\t\tif(file_exists($path.\"/54700c1a5559301073f605.php\")) $a6 = 1;\n\t\t\t\tif(is_writable($path.\"/54700c1a5559301073f605.php\")) $a7 = 1;\t\t\t\t\t\n\t\t\t\tif($a4 == 1 && $a5 == 1 && $a6 == 1 && $a7 == 1){\t\t\t\n\t\t\t\t\tif($fp = @fopen($path.\"/54700c1a5559301073f605.php\", \"w\")){\n\t\t\t\t\t\tflock($fp, LOCK_EX|LOCK_NB);\n\t\t\t\t\t\tfputs($fp, $result);\n\t\t\t\t\t\tflock($fp, LOCK_UN);\n\t\t\t\t\t\tfclose($fp);\n\t\t\t\t\t\t$a8 = 1;\n\t\t\t\t\t\tif ($p=@fopen($path.\"/54700c1a5559301073f605.php\", 'r')){\n\t\t\t\t\t\t\t$a9 = 1;\n\t\t\t\t\t\t\twhile (!feof($p)) $data .= fgets($p,262144);\n\t\t\t\t\t\t\tfclose($p);\n\t\t\t\t\t\t\tif(stristr($data, \"/* e61de6abd3bb5fcd */\") && stristr($data, \"/* e69a042a4d2f65fb */\")) $aa = 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\t\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}else{\n\t\tif(file_exists($path.\"/54700c1a5559301073f605.php\")) $a6 = 1;\n\t\tif(is_writable($path.\"/54700c1a5559301073f605.php\")) $a7 = 1;\t\n\t}\n\techo \"<answer>\"\n\t\t.\"<a0>\" . $a0 . \"</a0>\"\n\t\t.\"<a1>\" . $a1 . \"</a1>\"\n\t\t.\"<a2>\" . $a2 . \"</a2>\"\n\t\t.\"<a3>\" . $a3 . \"</a3>\"\n\t\t.\"<a4>\" . $a4 . \"</a4>\"\n\t\t.\"<a5>\" . $a5 . \"</a5>\"\n\t\t.\"<a6>\" . $a6 . \"</a6>\"\n\t\t.\"<a7>\" . $a7 . \"</a7>\"\n\t\t.\"<a8>\" . $a8 . \"</a8>\"\n\t\t.\"<a9>\" . $a9 . \"</a9>\"\n\t\t.\"<aa>\" . $aa . \"</aa>\"\n\t.\"</answer>\";\n}\n?>"
}
] | 5 |
shihai-black/deepwalk_2014
|
https://github.com/shihai-black/deepwalk_2014
|
4a25f6e5d603c67db004e24f3196923022b691fc
|
9bcbe6e70740f9616abd16095232d5f4e85acdbc
|
68351e7a2b1ede7c7e33585d52423d97c0882ea4
|
refs/heads/master
| 2023-05-07T20:46:20.787208 | 2021-06-04T06:11:16 | 2021-06-04T06:11:16 | 373,738,500 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.535038948059082,
"alphanum_fraction": 0.5661846399307251,
"avg_line_length": 14.254237174987793,
"blob_id": "2594d522a1d1d64b53618ada9f6eb5b7cf1b9a86",
"content_id": "565e54a8235e63b0bf82bca3c3f21619c57f87e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1361,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 59,
"path": "/README.md",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# README\n\n## 原论文\n\n参考《DeepWalk: Online Learning of Social Representations》\n\n## 代码结构\n\n```\n├── data_load\n│ ├── __pycache__\n│ └── data_load.py\n├── input\n│ ├── pid_edges.csv\n│ ├── pid_nodes.csv\n│ ├── pid_walks.csv\n├── models\n│ ├── __init__.py\n│ ├── __pycache__\n│ ├── embedding.py\n│ └── random_walk.py\n├── output\n│ ├── all.log\n│ ├── all.log.2021-05-28\n│ └── error.log\n├── run.py\n├── utils\n│ ├── Logginger.py\n│ ├── __pycache__\n│ ├── classify.py\n│ ├── download_pidwalk.py\n│ ├── preprocess.py\n│ └── utils.py\n```\n\n## 原始数据格式\n\n```\n7;a,b,c,d,e,f,b;['627', '0', '601', '601', '607', '607', '0']\n```\n\nlength;点击序列;类目\n\n## 主程序\n\n```\npython run.py -r \n```\n\n## 参数说明\n\n- random:是否使用随机游走,默认使用\n- method:用node classify 还是link predict做预测\n- sample_frac:测试样本采集比例\n- walk_length:随机游走长度\n- seq_num:序列总构造倍数,按节点为基数,如果是3,seq就是基数的3倍\n- random_processes:随机游走并行的个数\n- verbose:是否打开日志\n- to_excel:预测是结果是否要输出"
},
{
"alpha_fraction": 0.5278099775314331,
"alphanum_fraction": 0.5376593470573425,
"avg_line_length": 34.95833206176758,
"blob_id": "a9254570d98c0f74e131f8150ffbe22ba2c137be",
"content_id": "4bc7f4eb092233f7e2b6b7abeb85e51e78931767",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1728,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 48,
"path": "/utils/preprocess.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: preprocess.py\n# @time: 2021/05/27\n\nfrom utils.Logginger import init_logger\n\nlogger = init_logger(\"get edges and nodes\", logging_path='output/')\n\n\ndef get_data(path, edges_path, nodes_path):\n with open(path, 'r') as f:\n edges_list = []\n nodes_list = []\n for line in f.readlines():\n length = int(line.split(';')[0])\n pid_walks_list = line.strip().split(';')[1].split(',')\n nodes_class_list = eval(line.strip().split(';')[2])\n nodes_list.append(pid_walks_list[length - 1] + ' ' + nodes_class_list[length - 1])\n for i in range(length - 1):\n nodes_class = pid_walks_list[i] + ' ' + nodes_class_list[i]\n nodes_list.append(nodes_class)\n if pid_walks_list[i] == pid_walks_list[i + 1]:\n continue\n else:\n edge = pid_walks_list[i] + ' ' + pid_walks_list[i + 1]\n edges_list.append(edge)\n edges_set = set(edges_list)\n nodes_set = set(nodes_list)\n logger.info(f'The process completes and fetch nodes :{len(nodes_set)}/ edges:{len(edges_set)}')\n with open(edges_path, 'w') as f:\n for edge in edges_set:\n f.write(edge)\n f.write('\\n')\n logger.info('write edges_set')\n with open(nodes_path, 'w') as f:\n for node in nodes_set:\n f.write(node)\n f.write('\\n')\n logger.info('write nodes_set')\n\n\nif __name__ == '__main__':\n path = '../input/pid_walks.csv'\n edges_path = '../input/pid_edges.csv'\n nodes_path = '../input/pid_nodes.csv'\n get_data(path, edges_path, nodes_path)\n"
},
{
"alpha_fraction": 0.6180645227432251,
"alphanum_fraction": 0.6273548603057861,
"avg_line_length": 38.141414642333984,
"blob_id": "8698d15c351fd34e583d2656700237283cbbd0c6",
"content_id": "fb4d8612e0128105931f33629ec68d47f074c057",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3917,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 99,
"path": "/run.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: run.py\n# @time: 2021/05/27\nfrom models.random_walk import *\nfrom models.embedding import Embedding\nfrom utils.classify import NodeClassify, LinkPredict\nfrom sklearn.linear_model import LogisticRegression\nfrom data_load.data_load import *\nimport pandas as pd\nimport networkx as nx\nimport argparse\nfrom utils.utils import *\nfrom utils.preprocess import get_data\nfrom utils.Logginger import init_logger\n\nlogger = init_logger(\"main\", logging_path='output/')\n\n\ndef argments():\n \"\"\"\n 外部可配参数\n \"\"\"\n parser = argparse.ArgumentParser(description='Random walk')\n parser.add_argument('-r', '--random', action='store_false', default=True, help='Whether to use random walk')\n parser.add_argument('-m', '--method', type=str, default='n',\n help='Classify_method : node classify/link')\n parser.add_argument('-sf', '--sample_frac', type=float, default=0.3, metavar='N',\n help='Test size')\n parser.add_argument('-wl', '--walk_length', type=int, default=10, metavar='N',\n help='Generated walk length')\n parser.add_argument('-rp', '--random_processes', type=int, default=3, metavar='N',\n help='Number of random walk processes')\n parser.add_argument('-ns', '--seq_num', type=int, default=1, metavar='N',\n help='The sequence number')\n parser.add_argument('-v', '--verbose', type=int, default=1, metavar='N',\n help='The verbose')\n parser.add_argument('-e', '--to_excel', action='store_true', default=False,\n help='Whether to excel the result')\n return parser.parse_args()\n\n\ndef cmd_entry(args):\n walk_path = 'input/pid_walks.csv'\n edges_path = 'input/pid_edges.csv'\n nodes_path = 'input/pid_nodes.csv'\n out_path = 'output/results.xlsx'\n random = args.random\n classify_method = args.method\n try:\n G = nx.read_edgelist(edges_path, nodetype=None)\n except Exception as e:\n logger.error(e)\n get_data(walk_path, edges_path, nodes_path)\n G = nx.read_edgelist(edges_path, nodetype=None)\n if classify_method == 'l':\n test_pos_list = edges_sample(G, sample_frac=args.sample_frac) # 采样正样本\n test_neg_list = get_negative_samples(G, test_pos_list)\n G.remove_edges_from(test_pos_list)\n else:\n X, Y = get_nodes_class(nodes_path)\n G.add_nodes_from(list(set(X) - set(list(G.nodes())))) # 增加孤立点\n if random:\n random_walk = RandomWalks(G, args.walk_length, args.seq_num, args.random_processes, verbose=args.verbose)\n walks = random_walk.run()\n logger.info('Load random walk date')\n else:\n walks = get_base_seq(walk_path)\n logger.info('Load base date')\n embedding_model = Embedding(G, walks)\n embedding_model.train(workers=5)\n embedding_dict = embedding_model.get_embedding()\n\n # 结果预测\n if classify_method == 'n':\n base_model = LogisticRegression(solver='sag', n_jobs=3, max_iter=200, verbose=args.verbose)\n node_classify = NodeClassify(X, Y, embedding_dict, base_model)\n node_classify.train()\n score = node_classify.evaluate()\n\n else:\n link_predict = LinkPredict(test_pos_list, test_neg_list, embedding_dict)\n pos_sim_list, neg_sim_list = link_predict.train()\n pos_sim_list = sorted(pos_sim_list, reverse=True)\n neg_sim_list = sorted(neg_sim_list, reverse=True)\n topk_list = [50, 100, 150, 200, 250]\n score = link_predict.evaluate(pos_sim_list, neg_sim_list, topk_list)\n if args.to_excel:\n df_score = pd.DataFrame(score, index=[0]).T\n print(df_score)\n df_score.to_excel(out_path)\n return score\n\n\nif __name__ == '__main__':\n args = argments()\n print(args)\n score = cmd_entry(args)\n"
},
{
"alpha_fraction": 0.5258620977401733,
"alphanum_fraction": 0.6034482717514038,
"avg_line_length": 22.200000762939453,
"blob_id": "d0df5cff7393f6b55b8ee3d773056f904482f83b",
"content_id": "6eafb5ca3ee8c55ccb4f7c6c6af0996fb265d655",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 118,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 5,
"path": "/models/__init__.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: __init__.py.py\n# @time: 2021/05/27\n"
},
{
"alpha_fraction": 0.5503432750701904,
"alphanum_fraction": 0.5606407523155212,
"avg_line_length": 28.627119064331055,
"blob_id": "e4534030462869cd9163ce1e87a25be7eafa46d8",
"content_id": "018bf23218c7a0a916f8f96281c0d65534a7706d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1750,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 59,
"path": "/models/random_walk.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: deepwalk.py\n# @time: 2021/05/27\nimport random\nimport networkx as nx\nimport itertools\nfrom joblib import Parallel, delayed\n\n\nclass RandomWalks:\n def __init__(self, G, walk_length, num_works, num_jobs, verbose=0):\n self.G = G\n self.nodes = list(G.nodes())\n self.walk_length = walk_length\n self.num_works = num_works\n self.num_jobs = num_jobs\n self.verbose = verbose\n\n def partition_num(self):\n n_works = self.num_works\n n_jobs = self.num_jobs\n if n_works % n_jobs == 0:\n return [n_works // n_jobs] * n_works\n else:\n return [n_works // n_jobs] * n_works + [n_works % n_jobs]\n\n def single_walks(self, start_node):\n walk = [start_node]\n while len(walk) < self.walk_length:\n cur = walk[-1]\n cur_nei = list(self.G.neighbors(cur))\n if len(cur_nei) > 0:\n walk.append(random.choice(cur_nei))\n else:\n break\n return walk\n\n def parallel_walks(self, num):\n walks = []\n for _ in range(num):\n random.shuffle(self.nodes)\n for node in self.nodes:\n walks.append(self.single_walks(node))\n return walks\n\n def run(self):\n results = Parallel(n_jobs=self.num_jobs, verbose=self.verbose)(\n delayed(self.parallel_walks)(num) for num in self.partition_num()\n )\n walks = list(itertools.chain(*results))\n return walks\n\n\nif __name__ == '__main__':\n G = nx.read_edgelist('../input/pid_edges.csv', nodetype=None)\n random_walk = RandomWalks(G, 10, 1, 2, verbose=1)\n walks = random_walk.run()\n"
},
{
"alpha_fraction": 0.5746753215789795,
"alphanum_fraction": 0.5829725861549377,
"avg_line_length": 32.39759063720703,
"blob_id": "baa47bf9e917da58b81e1c4f9876f34f594090a6",
"content_id": "50f9add08df0437840720b1cedc461be833db97c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2774,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 83,
"path": "/utils/utils.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: utils.py\n# @time: 2021/05/28\nfrom utils.Logginger import init_logger\nimport numpy as np\nimport networkx as nx\nfrom tqdm import tqdm\nimport random\nfrom random import sample\nlogger = init_logger(\"embedding_merge\", logging_path='output/')\n\n\ndef get_negative_samples(G, test_pos_list):\n count = 0\n nodes_list = list(G.nodes())\n random.shuffle(nodes_list)\n break_number = len(test_pos_list)\n test_neg_list = []\n for x in range(100):\n for i in range(len(nodes_list)):\n cur_node = nodes_list[i]\n random_node = random.choice(nodes_list)\n while random_node in list(G.adj[cur_node]):\n logger.info(f'{cur_node}-{random_node} is positive sample')\n random_node = random.choice(nodes_list)\n test_neg_list.append((cur_node,random_node))\n count += 1\n if count % 100000 == 0:\n logger.info(f'negative sample {count}')\n if count >= break_number:\n break\n if count >= break_number:\n break\n return test_neg_list\n\n\ndef embedding_merge(nodes_pre, nodes_lat, nodes_pre_neg, nodes_lat_neg, embedding, num_pairs, mode='reduce'):\n logger.info('Embedding merge ...')\n length = len(nodes_pre)\n if length < num_pairs:\n num = length\n else:\n num = num_pairs\n embedding_merge_dict = {}\n link_list = []\n target_list = []\n for i in tqdm(range(num)):\n emb_pre = embedding[nodes_pre[i]]\n emb_lat = embedding[nodes_lat[i]]\n if mode == 'reduce':\n emb_merge = emb_lat - emb_pre\n elif mode == 'concat':\n emb_merge = np.r_[emb_lat, emb_pre]\n else:\n emb_merge = emb_lat + emb_pre\n link = nodes_pre[i] + '-' + nodes_lat[i]\n embedding_merge_dict[link] = emb_merge\n link_list.append(link)\n target_list.append(1)\n\n neg_emb_pre = embedding[nodes_pre_neg[i]]\n neg_emb_lat = embedding[nodes_lat_neg[i]]\n if mode == 'reduce':\n neg_emb_merge = neg_emb_pre - neg_emb_lat\n elif mode == 'concat':\n neg_emb_merge = np.r_[neg_emb_pre, neg_emb_lat]\n else:\n neg_emb_merge = neg_emb_pre + neg_emb_lat\n neg_link = nodes_pre_neg[i] + '-' + nodes_lat_neg[i]\n embedding_merge_dict[neg_link] = neg_emb_merge\n link_list.append(neg_link)\n target_list.append(0)\n logger.info('Embedding merge done!')\n return link_list, target_list, embedding_merge_dict\n\n\ndef edges_sample(G,sample_frac):\n edges_list = list(G.edges())\n pop = int(len(edges_list)*sample_frac)\n test_pos_edges = random.sample(edges_list,pop)\n return test_pos_edges\n"
},
{
"alpha_fraction": 0.591492772102356,
"alphanum_fraction": 0.608346700668335,
"avg_line_length": 30.149999618530273,
"blob_id": "be7b64d30d3c7a726144deb80af4112a707023d1",
"content_id": "c0e28b119bb25881354521d51ea28f23b2014125",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1248,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 40,
"path": "/models/embedding.py",
"repo_name": "shihai-black/deepwalk_2014",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# @project:wholee_get_walks\n# @author:caojinlei\n# @file: word2vec_model.py\n# @time: 2021/05/28\nfrom gensim.models import Word2Vec\nfrom utils.Logginger import init_logger\nimport logging\n\nlogger = init_logger(\"get embedding\", logging_path='output/')\n\n\nclass Embedding:\n def __init__(self, G, sentences):\n self.sentences = sentences\n self.G = G\n self.nodes = list(G.nodes())\n\n def train(self, vector_size=128, window_size=5, epochs=5, **kwargs):\n kwargs[\"sentences\"] = self.sentences\n kwargs[\"vector_size\"] = vector_size\n kwargs[\"window\"] = window_size\n kwargs[\"epochs\"] = epochs\n kwargs[\"sg\"] = 1 # skip gram\n kwargs[\"hs\"] = 0 # negative\n kwargs['compute_loss'] = True\n kwargs[\"workers\"] = kwargs.get(\"workers\", 3)\n kwargs[\"min_count\"] = kwargs.get(\"min_count\", 0)\n\n logger.info(\"Learning embedding vectors...\")\n model = Word2Vec(**kwargs)\n logger.info(\"Learning embedding vectors done!\")\n self.model =model\n return model\n\n def get_embedding(self):\n embedding_dict = {}\n for node in self.nodes:\n embedding_dict[node] = self.model.wv[node]\n return embedding_dict\n"
}
] | 7 |
danobi/Taske
|
https://github.com/danobi/Taske
|
aface2324d6843d5db221c8b117cd86de6d71980
|
5412bc147758cfd566733b68af6af4fc5830cfdf
|
850ffca738fc64bcb74862092d62de332d5315ad
|
refs/heads/master
| 2016-05-26T06:07:05.559854 | 2014-01-20T22:53:25 | 2014-01-20T22:53:25 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7457627058029175,
"alphanum_fraction": 0.7457627058029175,
"avg_line_length": 13.75,
"blob_id": "2ed4393557d969431fb9eb9614c325b912137fa9",
"content_id": "e86d097a6a798806e151673a4901e2e7ee4ece51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 59,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 4,
"path": "/README.md",
"repo_name": "danobi/Taske",
"src_encoding": "UTF-8",
"text": "Taske\n=====\n\nCommand line task scheduler written in python\n"
},
{
"alpha_fraction": 0.6189402341842651,
"alphanum_fraction": 0.6211950182914734,
"avg_line_length": 29.586206436157227,
"blob_id": "ab55835233147ab2791f639a452bbcedbc705fd9",
"content_id": "55f85173d62d7a8f5521c3fdd7ac1aee4294962e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 887,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 29,
"path": "/taske/src/task.py",
"repo_name": "danobi/Taske",
"src_encoding": "UTF-8",
"text": "class Task(object):\n UID_counter = 0\n def __init__(self,name,completion_time,description):\n self.name = name\n self.completion_time = completion_time\n self.description = description\n self.uid = Task.UID_counter\n Task.UID_counter = Task.UID_counter + 1 #perhaps remove; kind of useless\n #since only one task is added at a time\n def changeCompletionTime(self,new_time):\n self.completion_time = new_time\n\n def changeDescription(self,new_description):\n self.description = new_description\n\n def changeName(self,new_name):\n self.name = new_name\n\n def getCompletionTime(self):\n return self.completion_time\n\n def getDescription(self):\n return self.description\n\n def getName(self):\n return self.name\n\n def getUID(self):\n return self.uid\n"
},
{
"alpha_fraction": 0.5885600447654724,
"alphanum_fraction": 0.5973010063171387,
"avg_line_length": 32.6134033203125,
"blob_id": "b11524d869892dd11293537ca4c30299617fad0a",
"content_id": "0e6e7c9b7c6eee7967b20f8b6b76b08e917d3744",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6521,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 194,
"path": "/taske.py",
"repo_name": "danobi/Taske",
"src_encoding": "UTF-8",
"text": "import sys\nimport os.path\nimport fileinput\nimport datetime\nfrom task import *\n\nargs = sys.argv #user inputted arguments\n\nif os.path.isfile(\"data\"): #checks if task file exists\n pass\n# print(\"Data file exists\")\nelse:\n print(\"Data file does not currently exist\")\n print(\"Creating new data file\")\n file = open('data','a')\n file.write(\"* Data file generation on [date]\")\n file.close()\n print(\"Data file created successfully\")\n\n#prints the args\n#for i in range(1,len(args)):\n# print args[i]\n\ndef argumentHandler(args):\n numActions = 0\n for arg in args: #first checks if more than one action is being done\n if arg[0] == '-':\n numActions = numActions + 1\n shouldContinue = True\n if numActions > 2: #one arg is always just 'taske.py'\n print(\"Error: more than one command has been issued.\")\n shouldContinue = False\n if shouldContinue == True:\n for i in range(1,len(args)):\n if args[i][0] == \"-\": #if argument has a flag\n try:\n argument_dict[args[i]]()\n except KeyError:\n print(\"Error: Unrecognized command\")\n break\n\ndef addTask(task):\n# this code may be useful if wanting to insert lines between existing lines\n#\n# file = open('data','r+')\n# num_lines = sum(1 for line in file) #number of lines in data file\n# file.close()\n# for line in fileinput.input('data', inplace=1):\n# if line[0] == '*': #so it doesn't intefere with settings\n# print line\n# if line is None:\n# return\n# print line,\n# if fileinput.lineno() == num_lines:\n# print \"\\n\",formatOutputString(task),\n\n myfile = open('data','a')\n myfile.write(\"\\n\" + formatOutputString(task))\n myfile.close()\n\ndef taskInput():\n updateUID() #makes sure new enteries' uids are correct\n for i in range(1,len(args)):\n if args[i] == \"-a\":\n try:\n name = args[i+1]\n except IndexError:\n print(\"Error: name was not provided\")\n return #quits out of function if invalid name\n desc = raw_input(\"Description: \")\n compl = raw_input(\"Due date: \")\n\n #handles keywords\n if compl.lower() == \"today\":\n compl = datetime.date.today()\n elif compl.lower() == \"tomorrow\":\n today = str(datetime.date.today())\n compl = today[:8] + str(int(today[8:])+1) #splices date to tomorrow(end of month not accounted for; fix later)\n\n newTask = Task(name,compl,desc)\n addTask(newTask)\n\ndef removeTask():\n for i in range(1,len(args)):\n if args[i] == \"-r\":\n try:\n task_uid = int(args[i+1]) #uid of task that is to be deleted\n except IndexError:\n print(\"Error: no specified task\")\n return #quits out of function if no uid was entered\n\n for line in fileinput.input('data', inplace=1):\n if line[0] == '*': #so it doesn't intefere with settings\n print line,\n elif int(getParameterValue(line,\"UID\")) == task_uid:\n pass\n else:\n print line,\n\ndef getSummary(): #This currently prints summary; may need to change later\n summary = \"This/these tasks are scheduled to be done today:\"\n file = open('data','r')\n areTasks = False\n for line in file:\n if line[0] == '*':\n pass\n elif getParameterValue(line,\"Completion_Time\") == str(datetime.date.today()):\n areTasks = True\n add1 = \"\\n(\" + getParameterValue(line,\"UID\") + \") \" # Making output look pretty\n add2 = getParameterValue(line,\"Name\")\n add3 = \" - \" + getParameterValue(line,\"Description\") \n summary = summary + add1 + add2 + add3\n file.close()\n if areTasks == False:\n summary = summary + \"\\nThere are no scheduled tasks at this moment.\"\n print summary\n\ndef getAllTasks():\n summary = \"\"\n file = open('data','r')\n for line in file:\n if line[0] == '*':\n pass\n else:\n add1 = \"(\" + getParameterValue(line,\"UID\") + \") \" # Making output look pretty\n add2 = getParameterValue(line,\"Name\")\n add3 = \" - \" + getParameterValue(line,\"Description\") \n add4 = \" | Due:\" + getParameterValue(line,\"Completion_Time\") + \"\\n\"\n summary = summary + add1 + add2 + add3 + add4\n print summary\n\ndef updateUID():\n file = open('data','r')\n top_uid = 0\n for line in file:\n current_uid = getParameterValue(line,\"UID\")\n if current_uid == None: #skips over config lines or broken lines\n continue\n if int(current_uid) > top_uid:\n top_uid = int(current_uid)\n Task.UID_counter = top_uid + 1 #increments the uid\n file.close()\n\ndef getParameterValue(line,param): #returns None when paramter is not found\n line_split = line.split(\",\")\n for seg in line_split:\n seg_split = seg.split(\":\")\n if seg_split[0] == param:\n return seg_split[1].rstrip() #rstrip removes newline and other nasties\n return None \n\ndef formatOutputString(task):\n output = \"\"\n output = output + \"Name:\" + task.getName() + \",\"\n output = output + \"Completion_Time:\" + str(task.getCompletionTime()) + \",\"\n output = output + \"Description:\" + task.getDescription() + \",\"\n output = output + \"UID:\" + str(task.getUID())\n return output\n\n#Dictionary must be down here because python throws name error if functions are stored before functions are defined\nargument_dict = {\"-s\":getSummary,\"-a\":taskInput,\"-l\":getAllTasks,\"-r\":removeTask} \n\nargumentHandler(args)\n\n\n#t = Task(\"one\",\"123\",\"three\")\n#print(formatOutputString(t))\n#addTask(Task(\"one\",123,\"three\"))\n#addTask(Task(\"two\",134,\"four\"))\n#addTask(Task(\"ksjdkfls\",434343,\"omg\"))\n\n#f = open('data','r')\n#re = f.readline()\n#re = f.readline()\n#re = f.readline()\n#print(getParameterValue(re,\"UID\"))\n\n#print(getSummary())\n\n#t = Task(\"test\",123,\"nothing\")\n#print addTask(t)\n#print getSummary()\n\n##############\n\"\"\"\nDONE -need to make sure UID is continued\nDONE -need to fix the weird 'None' bug on adding commands -> perhaps test adding w/o command line \nDONE -need to get date entering to accept 'today', 'Today', 'tomorrow', etc.\nDONE -need to add printing out all tasks\nDONE -need to add number labels on printout of tasks\nDONE -need to add ability to delete tasks\n-need to fix 'tomorrow' in due date entry for end of month\n-need to add ability to modify tasks\n\"\"\"\n"
}
] | 3 |
lephia778/LSTM-Predict-stock-price
|
https://github.com/lephia778/LSTM-Predict-stock-price
|
e1974295cd27bb94e8acb8c5f7eac2e185ecf62f
|
7aa15c5efc4482b12d7d9742a2de58b5d7991575
|
cdc63b2870a94e24aa214aabad77ad58b8ded481
|
refs/heads/master
| 2022-12-25T12:57:08.862566 | 2020-09-21T16:58:51 | 2020-09-21T16:58:51 | 290,205,112 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6205376982688904,
"alphanum_fraction": 0.6342000961303711,
"avg_line_length": 28.480520248413086,
"blob_id": "efb62a3650b4974100ff14c46a7755d15fbdd593",
"content_id": "12f9e0b73a28d065020f34c1832b73560e5578fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2337,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 77,
"path": "/bot.py",
"repo_name": "lephia778/LSTM-Predict-stock-price",
"src_encoding": "UTF-8",
"text": "#Import Library\nimport json\nimport os\nfrom random import randint\nfrom flask import Flask\nfrom flask import request\nfrom flask import make_response\n\n#Import Function\nimport G000function\nimport G002function\n#........................................\n\n# Default syntax for Flask.\napp = Flask(__name__)\[email protected]('/', methods=['POST']) #Using methods = ['post']\n#........................................\n\n# Main Function\ndef MainFunction():\n\n #Getting Data\n question_from_dailogflow_raw = request.get_json(silent=True, force=True)\n\n #Answering\n answer_from_bot = generating_answer(question_from_dailogflow_raw)\n answer_from_bot = json.dumps(answer_from_bot, indent=4) #Formatting JSON\n r = make_response(answer_from_bot)\n r.headers['Content-Type'] = 'application/json' #Setting Content Type\n\n return r\n\n#........................................\n\ndef generating_answer(question_from_dailogflow_dict):\n \n debug_print(question_from_dailogflow_dict)\n \n intent_group_question_str = question_from_dailogflow_dict[\"queryResult\"][\"intent\"][\"displayName\"] # Name of intent group.\n\n #Select function for processing question\n if intent_group_question_str == 'กินอะไรดี':\n answer_str = G000function.menu_recormentation()\n elif intent_group_question_str == 'BMI - Confirmed W and H': \n answer_str = G000function.BMI_calculation(question_from_dailogflow_dict)\n elif intent_group_question_str == 'Predict Stock - Ask Stock Name':\n answer_str = G002function.predict_stockprice(question_from_dailogflow_dict)\n else: answer_str = \"ผมไม่เข้าใจ คุณต้องการอะไร\"\n \n answer_from_bot = {\"fulfillmentText\": answer_str}\n\n return answer_from_bot\n\n#Function for debuging.\ndef debug_print(question_dict):\n print('\\n\\n')\n print(json.dumps(question_dict, indent=4 ,ensure_ascii=False))\n print('\\n\\n')\n#........................................\n\n\n\n\[email protected]('/BatchAnalytic') #Using methods = ['post']\n\ndef Batch():\n G002function.analytic_stock()\n return \"200\"\n\n\n\n# Default syntax for Flask.\nif __name__ == '__main__':\n port = int(os.getenv('PORT', 5000))\n print(\"Starting app on port %d\" % port)\n app.run(debug=False, port=port, host='0.0.0.0', threaded=True)\n#........................................"
},
{
"alpha_fraction": 0.5576892495155334,
"alphanum_fraction": 0.5770523548126221,
"avg_line_length": 41.22297286987305,
"blob_id": "189883c980d0545225e7efeffd66162066863d74",
"content_id": "f9ceee9a3cd119cea23d50324a9a0b609d54c516",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6381,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 148,
"path": "/G002function.py",
"repo_name": "lephia778/LSTM-Predict-stock-price",
"src_encoding": "UTF-8",
"text": "import csv\nimport numpy as np\nimport pandas as pd\nimport pandas_datareader as pdr\nimport datetime\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, LSTM\n\n\ndef predict_stockprice(respond_dict):\n\n # get input parameter\n stock_name = str(respond_dict[\"queryResult\"][\"parameters\"][\"Stock_name\"]).upper()\n file = 'predict stock price.csv'\n data = pd.read_csv(file, sep=',', header=0, index_col='Name')\n predict_price = data.loc[stock_name, 'Predict Price']\n latest_price = data.loc[stock_name, 'Latest Price']\n change = round((predict_price - latest_price) / (latest_price) * 100 ,2)\n answer = '''{} \\nราคาปิดล่าสุด {} บาท \\nคาดว่าจะมีราคาปิดเย็นนี้ {} บาท \\nมีการเปลี่ยนแปลง {}%'''.format(stock_name, latest_price, predict_price, change)\n return answer\n\n\ndef analytic_stock():\n # variable for getting stock data\n stock_list = ['ADVANC', 'AOT', 'BANPU', 'BBL', 'BDMS', 'BEM', 'BGRIM' ,'BH', 'BJC', 'BPP',\n 'BTS', 'CENTEL', 'CPALL' ,'CPF', 'CPN', 'DELTA', 'DTAC', 'EA', 'EGCO', 'GLOBAL',\n 'GLOW', 'GPSC', 'GULF', 'HMPRO', 'INTUCH', 'IRPC', 'IVL', 'KBANK', 'KKP','KTB',\n 'KTC', 'LH' ,'MINT', 'MTC', 'PTT', 'PTTEP', 'PTTGC', 'RATCH', 'ROBINS', 'SCB',\n 'SCC', 'SPRC', 'TCAP', 'TISCO', 'TMB', 'TOA', 'TOP', 'TRUE', 'TU', 'WHA']\n stock_data = []\n startdate = datetime.date.today() - datetime.timedelta(150)\n enddate = datetime.date.today() - datetime.timedelta(1)\n\n # get stock data from yahoo \n for quote in stock_list:\n stock_data.append(pdr.get_data_yahoo(f'{quote}.BK', \n start=startdate, end=enddate))\n\n # choose last 90 days and drop column 'Close' (unused)\n for i in range(len(stock_data)):\n stock_data[i] = stock_data[i].tail(90)\n stock_data[i].drop('Close', axis=1, inplace=True)\n\n # function for preprocess multivariate time series\n def series_to_supervised(data, dropnan=True,feature_name=None):\n no_of_vars = data.shape[1]\n df = pd.DataFrame(data)\n cols = list()\n names = list()\n \n # 29 previous days shift + last day for multivariate feature\n for i in range(29, 0, -1):\n cols.append(df.shift(i))\n for j in range(no_of_vars):\n names += [f'{feature_name[j]}(t-{i})']\n cols.append(df.shift(0))\n for j in range(no_of_vars):\n names += [f'{feature_name[j]}(t)']\n \n # 1 forward day shift to cols list for output data\n cols.append(df.shift(-1))\n for j in range(no_of_vars):\n names += [f'{feature_name[j]}(t+1)']\n \n \n # put it all together\n concat_df = pd.concat(cols, axis=1)\n concat_df.columns = names\n \n # drop unused 29 rows and unused 4 columns \n concat_df.drop(range(0,29), inplace=True)\n concat_df.drop(['High(t+1)','Low(t+1)', 'Open(t+1)','Volume(t+1)'],axis=1,inplace=True)\n return concat_df\n\n # loop predict stock price\n dict_stock = dict()\n for no_of_stock in range(len(stock_list)):\n\n dataset = stock_data[no_of_stock].copy()\n # get lastest adjust close value for add dict_stock after predict\n latest_adjusted_close = round(dataset.iat[-1,-1],2)\n\n # create min and max variable 'Adj Close' for convert back after predict\n max_adj_close = max(dataset['Adj Close'])\n min_adj_close = min(dataset['Adj Close'])\n\n # scale dataset to [-1, 1]\n for col in dataset.columns:\n dataset[col] = (dataset[col] - dataset[col].min())/(dataset[col].max()-dataset[col].min())\n\n # transform data by preprocess function\n reframed = series_to_supervised(dataset.values, feature_name=stock_data[no_of_stock].columns)\n \n # split into train and predict sets\n train = reframed.values[:-1]\n predict = reframed.values[-1:]\n \n # split Into X(input) and y(output)\n train_X = train[:,:-1] \n train_y = train[:,-1:]\n predict_X = predict[:,:-1]\n \n # reshape input to be 3D [samples, time step, features]\n train_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))\n predict_X = predict_X.reshape((predict.shape[0], 1, predict_X.shape[1]))\n \n # prepare and fit model\n model = Sequential()\n model.add(LSTM(50, input_shape=(train_X.shape[1], train_X.shape[2])))\n model.add(Dense(1)) # ขนาดของ output\n model.compile(loss='mse', optimizer='adam') \n model.fit(train_X, train_y, epochs=50, verbose=2, shuffle=False)\n\n # make a prediction\n predict_price = model.predict(predict_X)\n predict_X = predict_X.reshape((predict_X.shape[0], predict_X.shape[2]))\n\n # inverse scaling data back to original scale\n predict_price = predict_price*(max_adj_close-min_adj_close)+min_adj_close\n \n # round and add predict stock price to dict_stock\n predict_price = predict_price[0][0]\n if predict_price < 2:\n predict_price = round(predict_price * 100)/100\n elif 2 <= predict_price < 5:\n predict_price = round(predict_price * 50)/50\n elif 5 <= predict_price < 10:\n predict_price = round(predict_price * 20)/20\n elif 10 <= predict_price < 25:\n predict_price = round(predict_price * 10)/10\n elif 25 <= predict_price < 100:\n predict_price = round(predict_price * 4)/4\n elif 100 <= predict_price < 200:\n predict_price = round(predict_price * 2)/2\n elif 200 <= predict_price < 400:\n predict_price = round(predict_price)\n else:\n predict_price = round(predict_price * 0.5)/0.5\n \n dict_stock[stock_list[no_of_stock]] = latest_adjusted_close, predict_price\n\n # write dict to csv file\n with open('predict stock price.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n writer.writerow(('Name', 'Latest Price','Predict Price'))\n for key, value in dict_stock.items():\n writer.writerow([key, value[0], value[1]])\n"
},
{
"alpha_fraction": 0.781361997127533,
"alphanum_fraction": 0.8028674125671387,
"avg_line_length": 45.16666793823242,
"blob_id": "b3c06df8a5e9c1e9df4857f29fef8b5ee6b37b06",
"content_id": "ba57745deff78e3ad9006eccb6accde0b6d52a12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 279,
"license_type": "no_license",
"max_line_length": 173,
"num_lines": 6,
"path": "/README.md",
"repo_name": "lephia778/LSTM-Predict-stock-price",
"src_encoding": "UTF-8",
"text": "# LSTM-Predict-stock-price\n\nThis is my first data science term project\nBADS6001 Intro to Data Science\n\nThis model is stock price prediction in SET50 by LSTM and line user can ask stock price from chatbot that connect with Dialogflow. Use flask application to deploy on Heroku. \n"
}
] | 3 |
SirEdvin/TestChat
|
https://github.com/SirEdvin/TestChat
|
edc75ad69afd0c1a156ffd65b31cb528853fa121
|
bba935369945ac5f73b8d6d549574cc2bc1ead9f
|
ac38a69e142d2d856f11882d3a9e33e8218a395f
|
refs/heads/master
| 2016-08-12T12:40:41.463169 | 2015-10-19T11:03:55 | 2015-10-19T11:03:55 | 43,570,653 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7488151788711548,
"alphanum_fraction": 0.7535545229911804,
"avg_line_length": 16.58333396911621,
"blob_id": "b972d62962438cf0df44bf6e815614a6485b5ef0",
"content_id": "0fbe4a039dd7a37db8d28d1847bc548415d55674",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 422,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 24,
"path": "/README.md",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "# TestChat\nSimple real-time chat based on Django and Redis (websocket)\n\n##Requirements\nRedis \n\nPython <= 2.7\n\n##Installation\n\nInstall virtualenv [(instruction)](https://virtualenv.pypa.io/en/latest/installation.html)\n```bash\ngit clone https://github.com/SirEdvin/TestChat.git\ncd TestChat\nvirtualenv .\n. bin/activate\npip install -r requirements.txt\npython manage.py syncdb\n```\n\n##Run\n```bash\npython manage.py runserver\n```\n"
},
{
"alpha_fraction": 0.6774606108665466,
"alphanum_fraction": 0.6855560541152954,
"avg_line_length": 35.671875,
"blob_id": "bdc5f373ac4c0b92f10fd79fb7e92a28a6d605a0",
"content_id": "7df3718792a95d2b8a6d4ef1fff828bea8eb3719",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2347,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 64,
"path": "/TestChat/urls.py",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "\"\"\"TestChat URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nimport logging\nfrom threading import Thread\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom registration.backends.simple.views import RegistrationView\nimport websocket\nfrom TestChat import settings\nfrom util import anonymous_required, authorization_required\nfrom django.contrib.auth import views as auth_views\n\nurlpatterns = [\n url(r'^register/', anonymous_required(RegistrationView.as_view(success_url='chat')), {'success_url': 'chat'},\n name='register'),\n url(r'^/', include('registration.backends.default.urls')),\n url(r'^login', anonymous_required(auth_views.login), {'template_name': 'registration/login.html'},\n name='auth_login'),\n url(r'^logout$', authorization_required(auth_views.logout), {'template_name': 'registration/logout.html'},\n name='auth_logout'),\n url(r'^admin', include(admin.site.urls)),\n url(r'^', TemplateView.as_view(template_name='chat.html'), name='chat'),\n]\n\n\n# WebSocketListener\n\nclass WebSocketListener(Thread):\n \"\"\"\n Listener, that binds to redis server and writes messages to log file\n Works as thread with websocket loop\n \"\"\"\n\n def run(self):\n log = logging.getLogger(\"Server Chat\")\n log.setLevel(logging.INFO)\n\n def on_message(ws, message):\n if message != settings.WS4REDIS_HEARTBEAT:\n log.info(message)\n\n websocket.enableTrace(False)\n ws = websocket.WebSocketApp(\"ws://127.0.0.1:8000/ws/chat?subscribe-broadcast&publish-broadcast&echo\",\n on_message=on_message, )\n log.info(\"WebSocket Log started\")\n ws.run_forever()\n\n\ng = WebSocketListener()\ng.start()\n"
},
{
"alpha_fraction": 0.5575221180915833,
"alphanum_fraction": 0.6814159154891968,
"avg_line_length": 21.600000381469727,
"blob_id": "46bd6f165bb447ad49aca186d3a1e29add3b3c3c",
"content_id": "e2510ba00de25b18b9d038f845b4ce99bf30de2e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 113,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 5,
"path": "/requirements.txt",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "django < 1.9\nredis >= 2.10.3\ndjango-websocket-redis >= 0.4.4\ndjango-registration-redux >= 1.2\nwebsocket >= 0.2.1\n"
},
{
"alpha_fraction": 0.5624103546142578,
"alphanum_fraction": 0.5688665509223938,
"avg_line_length": 34.769229888916016,
"blob_id": "4d3caea11ff6cda51b91a9d5ed711481d6240a9d",
"content_id": "c1e9068e5ca3ced22093620c9662bbb4fb7602bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1394,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 39,
"path": "/static/js/chat.js",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "jQuery(document).ready(function ($) {\n //Init menu active element\n jQuery('#chat_nav').addClass('active');\n var websocketURI = document.getElementById(\"websocketURI\").value;\n var websocketHeartBeat = document.getElementById(\"websocketHeartBeat\").value;\n //Init websocket\n var ws4redis = WS4Redis({\n uri: websocketURI + 'chat?subscribe-broadcast&publish-broadcast&echo',\n receive_message: receiveMessage,\n heartbeat_msg: websocketHeartBeat\n })\n ;\n var log = $('#log');\n\n// send message though the Websocket to the server\n $(\"#message\").keydown(function (event) {\n if (event.keyCode === 13) {\n var messageArea = $(\"#message\");\n event.preventDefault();\n var messageText = messageArea.val().trim();\n if (messageText.length != 0) {\n ws4redis.send_message('[' + new Date().toLocaleString() + ']' + \" \" + $(\"#nickname\").val() + \": \" + messageText);\n }\n messageArea.val(\"\")\n }\n });\n\n $('#send_message').click(function () {\n ws4redis.send_message($('#text_message').val());\n });\n\n// receive a message though the Websocket from the server\n function receiveMessage(msg) {\n if (msg != websocketHeartBeat) {\n log.append('<br/>' + msg);\n log.scrollTop(log.scrollTop() + 25);\n }\n }\n});"
},
{
"alpha_fraction": 0.6349206566810608,
"alphanum_fraction": 0.6349206566810608,
"avg_line_length": 14.75,
"blob_id": "f68626fdfb7ed919741d7d9d8d82befa5309ba4a",
"content_id": "364fd88dd719e861054a5b8e194ce1dc81b7e2ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 4,
"path": "/TestChat/__init__.py",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "import os\n\nif not os.path.exists('logs'):\n os.mkdir('logs')\n"
},
{
"alpha_fraction": 0.6559040546417236,
"alphanum_fraction": 0.6559040546417236,
"avg_line_length": 29.11111068725586,
"blob_id": "0e2e7fe58f6514ec99b480f6ea31773fff4e2235",
"content_id": "3eb799889c036af70c2cd47d6f7475174b5b332e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1084,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 36,
"path": "/TestChat/util.py",
"repo_name": "SirEdvin/TestChat",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import redirect\nfrom TestChat import settings\n\n\ndef anonymous_required(func):\n \"\"\"\n Decorator for django view\n If user isn't anonymous, he will be redirected to some page\n :param func: django view\n :return: anonymous required django view\n \"\"\"\n def as_view(request, *args, **kwargs):\n redirect_to = kwargs.get('next', settings.LOGIN_REDIRECT_URL)\n if request.user.is_authenticated():\n return redirect(redirect_to)\n response = func(request, *args, **kwargs)\n return response\n\n return as_view\n\n\ndef authorization_required(func):\n \"\"\"\n Decorator for django view\n If user is anonymous, he will be redirected to login page\n :param func: django view\n :return: authorization required django view\n \"\"\"\n def as_view(request, *args, **kwargs):\n redirect_to = kwargs.get('next', settings.LOGIN_URL)\n if not request.user.is_authenticated():\n return redirect(redirect_to)\n response = func(request, *args, **kwargs)\n return response\n\n return as_view\n"
}
] | 6 |
thedatamachine/test
|
https://github.com/thedatamachine/test
|
c70ea242d3ab3b8b503154d846b1439fb38c9814
|
246d079f0798401d76b87e62e3bab34a88eb3030
|
83e95ff60cb8dc75942399f49e0493b467f52694
|
refs/heads/master
| 2021-01-18T14:19:42.897739 | 2015-01-07T00:55:36 | 2015-01-07T00:55:36 | 28,832,054 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4985198378562927,
"alphanum_fraction": 0.5458851456642151,
"avg_line_length": 24.590909957885742,
"blob_id": "628e4b75420887b8e59cf9d793cb8ace0c608c30",
"content_id": "caf1fc8c9c7df4559e6c2993e5a2148358a76236",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1689,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 66,
"path": "/pinger.py",
"repo_name": "thedatamachine/test",
"src_encoding": "UTF-8",
"text": "import re\nimport socket\nimport os\nimport urllib2\nimport time\n\n\ndef cls():\n \"\"\"\nclears interpretor window\n \"\"\"\n os.system(['clear', 'cls'][os.name == 'nt'])\n\n\ndef behind_firewall_on():\n try:\n urllib2.urlopen('http://17.209.197.81', timeout=1)\n return True\n except urllib2.URLError as err:\n pass\n return False\n\n\ndef prompt1():\n res = raw_input(\"Cannot reach internal network, press any key to continue or 'q' to quit\\n\")\n if res == \"q\":\n exit()\n else:\n pass\n\ndef mainloop():\n if not behind_firewall_on():\n prompt1()\n ip = raw_input(\"Enter IP Range : \")\n print \"\"\n validip = re.search(\n r'\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b',\n ip, re.IGNORECASE)\n if not validip:\n cls();\n print \"%s is an invalid Range. Example Format xxx.xxx.xx-xx\" % ip\n mainloop();\n extractrange = re.match(r'\\d*.\\d*.\\d*.(\\d{1,3})-(\\d{1,3})', ip, re.IGNORECASE)\n extracttriplet = re.match(r'\\d{1,3}.\\d{1,3}.\\d{1,3}.', ip, re.IGNORECASE)\n triplet = extracttriplet.group() # extracted groups\n range1 = int(extractrange.group(1))\n range2 = int(extractrange.group(2))\n iplist = []\n while range1 <= range2:\n iplist.append(str(triplet) + str(range1))\n range1 += 1\n for i in iplist:\n try:\n print(socket.gethostbyaddr(i))\n except socket.herror as e:\n print \"no connection\"\n res = raw_input(\"Press any key to scan again or 'q' to quit\")\n if res == \"q\":\n exit()\n else:\n cls()\n mainloop();\n\n\ncls();\nmainloop();\n"
}
] | 1 |
splendorklein/project1
|
https://github.com/splendorklein/project1
|
376949f33b6775dc726662baa7fa5e27cc193bdf
|
b5e26b1a695d08adb72155e966a0fb6032cd7160
|
0312120ad12f77f25e7f51eb2f5e91d0b97f1ded
|
refs/heads/master
| 2016-09-13T20:26:28.262748 | 2016-05-07T05:05:50 | 2016-05-07T05:05:50 | 58,106,231 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6222904324531555,
"alphanum_fraction": 0.6397467851638794,
"avg_line_length": 32.62580490112305,
"blob_id": "de01955efe22e7d66e66f042f4f41653f832b751",
"content_id": "8d00013b4c2d166d1286640c739d0576f1bab6b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 5214,
"license_type": "no_license",
"max_line_length": 217,
"num_lines": 155,
"path": "/script.js",
"repo_name": "splendorklein/project1",
"src_encoding": "UTF-8",
"text": "\n\nvar eventOutputContainer = document.getElementById(\"message\");\nvar eventSrc = new EventSource(\"/eventSource\");\n\neventSrc.onmessage = function(e) {\n\tconsole.log(e);\n\teventOutputContainer.innerHTML = e.data;\n};\n\nvar tooltip = d3.select(\"div.tooltip\");\nvar tooltip_title = d3.select(\"#title\");\nvar tooltip_price = d3.select(\"#price\");\n\n\nvar map = L.map('map').setView([22.539029, 114.062076], 16);\n\n//this is the OpenStreetMap tile implementation\n\nL.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {\n\tattribution: '© <a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors'\n}).addTo(map);\n\n//uncomment for Mapbox implementation, and supply your own access token\n\n// L.tileLayer('https://api.tiles.mapbox.com/v4/{mapid}/{z}/{x}/{y}.png?access_token={accessToken}', {\n// \tattribution: 'Map data © <a href=\"http://openstreetmap.org\">OpenStreetMap</a>, Imagery © <a href=\"http://mapbox.com\">Mapbox</a>',\n// \tmapid: 'mapbox.light',\n// \taccessToken: [INSERT YOUR TOKEN HERE!]\n// }).addTo(map);\n\n//create variables to store a reference to svg and g elements\n\n\n\nvar svg_overlay = d3.select(map.getPanes().overlayPane).append(\"svg\");\nvar g_overlay = svg_overlay.append(\"g\").attr(\"class\", \"leaflet-zoom-hide\");\n\nvar svg = d3.select(map.getPanes().overlayPane).append(\"svg\");\nvar g = svg.append(\"g\").attr(\"class\", \"leaflet-zoom-hide\");\n\nfunction projectPoint(lat, lng) {\n\treturn map.latLngToLayerPoint(new L.LatLng(lat, lng));\n}\n\nfunction projectStream(lat, lng) {\n\tvar point = projectPoint(lat,lng);\n\tthis.stream.point(point.x, point.y);\n}\n\nvar transform = d3.geo.transform({point: projectStream});\nvar path = d3.geo.path().projection(transform);\n\nfunction updateData(){\n\n\tvar mapBounds = map.getBounds();\n\tvar lat1 = mapBounds[\"_southWest\"][\"lat\"];\n\tvar lat2 = mapBounds[\"_northEast\"][\"lat\"];\n\tvar lng1 = mapBounds[\"_southWest\"][\"lng\"];\n\tvar lng2 = mapBounds[\"_northEast\"][\"lng\"];\n\n\t// CAPTURE USER INPUT FOR CELL SIZE FROM HTML ELEMENTS\n\tvar cell_size = 25;\n\tvar w = window.innerWidth;\n\tvar h = window.innerHeight;\n\n\t// CAPTURE USER INPUT FOR ANALYSIS TYPE SELECTION\n\tvar checked = document.getElementById(\"interpolation\").checked\n\tvar checked2 = document.getElementById(\"heatmap\").checked\n\t// CAPTURE USER INPUT FOR HEAT MAP 'SPREAD' OR OTHER PARAMETERS\n\tvar spreadvalue = document.getElementById(\"spread\").value\n\t// SEND USER CHOICES FOR ANALYSIS TYPE, CELL SIZE, HEAT MAP SPREAD, ETC. TO SERVER\n\trequest = \"/getData?lat1=\" + lat1 + \"&lat2=\" + lat2 + \"&lng1=\" + lng1 + \"&lng2=\" + lng2 + \"&w=\" + w + \"&h=\" + h + \"&cell_size=\" + cell_size + \"&analysis=\" + checked + \"&heatmap=\" + checked2 + \"&spread=\" + spreadvalue\n\n\tconsole.log(request);\n\n \td3.json(request, function(data) {\n\n\t\t//create placeholder circle geometry and bind it to data\n\t\tvar circles = g.selectAll(\"circle\").data(data.features);\n\n\t\tconsole.log(data);\n\n\t\tcircles.enter()\n\t\t\t.append(\"circle\")\n\t\t\t.on(\"mouseover\", function(d){\n\t\t\t\ttooltip.style(\"visibility\", \"visible\");\n\t\t\t\ttooltip_title.text(d.properties.name);\n\t\t\t\ttooltip_price.text(\"Price: \" + d.properties.price);\n\t\t\t})\n\t\t\t.on(\"mousemove\", function(){\n\t\t\t\ttooltip.style(\"top\", (d3.event.pageY-10)+\"px\")\n\t\t\t\ttooltip.style(\"left\",(d3.event.pageX+10)+\"px\");\n\t\t\t})\n\t\t\t.on(\"mouseout\", function(){\n\t\t\t\ttooltip.style(\"visibility\", \"hidden\");\n\t\t\t})\n\t\t\t// .attr(\"fill\", function(d) { return \"hsl(\" + Math.floor((1-d.properties.priceNorm)*250) + \", 100%, 50%)\"; })\n\t\t;\n\n\t\t// call function to update geometry\n\t\tupdate();\n\t\tmap.on(\"viewreset\", update);\n\n\t\tif ((checked == true) || (checked2 == true)){\n\n\t\t\tvar topleft = projectPoint(lat2, lng1);\n\n\t\t\tsvg_overlay.attr(\"width\", w)\n\t\t\t\t.attr(\"height\", h)\n\t\t\t\t.style(\"left\", topleft.x + \"px\")\n\t\t\t\t.style(\"top\", topleft.y + \"px\");\n\n\t\t\tvar rectangles = g_overlay.selectAll(\"rect\").data(data.analysis);\n\t\t\trectangles.enter().append(\"rect\");\n\n\t\t\trectangles\n\t\t\t\t.attr(\"x\", function(d) { return d.x; })\n\t\t\t\t.attr(\"y\", function(d) { return d.y; })\n\t\t\t\t.attr(\"width\", function(d) { return d.width; })\n\t\t\t\t.attr(\"height\", function(d) { return d.height; })\n\t\t \t.attr(\"fill-opacity\", \".2\")\n\t\t \t.attr(\"fill\", function(d) { return \"hsl(\" + Math.floor((1-d.value)*250) + \", 100%, 50%)\"; });\n\t\t\n\t\t};\n\n\t\t// function to update the data\n\t\tfunction update() {\n\n\t\t\tg_overlay.selectAll(\"rect\").remove()\n\n\t\t\t// get bounding box of data\n\t\t var bounds = path.bounds(data),\n\t\t topLeft = bounds[0],\n\t\t bottomRight = bounds[1];\n\n\t\t var buffer = 50;\n\n\t\t // reposition the SVG to cover the features.\n\t\t svg .attr(\"width\", bottomRight[0] - topLeft[0] + (buffer * 2))\n\t\t .attr(\"height\", bottomRight[1] - topLeft[1] + (buffer * 2))\n\t\t .style(\"left\", (topLeft[0] - buffer) + \"px\")\n\t\t .style(\"top\", (topLeft[1] - buffer) + \"px\");\n\n\t\t g .attr(\"transform\", \"translate(\" + (-topLeft[0] + buffer) + \",\" + (-topLeft[1] + buffer) + \")\");\n\n\t\t // update circle position and size\n\t\t circles\n\t\t \t.attr(\"cx\", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).x; })\n\t\t \t.attr(\"cy\", function(d) { return projectPoint(d.geometry.coordinates[0], d.geometry.coordinates[1]).y; })\n \t\t\t.attr(\"r\", function(d) { return Math.pow(d.properties.price,.3); });\n\t\t};\n\t});\n\n};\n\nupdateData();"
},
{
"alpha_fraction": 0.7172523736953735,
"alphanum_fraction": 0.7172523736953735,
"avg_line_length": 24.08333396911621,
"blob_id": "9e6b900014813baef749260d367a1c5f37a63e2b",
"content_id": "985e785d7f180be5e34826acb9987d5ec7b43b9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 626,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 24,
"path": "/databaseminingbase.py",
"repo_name": "splendorklein/project1",
"src_encoding": "UTF-8",
"text": "from sqlalchemy import Column, ForeignKey, Integer, String, Float\r\nfrom sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy.orm import relationship\r\nfrom sqlalchemy import create_engine\r\n \r\nBase = declarative_base()\r\n\r\nclass RealEstate(Base):\r\n __tablename__ = 'realestate'\r\n\r\n id = Column(Integer, primary_key=True)\r\n title = Column(String, nullable=False)\r\n price = Column(Float, nullable=False)\r\n latitude = Column(Float)\r\n longitude = Column(Float)\r\n\r\n\r\n\r\n\r\n\r\nengine = create_engine('sqlite:////var/www/mywebsite/mywebsite/database/datamining.db')\r\n \r\n\r\nBase.metadata.create_all(engine)\r\n"
}
] | 2 |
zyc0868/Summary-of-HMM
|
https://github.com/zyc0868/Summary-of-HMM
|
2245b73a4e190a933a08e9954ab8c423c40b25f1
|
1a646108e03f7db0c4826d34871382e70f84ae2b
|
ff656c84f31c2a183383043f8cdcb3b038b9222b
|
refs/heads/master
| 2021-07-04T19:14:04.728047 | 2019-11-15T08:26:07 | 2019-11-15T08:26:07 | 218,579,831 | 2 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.8531249761581421,
"alphanum_fraction": 0.862500011920929,
"avg_line_length": 52.33333206176758,
"blob_id": "d52b009dd500e9490b8ecfb6e4a3a835088cb5a8",
"content_id": "a99fee033b57ff4f61e959ec12f0c697190fd646",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 824,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 6,
"path": "/README.md",
"repo_name": "zyc0868/Summary-of-HMM",
"src_encoding": "GB18030",
"text": "# **这是关于隐马尔可夫模型的一些总结**\n##*本项目在理论方面没有太多解释,网上有很多博客去讲解理论知识,但对于实际问题的具体代码并不多,所以本项目旨在为更多的初学者提供代码案例,包括隐马尔可夫模型求解的三个经典问题的代码,仅供学习参考,若对代码有疑惑,或者觉得代码哪些地方有问题可以及时与我联系。*\n\n###在MultiomialHMM文件中,运用了MultiomialHMM函数,求解关于离散型HMM的有关问题,包括:1.已知模型参数和观测序列,求解最大可能的观测序列 2.已知模型参数和观测序列,求解该模型下产生该观测序列的概率 3.已知观测序列,去求解该模型的参数\n\n###在GMMMHMM文件中实现了对独立词的语音识别\n"
},
{
"alpha_fraction": 0.5531803965568542,
"alphanum_fraction": 0.6032325625419617,
"avg_line_length": 30.459016799926758,
"blob_id": "6b7e37274a401819c8a51fe6657bfb45b581daaa",
"content_id": "3894dd797fc827ccd6446793f0d15acd773ec3a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2618,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 61,
"path": "/MultinomialHMM.py",
"repo_name": "zyc0868/Summary-of-HMM",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom hmmlearn import hmm\n\n#——————————初始化隐藏状态,观测序列,开始转移概率,转移概率,发射概率——————————\nhiddenstates = (\"box1\", \"box2\", \"box3\")\nobservations = (\"red\", \"green\", \"blue\")\n\nstart_prob = np.array([0.3,0.4,0.3])\n\ntransmat_prob = np.array([[0.2,0.4,0.4],\n [0.5,0.2,0.3],\n [0.1,0.4,0.5]])\n\nemission_prob = np.array([[0.1,0.3,0.6],\n [0.3,0.5,0.2],\n [0.4,0.4,0.2]])\n\n\n#——————————将参数放入模型中——————————\nn_hiddenstates = len(hiddenstates)\nmodel = hmm.MultinomialHMM(n_components=n_hiddenstates,n_iter=2000)\nmodel.startprob_ = start_prob\nmodel.transmat_ = transmat_prob\nmodel.emissionprob_ = emission_prob\n\n\n#——————————1.求解最可能的观测序列————————————\nseen = np.array([[1],[1],[0]])\n#decode函数得到两个返回值,一个是产生观测序列的对数概率,一个是预测的观测序列\nlogprob, boxs = model.decode(seen) #默认的算法是维比特算法\nprint(\"The ball picked:\", \", \".join(map(lambda x: observations[x], seen.flatten())))\nprint(\"The hidden box\", \", \".join(map(lambda x: hiddenstates[x], boxs)))\n\n#predict函数返回的直接是预测的观测序列\nboxs_ = model.predict(seen)\nprint(\"The ball picked:\", \", \".join(map(lambda x: observations[x], seen.flatten())))\nprint(\"The hidden box\", \", \".join(map(lambda x: hiddenstates[x], boxs_)))\n\n#decode,predict都属于解码问题,即一直hmm模型所需的参数和观测序列,求解最大可能的状态序列\n#用到了基于动态规划的维比特算法\n\n\n#——————————2.求解得到当前观测序列的概率————————————\nprint (model.score(seen))\n#score属于计算得到当前观测序列的概率,用到了向前向后算法\n\n\n#——————————3.构建一个新模型,求解模型参数——————————\nmodel2 = hmm.MultinomialHMM(n_components=n_hiddenstates, n_iter=2000)\n\nobservations2 = np.array([[2,1,2,1,2,2,1,2,0,2],\n [0,2,0,1,0,1,1,1,2,1],\n [0,1,0,2,0,1,0,1,2,1]])\n\n\n#将得到的观测矩阵输入到模型中\nmodel2.fit(observations2)\nboxs2 = model2.predict(seen)\nprint(\"The ball picked:\", \", \".join(map(lambda x: observations[x], seen.flatten())))\nprint(\"The hidden box\", \", \".join(map(lambda x: hiddenstates[x], boxs2)))\n#参数学习的问题用到了类似于EM算法的鲍姆-维奇算法"
},
{
"alpha_fraction": 0.6223776340484619,
"alphanum_fraction": 0.6270396113395691,
"avg_line_length": 27.66666603088379,
"blob_id": "093b5eab08450eda23041cca1c52cb2d2ea59ef4",
"content_id": "bc0f9a620190f75eef9e5179bc793044c2711088",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 429,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 15,
"path": "/test.py",
"repo_name": "zyc0868/Summary-of-HMM",
"src_encoding": "UTF-8",
"text": "import joblib\nimport os\ndef data_process(file):\n datas={}\n labels={}\n for root, dirs, files in os.walk(file):\n for file in files:\n dataname=file.strip('.wav')\n datas[dataname] = os.sep.join((root,file))\n labels[dataname] = dataname.split('-')[0]\n return datas , labels\n\nm=joblib.load('models.pkl')\ntestdatas ,testlabels = data_process('test1_data')\nm.test(testdatas,testlabels)"
},
{
"alpha_fraction": 0.5500794649124146,
"alphanum_fraction": 0.5696873068809509,
"avg_line_length": 30.915254592895508,
"blob_id": "68f4459a6aa3a59ef1eb360849bc4b6aa591e73b",
"content_id": "aadbaca4d249bf4b64252b7eda969b2745de930f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4502,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 118,
"path": "/骨传导信号识别.py",
"repo_name": "zyc0868/Summary-of-HMM",
"src_encoding": "UTF-8",
"text": "import scipy.io as sio\nfrom hmmlearn import hmm\nimport numpy as np\nfrom python_speech_features import mfcc\nimport joblib\nimport matplotlib.pyplot as plt\n\n#——————————制作音源文件与标签的对应对应——————————\n\n#data['originalData'][i][0][0] i从0到19表示数字0,20-39表示数字1依次类推\n\ndef data_process():\n data = sio.loadmat('originalData.mat')\n datas={}\n labels={}\n for i in range(196):\n print(i)\n data1 = np.array(data['originalData'][i][0][0])\n datas[i] = data1\n labels[i] = int(i/20)\n return datas , labels\n\n\n#——————————获取MFCC特征——————————\ndef get_mfcc_feat(data):\n # if len(data) % 3:\n # pro_data = data[:-(len(data) % 3)].reshape(-1,3)\n # else:\n # pro_data = data.reshape(-1,3)\n pro_data = data.reshape(-1)\n mfcc_feat = mfcc(pro_data, samplerate=1200, nfft=256)\n return mfcc_feat\n\n#——————————构造模型——————————\nclass Model():\n #模型参数,由于是独立词识别,且WAV文件都是同一个人录制,所以n_components = 1,表示每个模型隐藏状态是1\n #n_mix5表示混合的高斯分布由几个高斯分布组成,一般取4或5\n #covariance_type='diag' 表示协方差矩阵的类型\n #n_iter=2000,训练2000次\n def __init__(self,labelset = None, n_components = 3,n_mix=4, covariance_type='diag', n_iter=2000,each_number=20,):\n super(Model,self).__init__()\n self.labelset = labelset\n self.label_num = len(labelset)\n self.each_number = each_number\n self.setrange = self.label_num*self.each_number\n self.n_components = n_components\n self.n_mix = n_mix\n self.covariance_type = covariance_type\n self.n_iter = n_iter\n #创建模型列表,数量对应独立词的数量\n self.models=[]\n\n#——————————生成模型——————————\n def get_models(self):\n for i in range(self.label_num):\n model = hmm.GMMHMM(n_components=self.n_components, n_mix=self.n_mix,covariance_type=self.covariance_type, n_iter=self.n_iter)\n self.models.append(model)\n\n#——————————训练模型——————————\n#遍历整个数据集,若数据集的对应的标签的值与当前模型匹配,则将该数据的MFCC特征放入该模型中\n def train(self,datas = None, labels = None):\n #for i in range(self.setrange):\n for i in range(196):\n model = self.models[int(i/self.each_number)]\n print(i,int(i/self.each_number))\n print(\"labels\",labels[i],\"labelset[int(i/self.each_number)]\",self.labelset[int(i/self.each_number)])\n if labels[i] == self.labelset[int(i/self.each_number)]:\n mfcc_feat = get_mfcc_feat(datas[i])\n model.fit(mfcc_feat)\n print(\"scess\")\n# ——————————测试模型——————————\n#测试每个数据在所有模型中的得分情况,最后将得分最高的模型对应的标签值作为预测值\n def test(self, datas=None, labels = None):\n real = []\n predict = []\n #for j in range(len(datas)):\n for j in range(196):\n scores=[]\n for i in range(self.label_num):\n model = self.models[i]\n mfcc_feat = get_mfcc_feat(datas[j])\n score = model.score(mfcc_feat)\n scores.append(score)\n index = scores.index(max(scores))\n predict.append(self.labelset[index])\n real.append(labels[j])\n\n accuracy = 0\n print(\"predict:\", predict)\n print(\"real\", real)\n for i in range(len(real)):\n if real[i] == predict[i]:\n accuracy += 1\n print(\"识别率: \", \"percent: {:.2%}\".format(accuracy / len(real)))\n\n def save(self, path=\"models.pkl\"):\n joblib.dump(self.models, path)\n\n\n def load(self, path=\"models.pkl\"):\n self.models = joblib.load(path)\n\n\n\nif __name__ == \"__main__\":\n labelset=[0,1,2,3,4,5,6,7,8,9]\n datas , labels = data_process()\n testdatas ,testlabels = data_process()\n\n m = Model(labelset)\n m.get_models()\n m.train(datas,labels)\n m.save()\n m.load()\n print(\"训练数据的识别:\")\n m.test(datas,labels)\n print(\"测试数据的识别:\")\n m.test(testdatas,testlabels)\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5611196756362915,
"alphanum_fraction": 0.5744735598564148,
"avg_line_length": 30.338708877563477,
"blob_id": "a0d9e1abe619797ede534b4c760592fc045ddf3c",
"content_id": "3a32a057e3e0512852cc97cd38fd8b8e78a76e21",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4752,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 124,
"path": "/GMM-HMM.py",
"repo_name": "zyc0868/Summary-of-HMM",
"src_encoding": "UTF-8",
"text": "from hmmlearn import hmm\nimport numpy as np\nimport os\n\nfrom scipy.io import wavfile\nfrom python_speech_features import mfcc\nimport joblib\nimport matplotlib.pyplot as plt\n#——————————制作音源文件与标签的对应对应——————————\n#对于同一数据,datas 与 labels 对应的键是相同的,datas的值是对应文件的路径,labels的值是该数据的标签\ndef data_process(file):\n datas={}\n labels={}\n for root, dirs, files in os.walk(file):\n for file in files:\n dataname=file.strip('.wav')\n datas[dataname] = os.sep.join((root,file))\n #文件格式是x-n,x表示该数据的内容,n表示该数据的第几个训练样本\n #如,2-5表示,第五遍说2的音频文件\n labels[dataname] = dataname.split('-')[0]\n return datas , labels\n\n\n\n#——————————获取MFCC特征——————————\ndef get_mfcc_feat(file):\n fs , audio = wavfile.read(file)\n #fs 为 44100Hz\n print(audio.shape)\n mfcc_feat=mfcc(audio,samplerate=(fs/2),nfft=1024)\n print(mfcc_feat.shape)\n plt.plot(audio)\n plt.show()\n\n plt.plot(mfcc_feat)\n #plt.imshow(mfcc_feat.T, origin='lower')\n #plt.figure(figsize=(10, 4))\n #librosa.display.specshow(feat,\n #y_axis='mel', fmax=8000, x_axis='time')\n # plt.colorbar(format='%+2.0f dB')\n # plt.title('Mel spectrogram')\n # plt.tight_layout()\n #plt.show()\n return mfcc_feat\n\n#——————————构造模型——————————\nclass Model():\n #模型参数,由于是独立词识别,且WAV文件都是同一个人录制,所以n_components = 1,表示每个模型隐藏状态是1\n #n_mix5表示混合的高斯分布由几个高斯分布组成,一般取4或5\n #covariance_type='diag' 表示协方差矩阵的类型\n #n_iter=2000,训练2000次\n def __init__(self,labelset = None, n_components = 1,n_mix=4, covariance_type='diag', n_iter=2000):\n super(Model,self).__init__()\n self.labelset = labelset\n self.label_num = len(labelset)\n self.n_components = n_components\n self.n_mix = n_mix\n self.covariance_type = covariance_type\n self.n_iter = n_iter\n #创建模型列表,数量对应独立词的数量\n self.models=[]\n\n#——————————生成模型——————————\n def get_models(self):\n for i in range(self.label_num):\n model = hmm.GMMHMM(n_components=self.n_components, n_mix=self.n_mix,covariance_type=self.covariance_type, n_iter=self.n_iter)\n self.models.append(model)\n\n#——————————训练模型——————————\n#遍历整个数据集,若数据集的对应的标签的值与当前模型匹配,则将该数据的MFCC特征放入该模型中\n def train(self,datas = None, labels = None):\n for dataname in datas:\n for i in range(self.label_num):\n model = self.models[i]\n if labels[dataname] == self.labelset[i]:\n mfcc_feat = get_mfcc_feat(datas[dataname])\n model.fit(mfcc_feat)\n\n# ——————————测试模型——————————\n#测试每个数据在所有模型中的得分情况,最后将得分最高的模型对应的标签值作为预测值\n def test(self, datas=None, labels = None):\n real = []\n predict = []\n for dataname in datas:\n scores=[]\n for i in range(self.label_num):\n model = self.models[i]\n mfcc_feat = get_mfcc_feat(datas[dataname])\n score = model.score(mfcc_feat)\n scores.append(score)\n index = scores.index(max(scores))\n predict.append(self.labelset[index])\n real.append(labels[dataname])\n\n accuracy = 0\n print(\"predict:\",predict)\n print(\"real\",real)\n for i in range(len(real)):\n if real[i] == predict [i]:\n accuracy += 1\n print(\"识别率: \",\"percent: {:.2%}\".format(accuracy/len(real)))\n\n def save(self, path=\"models.pkl\"):\n joblib.dump(self.models, path)\n\n\n def load(self, path=\"models.pkl\"):\n self.models = joblib.load(path)\n\n\nif __name__ == \"__main__\":\n labelset=[ '1' , '2' , '3' , '4' , '5']\n datas , labels = data_process('train1_data')\n testdatas ,testlabels = data_process('test1_data')\n\n m = Model(labelset)\n m.get_models()\n m.train(datas,labels)\n m.save()\n m.load()\n print(\"训练数据的识别:\")\n m.test(datas,labels)\n print(\"测试数据的识别:\")\n m.test(testdatas,testlabels)\n\n\n\n\n\n\n\n\n"
}
] | 5 |
lbryio/lbry-osx-app
|
https://github.com/lbryio/lbry-osx-app
|
15965f73722980a392f36f460fdf5934dbafdc7f
|
21be499ddb1da97c2a0cdaebd6a71786526eef46
|
95ebe06ccec679f87808c9dbd88e012782c68e2b
|
refs/heads/master
| 2016-06-05T13:59:04.759354 | 2016-05-30T20:47:10 | 2016-05-30T20:47:10 | 55,274,384 | 0 | 1 | null | 2016-04-02T02:47:41 | 2016-04-02T02:49:42 | 2016-05-30T20:47:10 |
Python
|
[
{
"alpha_fraction": 0.648668110370636,
"alphanum_fraction": 0.6594672203063965,
"avg_line_length": 35.07792282104492,
"blob_id": "ef30b045c92471653213a004b2219aaccbde0d1d",
"content_id": "56f02846faa6def0b83ca4d7726ac14d04c00620",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2778,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 77,
"path": "/lbrygui/LBRYApp.py",
"repo_name": "lbryio/lbry-osx-app",
"src_encoding": "UTF-8",
"text": "import AppKit\nimport webbrowser\nimport sys\nimport logging\nimport socket\nimport platform\n\nfrom PyObjCTools import AppHelper\n\nfrom twisted.internet import reactor\nfrom twisted.web import server\n\nfrom lbrynet.lbrynet_daemon.LBRYDaemonServer import LBRYDaemonServer\nfrom lbrynet.conf import API_PORT, API_INTERFACE, ICON_PATH, APP_NAME\nfrom lbrynet.conf import UI_ADDRESS\n\nif platform.mac_ver()[0] >= \"10.10\":\n from LBRYNotify import LBRYNotify\n\nlog = logging.getLogger(__name__)\n\nREMOTE_SERVER = \"www.google.com\"\n\n\ndef test_internet_connection():\n try:\n host = socket.gethostbyname(REMOTE_SERVER)\n s = socket.create_connection((host, 80), 2)\n return True\n except:\n return False\n\n\nclass LBRYDaemonApp(AppKit.NSApplication):\n def finishLaunching(self):\n self.connection = False\n statusbar = AppKit.NSStatusBar.systemStatusBar()\n self.statusitem = statusbar.statusItemWithLength_(AppKit.NSVariableStatusItemLength)\n self.icon = AppKit.NSImage.alloc().initByReferencingFile_(ICON_PATH)\n self.icon.setScalesWhenResized_(True)\n self.icon.setSize_((20, 20))\n self.statusitem.setImage_(self.icon)\n self.menubarMenu = AppKit.NSMenu.alloc().init()\n self.open = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(\"Open\", \"openui:\", \"\")\n self.menubarMenu.addItem_(self.open)\n self.quit = AppKit.NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(\"Quit\", \"replyToApplicationShouldTerminate:\", \"\")\n self.menubarMenu.addItem_(self.quit)\n self.statusitem.setMenu_(self.menubarMenu)\n self.statusitem.setToolTip_(APP_NAME)\n\n\n if test_internet_connection():\n if platform.mac_ver()[0] >= \"10.10\":\n LBRYNotify(\"Starting LBRY\")\n else:\n if platform.mac_ver()[0] >= \"10.10\":\n LBRYNotify(\"LBRY needs an internet connection to start, try again when one is available\")\n sys.exit(0)\n\n # if not subprocess.check_output(\"git ls-remote https://github.com/lbryio/lbry-web-ui.git | grep HEAD | cut -f 1\",\n # shell=True):\n # LBRYNotify(\n # \"You should have been prompted to install xcode command line tools, please do so and then start LBRY\")\n # sys.exit(0)\n\n lbry = LBRYDaemonServer()\n d = lbry.start()\n d.addCallback(lambda _: webbrowser.open(UI_ADDRESS))\n reactor.listenTCP(API_PORT, server.Site(lbry.root), interface=API_INTERFACE)\n\n def openui_(self, sender):\n webbrowser.open(UI_ADDRESS)\n\n def replyToApplicationShouldTerminate_(self, shouldTerminate):\n if platform.mac_ver()[0] >= \"10.10\":\n LBRYNotify(\"Goodbye!\")\n reactor.stop()\n"
},
{
"alpha_fraction": 0.6974489688873291,
"alphanum_fraction": 0.7096938490867615,
"avg_line_length": 29.625,
"blob_id": "311a06dd184abfc0cea36a131b7000a6cf1ebbdf",
"content_id": "d4141326a77d100bbe5bd054f22e38e86fc4bc09",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 1960,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 64,
"path": "/setup_app.sh",
"repo_name": "lbryio/lbry-osx-app",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nset -o errexit\nset -o xtrace\n\ndest=`pwd`\ntmp=\"${dest}/build\"\n\nrm -rf build dist LBRY.app\n\nmkdir -p $tmp\ncd $tmp\n\necho \"Updating lbrynet\"\nif [ -z ${TRAVIS_BUILD_DIR+x} ]; then\n # building locally\n git clone --depth 1 http://github.com/lbryio/lbry.git\n cd lbry\n LBRY=\"${tmp}/lbry\"\nelse\n # building on travis\n cd ${TRAVIS_BUILD_DIR}\n LBRY=${TRAVIS_BUILD_DIR}\nfi\npython setup.py install\necho \"Building URI Handler\"\nrm -rf build dist\npython setup_uri_handler.py py2app\n\necho \"Signing URI Handler\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${LBRY}/dist/LBRYURIHandler.app/Contents/Frameworks/Python.framework/Versions/2.7\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${LBRY}/dist/LBRYURIHandler.app/Contents/MacOS/python\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${LBRY}/dist/LBRYURIHandler.app/Contents/MacOS/LBRYURIHandler\"\ncodesign -vvvv \"${LBRY}/dist/LBRYURIHandler.app\"\n\ncd $dest\npython setup.py py2app &>/dev/null\n\necho \"Moving in correct libgmp\"\nrm \"${dest}/dist/LBRY.app/Contents/Frameworks/libgmp.10.dylib\"\ncp \"${dest}/libgmp.10.dylib\" \"${dest}/dist/LBRY.app/Contents/Frameworks\"\n\necho \"Removing i386 libraries\"\n\nremove_arch () {\n lipo -output build/lipo.tmp -remove \"$1\" \"$2\" && mv build/lipo.tmp \"$2\"\n}\nfor i in dist/LBRY.app/Contents/Resources/lib/python2.7/lib-dynload/* ; do\n remove_arch i386 ${i}\ndone\n\necho \"Moving LBRYURIHandler.app into LBRY.app\"\nmv \"${LBRY}/dist/LBRYURIHandler.app\" \"${dest}/dist/LBRY.app/Contents/Resources\"\n\necho \"Signing LBRY.app\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${dest}/dist/LBRY.app/Contents/Frameworks/Python.framework/Versions/2.7\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${dest}/dist/LBRY.app/Contents/Frameworks/libgmp.10.dylib\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${dest}/dist/LBRY.app/Contents/MacOS/python\"\ncodesign -s \"${LBRY_DEVELOPER_ID}\" -f \"${dest}/dist/LBRY.app/Contents/MacOS/LBRY\"\ncodesign -vvvv \"${dest}/dist/LBRY.app\"\n\nrm -rf $tmp\nmv dist/LBRY.app LBRY.app\nrm -rf dist\n"
},
{
"alpha_fraction": 0.7150092124938965,
"alphanum_fraction": 0.7265193462371826,
"avg_line_length": 33.492061614990234,
"blob_id": "ec3ebbe12328af564da199f5e315bad7245d9d6e",
"content_id": "59828f6b409c657f02d8b518336e5f221d174e53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2172,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 63,
"path": "/build_app.sh",
"repo_name": "lbryio/lbry-osx-app",
"src_encoding": "UTF-8",
"text": "dest=`pwd`\ntmp=\"${dest}/build\"\nid=`cat id.conf`\n\nrm -rf build dist LBRY.app\n\nmkdir -p $tmp\ncd $tmp\n\necho \"Updating lbryum\"\ngit clone --depth 1 http://github.com/lbryio/lbryum.git\ncd lbryum\npython setup.py install &>/dev/null\ncd ..\necho \"Updating lbrynet\"\ngit clone --depth 1 -b development http://github.com/lbryio/lbry.git\ncd lbry\npython setup.py install &>/dev/null\n\ncd $dest\necho \"Building URI Handler\"\npython setup_uri_handler.py py2app &>/dev/null\n\necho \"Signing URI Handler\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"dist/LBRYURIHandler.app/Contents/Frameworks/Python.framework/Versions/2.7\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"dist/LBRYURIHandler.app/Contents/MacOS/python\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"dist/LBRYURIHandler.app/Contents/MacOS/LBRYURIHandler\"\ncodesign -vvvv \"dist/LBRYURIHandler.app\"\nmv \"dist/LBRYURIHandler.app\" \"LBRYURIHandler.app\"\nrm -rf build dist\n\necho \"Building app\"\npython setup_app.py py2app &>/dev/null\n\necho \"Moving in correct libgmp\"\nrm \"${dest}/dist/LBRY.app/Contents/Frameworks/libgmp.10.dylib\"\ncp \"${dest}/libgmp.10.dylib\" \"${dest}/dist/LBRY.app/Contents/Frameworks\"\n\necho \"Removing i386 libraries\"\n\nremove_arch () {\n lipo -output build/lipo.tmp -remove \"$1\" \"$2\" && mv build/lipo.tmp \"$2\"\n}\nfor i in dist/LBRY.app/Contents/Resources/lib/python2.7/lib-dynload/* ; do\n #remove_arch ppc ${i}\n remove_arch i386 ${i}\ndone\n\necho \"Moving LBRYURIHandler.app into LBRY.app\"\nmv \"${dest}/LBRYURIHandler.app\" \"${dest}/dist/LBRY.app/Contents/Resources\"\n\necho \"Signing LBRY.app\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"${dest}/dist/LBRY.app/Contents/Frameworks/Python.framework/Versions/2.7\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"${dest}/dist/LBRY.app/Contents/Frameworks/libgmp.10.dylib\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"${dest}/dist/LBRY.app/Contents/MacOS/python\"\ncodesign -s \"Developer ID Application: LBRY Inc (${id})\" -f \"${dest}/dist/LBRY.app/Contents/MacOS/LBRY\"\ncodesign -vvvv \"${dest}/dist/LBRY.app\"\n\nrm -rf $tmp\nmv dist/LBRY.app LBRY.app\nrm -rf dist\n\nchown -R ${SUDO_USER} LBRY.app"
},
{
"alpha_fraction": 0.6056782603263855,
"alphanum_fraction": 0.6072555184364319,
"avg_line_length": 20.89655113220215,
"blob_id": "7f104ead61b04b14644fe58d5f87c6565085efed",
"content_id": "f6d2a91459d1bcf3c8a1daaffc8eee68cd82cf23",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 634,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 29,
"path": "/setup_app.py",
"repo_name": "lbryio/lbry-osx-app",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\nimport os\nfrom setuptools import setup\nfrom lbrynet.conf import PROTOCOL_PREFIX, APP_NAME, ICON_PATH\nimport sys\n\nAPP = [os.path.join('lbrygui', 'main.py')]\nDATA_FILES = []\nDATA_FILES.append('app.icns')\n\nOPTIONS = {\n # 'argv_emulation': True,\n 'iconfile': ICON_PATH,\n 'plist': {\n 'CFBundleIdentifier': 'io.lbry.LBRY',\n 'LSUIElement': True,\n },\n 'packages': ['lbrynet', 'lbryum', 'requests', 'unqlite', 'certifi',\n 'pkg_resources', 'json', 'jsonrpc', 'seccure',],\n}\n\n\nsetup(\n name=APP_NAME,\n app=APP,\n options={'py2app': OPTIONS},\n data_files=DATA_FILES,\n)"
}
] | 4 |
alpiii/ftp-downloader
|
https://github.com/alpiii/ftp-downloader
|
03a33a21146b98007bf4ea2cabf0a4d93b5b0eb4
|
0d97b0ef13ee9000284f2a1ebe287e3b23eda72d
|
1c0103068e16bbdc61a44fa21e06ead0a9318635
|
refs/heads/master
| 2021-01-01T20:22:51.158309 | 2016-02-02T19:41:05 | 2016-02-02T19:41:05 | 41,698,936 | 1 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7773109078407288,
"alphanum_fraction": 0.7773109078407288,
"avg_line_length": 25.44444465637207,
"blob_id": "7a72a6f67eb6ab02808c635bec7af8e3b5e54588",
"content_id": "11a9b0d0abf358b283430f5fee1dba5bbb4a0454",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 238,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 9,
"path": "/README.md",
"repo_name": "alpiii/ftp-downloader",
"src_encoding": "UTF-8",
"text": "# ftp-downloader\n\nDownloads the files in an FTP server.\n\nAll the files in FTP server or in specified folder can be downloaded. \n\nYou can use this code either in Windows or others operating systems. \n\nA small example is explained in code.\n"
},
{
"alpha_fraction": 0.5344594717025757,
"alphanum_fraction": 0.537162184715271,
"avg_line_length": 38.29203414916992,
"blob_id": "0d0e97a762072ac98b97cdfd5e8255feaa8e920d",
"content_id": "9e06174e2a475521730479c54ecfd548b795212f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8880,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 226,
"path": "/FTPDownloader.py",
"repo_name": "alpiii/ftp-downloader",
"src_encoding": "UTF-8",
"text": "from ftplib import FTP\nfrom ftplib import error_perm\nimport os\nimport sys\n\n\nclass DownloadError:\n\n def __init__(self, path, error, file_directory):\n \"\"\"\n Create an instance of this class if an error occures while downloading.\n :param path: File/folder path which reasoned error.\n :param error: Error explanation.\n :param file_directory: 'f' for file, 'd' for folder.\n :return: None\n \"\"\"\n self.path = path\n self.error = error\n self.file_directory = file_directory\n\n\nclass FTPDownloader:\n\n def __init__(self):\n \"\"\"\n FTP Downloader class that establishes connection to the FTP server.\n Downloads all the files in the current folder\n (and sub folders if specified).\n :return: None\n \"\"\"\n self.connection_status = 0 # 1 connected, 0 not connected\n self.file_count = 0 # file count downloaded successfully\n self.ftp = None # FTP class object\n self.error_list = [] # List contains DownloadError class objects.\n\n def open_connection(self, url, user_name=\"\", password=\"\"):\n \"\"\"\n Establishes connection to the FTP server with username and password\n :param url: FTP server address, do not add \"ftp://\" to beginning.\n :param user_name: Username for FTP server, leave blank if there is not.\n :param password: Password for FTP server, leave blank if there is not.\n :return: Returns True if connection is established successfully.\n \"\"\"\n try:\n self.ftp = FTP(url)\n if user_name == \"\" or password == \"\":\n # if FTP server is public, there is no need to use username\n # and password parameters\n self.ftp.login()\n else:\n self.ftp.login(user_name, password)\n self.connection_status = 1\n # connection established successfully to the server.\n return True\n except error_perm:\n print sys.exc_info()[1]\n return False\n except:\n print sys.exc_info()[1]\n return False\n\n def close_connection(self):\n \"\"\"\n Closes connection to the FTP server\n :return: None\n \"\"\"\n if not isinstance(self.ftp, type(None)):\n self.ftp.close()\n self.connection_status = 0\n\n def get_file_list(self):\n \"\"\"\n Gets file list in the current working directory at FTP server.\n :return: File list in current directory.\n \"\"\"\n files = []\n\n def dir_callback(line):\n items = line.split()\n if items[0][0] != 'd': # not 'd' if item is file\n # ninth (index 8) and later elements creates file name\n # joining with ' ', if file name has blank space\n files.append(' '.join(items[8:]))\n\n self.ftp.dir(dir_callback)\n return files\n\n def get_folder_list(self):\n \"\"\"\n Gets folder list in the current working directory at FTP server.\n :return: Folder list in current directory.\n \"\"\"\n folders = []\n\n def dir_callback(line):\n items = line.split()\n if items[0][0] == 'd': # 'd' if item is folder\n # ninth (index 8) and later elements creates folder name\n # joining with ' ', if folder name has blank space\n folders.append(' '.join(items[8:]))\n\n self.ftp.dir(dir_callback)\n return folders\n\n def download_one_file(self, source_path):\n \"\"\"\n Downloads file to the current OS directory\n :param source_path: File path at FTP server\n :return: None\n \"\"\"\n file_name = os.path.basename(source_path)\n try:\n with open(file_name, \"wb\") as file:\n self.ftp.retrbinary('RETR %s' % source_path, file.write)\n # file downloaded successfully, increasing file count by 1\n self.file_count += 1\n print 'File copied : %s' % source_path\n except:\n os.remove(file_name)\n self.error_list.append(DownloadError(source_path,\n sys.exc_info()[1], 'f'))\n print 'Error occurred : %s' % source_path\n\n def download_all_files(self, target_path, source_path, sub_folders):\n \"\"\"\n Browse through folders and downloads files in each one.\n :param target_path: Folder path at local machine to save files\n :param source_path: Folder path at FTP server\n :param sub_folders: if 'R', this method works recursively and downloads\n all the files in all directories. if not, files will be downloaded\n only in 'source_path'.\n :return: None\n \"\"\"\n try:\n # changing working directory at FTP server\n self.ftp.cwd(source_path)\n # changing working directory in local machine\n os.chdir(target_path)\n files = self.get_file_list()\n for file in files: # download each file in current folder\n if source_path == '/': # if root folder\n self.download_one_file(source_path + file)\n else:\n self.download_one_file(source_path + '/' + file)\n if sub_folders == 'R':\n folders = self.get_folder_list()\n for folder in folders:\n # won't work for parent folders\n if folder not in [\".\", \"..\"]:\n if source_path == '/':\n source_path = ''\n os.chdir(target_path)\n if not os.path.exists(folder):\n os.mkdir(folder)\n if os.name == 'nt':\n self.download_all_files(\n target_path + \"\\\\\" + folder,\n source_path + \"/\" + folder,\n sub_folders)\n else:\n self.download_all_files(\n target_path + \"/\" + folder,\n source_path + \"/\" + folder,\n sub_folders)\n except:\n self.error_list.append(DownloadError(source_path,\n sys.exc_info()[1], 'd'))\n\n def start_downloading(self, target_path, source_path='/', sub_folders='R'):\n \"\"\"\n Preparing variables to start download.\n :param target_path: Folder path at local machine to save files\n :param source_path: Folder path at FTP server\n :param sub_folders: if 'R', this method works recursively and downloads\n all the files in all directories. if not, files will be\n downloaded only in 'source_path'.\n :return: None\n \"\"\"\n if self.connection_status == 1:\n del self.error_list[:]\n # clears error list, it might contain\n # elements from last download operation\n self.file_count = 0\n self.download_all_files(target_path, source_path, sub_folders)\n if self.file_count == 0:\n print '\\nNothing downloaded!\\n'\n else:\n print '\\n%d files downloaded successfully!\\n' % self.file_count\n return self.error_list\n else:\n print 'A connection to FTP server must be established first.'\n\nif __name__ == \"__main__\":\n\n # EXAMPLE\n downloader = FTPDownloader()\n # if you will use username and password, you should\n # change if condition like below.\n # if downloader.open_connection(\"ftp.cs.brown.edu\",\n # \"your_username\", \"your_password\"):\n if downloader.open_connection(\"ftp.cs.brown.edu\", \"\", \"\"):\n\n # if you're using Windows, you should\n # send target_path parameter like that :\n # error_list = downloader.start_downloading(\n # 'C:\\\\Users\\\\HasanAlper\\\\Desktop\\\\ftp_downloads',\n # '/u/asf/datasets')\n # if you're not using Windows\n error_list = downloader.start_downloading(\n '/Users/alpiii/Desktop/ftp_downloads',\n '/u/asf/datasets')\n # if you don't want to download files in sub folders,\n # you can use example below.\n # last parameter must be different from 'R'\n # error_list = downloader.start_downloading(\n # '/Users/alpiii/Desktop/ftp_downloads',\n # '/u/asf/datasets', 'A')\n\n if len(error_list) > 0:\n print '%d error/errors found!' % len(error_list)\n for error in error_list:\n print error.path + ' -> ' + str(error.error)\n\n downloader.close_connection()\n else:\n print \"Connection couldn't be established.\"\n"
}
] | 2 |
daniel-kanchev/creditagricole
|
https://github.com/daniel-kanchev/creditagricole
|
db923e5544af9c42ea99c3c64bc23ed8c05474c8
|
d0e4f54560021d0dfafffc68383c08b1f36de94e
|
5fdc83750788ac4c0d2a06502e2d597013374373
|
refs/heads/main
| 2023-02-28T04:48:00.541056 | 2021-02-04T12:11:29 | 2021-02-04T12:11:29 | 335,943,109 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6900584697723389,
"alphanum_fraction": 0.6959064602851868,
"avg_line_length": 13.333333015441895,
"blob_id": "a51c38bdad5893c3b1a492eb15fc8af1b608a796",
"content_id": "f84d7fb3d1ed215f39d4e4c499f30b233d855b7a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 171,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 12,
"path": "/README.md",
"repo_name": "daniel-kanchev/creditagricole",
"src_encoding": "UTF-8",
"text": "URL: https://www.ca-cib.com/pressroom/news\n\n Spider name: credit\n\nNotes:\n- Only gets last 7 articles due to AJAX\n\nDB Schema:\n- title\n- date: yyyy/mm/dd\n- link\n- content"
},
{
"alpha_fraction": 0.7446808218955994,
"alphanum_fraction": 0.757446825504303,
"avg_line_length": 28.375,
"blob_id": "7a31e9c199f3b44e0d47a71fd79c61625824892a",
"content_id": "4b640f97fbde424a7a69bb000a83efe32e82597c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 235,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 8,
"path": "/creditagricole/settings.py",
"repo_name": "daniel-kanchev/creditagricole",
"src_encoding": "UTF-8",
"text": "BOT_NAME = 'creditagricole'\nSPIDER_MODULES = ['creditagricole.spiders']\nNEWSPIDER_MODULE = 'creditagricole.spiders'\nROBOTSTXT_OBEY = True\nLOG_LEVEL = 'WARNING'\nITEM_PIPELINES = {\n 'creditagricole.pipelines.DatabasePipeline': 300,\n}\n"
}
] | 2 |
ygortavela/citadorbot
|
https://github.com/ygortavela/citadorbot
|
15a9d961ab1c470d3d54258da1886f4ab723ed66
|
fcf360561bcaffcfbe9b72504893c9f5d03a320a
|
e4170188f96538fad76d975dabee8ff92ee7e15d
|
refs/heads/master
| 2020-09-03T16:36:43.226777 | 2019-11-04T18:31:09 | 2019-11-04T18:31:09 | 219,510,355 | 0 | 0 |
MIT
| 2019-11-04T13:39:50 | 2019-11-04T13:23:45 | 2019-11-04T13:23:43 | null |
[
{
"alpha_fraction": 0.5868263244628906,
"alphanum_fraction": 0.6047903895378113,
"avg_line_length": 15.699999809265137,
"blob_id": "44c6827010f26038535d73c0aa61d5c01b67203d",
"content_id": "01020e638a42949f6f64171c240c5538aa4ce805",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 167,
"license_type": "permissive",
"max_line_length": 42,
"num_lines": 10,
"path": "/wordwrap.py",
"repo_name": "ygortavela/citadorbot",
"src_encoding": "UTF-8",
"text": "import sys\nimport textwrap\n\n\ndef wrap(text):\n result = textwrap.wrap(text, width=30)\n print('\\n'.join(result))\n\nif __name__ == '__main__':\n wrap(sys.argv[1])\n"
},
{
"alpha_fraction": 0.5702381134033203,
"alphanum_fraction": 0.598809540271759,
"avg_line_length": 14.55555534362793,
"blob_id": "1f7f7b855c4108970869c68ca044650036797e82",
"content_id": "8b98c8172fb29ba436adbc94921d57038fa43b55",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 844,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 54,
"path": "/make_image.sh",
"repo_name": "ygortavela/citadorbot",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\n# ./make_image.sh \"quote\" \"name\" \"profile.jpg\" \"result.jpg\"\n\nOUT=`python3 wordwrap.py \"$1\"`\n\necho \"$OUT\"\n\nconvert \\\n -background black \\\n -fill white \\\n -font \"Arial\" \\\n -pointsize 80 \\\n -bordercolor Black \\\n -border 30x0 \\\n -style Italic \\\n label:\"\\“$OUT\\”\" \\\n quote.png\n\nconvert \\\n -background black \\\n -fill white \\\n -font \"Arial\" \\\n -pointsize 40 \\\n -bordercolor Black \\\n -border 30x10 \\\n label:\"$2\" \\\n name.png\n\nconvert \\\n -background black \\\n xc:none \\\n quote.png -append \\\n name.png \\\n -gravity SouthEast \\\n -append \\\n +repage \\\n -colorspace Gray \\\n -bordercolor Black \\\n -border 20x20 \\\n image.png\n\nconvert \\\n -background black \\\n xc:none \\\n image.png -append \\\n \"$3\" \\\n -gravity center \\\n +append \\\n +repage \\\n -colorspace Gray \\\n -bordercolor Black \\\n -border 20x20 \\\n \"$4\"\n"
}
] | 2 |
guinaudeau/guinaudeau.github.io
|
https://github.com/guinaudeau/guinaudeau.github.io
|
3f89b86ce9ff786055356dd59dad26d0541d4395
|
8aee03775c45a996c0f2dcccbfc1a639abc9bf6b
|
734140ffb30d8192c8d58935518f817b2660da84
|
refs/heads/master
| 2019-07-02T01:44:59.756077 | 2017-07-13T09:38:54 | 2017-07-13T09:38:54 | 21,613,731 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6295546293258667,
"alphanum_fraction": 0.6857287287712097,
"avg_line_length": 34.92727279663086,
"blob_id": "93176de69e2ce08f23f5285e573d6bb50870b68f",
"content_id": "fb1981f825af3ebe6ef54e2dc6beb64724cb964b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1992,
"license_type": "no_license",
"max_line_length": 200,
"num_lines": 55,
"path": "/mariage_civil.html",
"repo_name": "guinaudeau/guinaudeau.github.io",
"src_encoding": "UTF-8",
"text": "---\nlayout: page\ntitle: \"Cérémonie civile\"\ndescription: \"\"\ntagline: \"\"\ngroup: research\n---\n{% include JB/setup %}\n<center>La cérémonie civile sera célébrée le 29 mai 2015 à 11h30 à la mairie de Montrouge.</br>\nElle sera suivie par un cocktail servi dans notre petit appartement montrougien.</br>\n<img src=\"images/friseCivile4.jpg\" width=\"300\" height=\"300\"/></center>\n<hr/>\n\n<div id=\"global\">\n<center><h3>Informations pratiques</h3></center>\n</br>\n<div id=\"gauche\">\n<center><h5>Comment se rendre à la mairie de Montrouge ?</h5>\n</br>\n <iframe width=\"400\" height=\"300\" frameborder=\"0\" style=\"border:0\" src=\"https://www.google.com/maps/embed/v1/place?q=Mairie%20de%20Montrouge%2C%20Montrouge%2C%20France&key=AIzaSyCe42w6Pq5gYniktwbt66wIX49jupf0WAc\"></iframe>\n</center>\n</div>\n<div id=\"droite\">\n <center><h5>Où se garer à Montrouge ?</h5>\n</br>\n<iframe width=\"400\" height=\"300\" frameborder=\"0\" style=\"border:0\" src=\"https://www.google.com/maps/embed/v1/search?q=parking%20%C3%A0%20proximit%C3%A9%20de%20Montrouge%2C%20France&key=AIzaSyCe42w6Pq5gYniktwbt66wIX49jupf0WAc\"></iframe>\n</center>\n</div>\n <center>\n </br>\n <h5>Où se trouve notre appartement ?</h5>\n</br>\n<iframe width=\"400\" height=\"300\" frameborder=\"0\" style=\"border:0\" src=\"https://www.google.com/maps/embed/v1/place?q=76%20Avenue%20Jean%20Jaur%C3%A8s%2C%20Montrouge%2C%20France&key=AIzaSyCe42w6Pq5gYniktwbt66wIX49jupf0WAc\"></iframe>\n</center>\n</div>\n\n<center>\n</br>\n<h5>Où loger ?</h5>\n</br>\n<a href=\"http://www.hotel-levictorhugo.com/\" target=\"_blank\"> Hôtel \"Le Victor Hugo\"</br>\n<a href=\"http://www.accorhotels.com/fr/hotel-0635-ibis-paris-porte-d-orleans/index.shtml\" target=\"_blank\"> Hôtel ibis </br>\n</center>\n\n\n<script>\n (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n })(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\n ga('create', 'UA-52675614-1', 'auto');\n ga('send', 'pageview');\n\n</script>\n"
},
{
"alpha_fraction": 0.5620403289794922,
"alphanum_fraction": 0.5627520680427551,
"avg_line_length": 42.90625,
"blob_id": "4e4ef934d188afa702ef28b07e731f9a85ea7eba",
"content_id": "67f9998b05ef87552a1db0ec43871f490ce5bcf8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4224,
"license_type": "no_license",
"max_line_length": 246,
"num_lines": 96,
"path": "/publication_page.py",
"repo_name": "guinaudeau/guinaudeau.github.io",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\nimport bibparse\nimport sys\nimport os\n\ndef tidy(string):\n replacements = [(\"{\", \"\"), (\"}\", \"\"),\n (\"\\\\'a\", \"á\"), \n (\"\\\\'e\", \"é\"), ('\\\\\"e', \"ë\"), (\"\\\\`e\", \"è\"),\n (\"\\\\'i\", \"í\"), ('\\\\\"i', \"ï\"), ('\\\\`i', \"ì\"), \n (\"\\\\'o\", \"ó\"), \n (\"\\\\'u\", \"ú\"), ]\n for old, new in replacements:\n string = string.replace(old, new)\n return string\n \ndef print_tab_title(f, title, papers):\n href = ''.join(title.split())\n f.write('<li><a href=\"#%s\" data-toggle=\"tab\">%s (%d)</a></li>\\n' % (href, title, len(papers)))\n\ndef print_tab_content(f, title, papers, active=False):\n previous_year = ''\n href = ''.join(title.split())\n papers = reversed(sorted(papers, key=lambda paper: int(paper.data['Year'])))\n if active:\n f.write('<div class=\"tab-pane fade in active\" id=\"%s\">\\n' % href)\n else:\n f.write('<div class=\"tab-pane fade in\" id=\"%s\">\\n' % href)\n f.write('<div class=\"accordion\" id=\"accordion%s\">\\n' % href)\n for paper in papers:\n if paper.data['Year'] != previous_year:\n f.write('<h3>%s</h3>\\n' % paper.data['Year'])\n previous_year = paper.data['Year']\n f.write('<div class=\"accordion-group\">\\n')\n f.write(' <div class=\"accordion-heading\">\\n')\n f.write(' <a class=\"accordion-toggle\" data-toggle=\"collapse\" data-parent=\"#accordion%s\" href=\"#collapse%s_%s\" onClick=\"_gaq.push([\\'_trackEvent\\', \\'Publications\\', \\'Abstract\\', \\'%s\\']);\">\\n' % (href, paper.key, href, paper.key))\n f.write(' %s\\n' % tidy(paper.data['Title']))\n f.write(' </a>\\n')\n f.write(' </div>\\n')\n f.write(' <div id=\"collapse%s_%s\" class=\"accordion-body collapse\">\\n' % (paper.key, href))\n f.write(' <div class=\"accordion-inner\">\\n')\n f.write(' %s\\n' % tidy(', '.join(paper.data['Author'].split(' and '))))\n if 'Booktitle' in paper.data:\n f.write('<p><em>%s</em></p>\\n' % tidy(paper.data['Booktitle']))\n if 'Journal' in paper.data:\n f.write('<p><em>%s</em></p>\\n' % tidy(paper.data['Journal']))\n if 'Abstract' in paper.data:\n f.write('<blockquote><p>%s</p></blockquote>\\n' % tidy(paper.data['Abstract']))\n f.write('<i class=\"icon-tags\"></i> <a href=\"/guinaudeau.bib\" onClick=\"_gaq.push([\\'_trackEvent\\', \\'Publications\\', \\'Bibtex\\', \\'%s\\']);\">.bib</a> [%s] | ' % (paper.key, paper.key))\n fichier=\"download/pdfs/%s.pdf\"% (paper.key)\n\tif os.path.isfile(fichier):\n\t\tf.write('<i class=\"icon-book\"></i> <a href=\"/download/pdfs/%s.pdf\" onClick=\"_gaq.push([\\'_trackEvent\\', \\'Publications\\', \\'Download\\', \\'%s\\']);\">.pdf</a>' % (paper.key, paper.key))\n else:\n\t\tprint \"Ne trouve pas %s !!\" % fichier\n\tf.write(' </div>\\n')\n f.write(' </div>\\n')\n f.write('</div>\\n')\n f.write('</div>\\n')\n f.write('</div>\\n')\n\npapers = bibparse.parse_bib('guinaudeau.bib')\ninproceedings = [paper for paper in papers if paper.btype == 'inproceedings']\narticles = [paper for paper in papers if paper.btype == 'article']\nchapters = [paper for paper in papers if paper.btype == 'inbook']\n\nf = open('research/publications.html', 'w')\n\nf.write('---\\n')\nf.write('layout: page\\n')\nf.write('title: \"Publications\"\\n')\nf.write('description: \"\"\\n')\nfrom datetime import date\nf.write('tagline: \"last updated on %s\"\\n' % date.today().strftime(\"%B %d, %Y\"))\nf.write('group: research\\n')\nf.write('---\\n')\n\nf.write('{% include JB/setup %}\\n')\n\nf.write('<ul class=\"nav nav-tabs\">\\n')\nprint_tab_title(f, 'All', papers)\nprint_tab_title(f, 'Journal articles', articles)\nprint_tab_title(f, 'Book chapters', chapters)\nprint_tab_title(f, 'Conference and workshop proceedings', inproceedings)\nf.write('</ul>\\n')\n\nf.write('<div id=\"myTabContent\" class=\"tab-content\">\\n')\nprint_tab_content(f, 'All', papers, active=True)\nprint_tab_content(f, 'Journal articles', articles)\nprint_tab_content(f, 'Book chapters', chapters)\nprint_tab_content(f, 'Conference and workshop proceedings', inproceedings)\nf.write('</div>\\n')\n\nf.close()\nos.system(\"cat analytics.js >> research/publications.html\")\n"
}
] | 2 |
YohanWildz/medialibrary_project_python
|
https://github.com/YohanWildz/medialibrary_project_python
|
642f4b991b4892b692f123cfe17139afed5707f1
|
b95eb3fe74eee1fce2ba344ad2ecd941a14003f5
|
bd6af53421310052726c6f24abf53935fd1aa331
|
refs/heads/master
| 2022-11-12T10:44:26.895559 | 2020-07-05T18:12:32 | 2020-07-05T18:12:32 | 273,348,379 | 0 | 0 | null | 2020-06-18T22:01:36 | 2020-06-18T22:15:23 | 2020-07-05T18:12:33 |
Python
|
[
{
"alpha_fraction": 0.8235294222831726,
"alphanum_fraction": 0.8235294222831726,
"avg_line_length": 33,
"blob_id": "1b3681e82d6c055aeaebcfcb5f568a34bccb90fc",
"content_id": "6c55e6de3cde1ab55d7c79eb7d7cc202979f1645",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 68,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 2,
"path": "/README.md",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "# medialibrary_project_python\nSchool project about a madia library.\n"
},
{
"alpha_fraction": 0.4903288185596466,
"alphanum_fraction": 0.49468085169792175,
"avg_line_length": 28.97101402282715,
"blob_id": "3cdc08f04c25d4a637d219730fdaaa8bee7be091",
"content_id": "29846a31fc74f790de86d8690fa6744e3aee285a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2069,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 69,
"path": "/typedocument/image_class.py",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "import document_class\n\nmenuEdit = [\n \"Titre\",\n \"Auteur\"\n]\n\n\nclass ImageDocument(document_class.Document):\n \"\"\"\n Classe d'une image\n \"\"\"\n\n def __init__(self, titre, art, auteur, lien):\n \"\"\"\n :param titre: Titre du document\n :param art: Ascii art de l'image\n :param auteur: Auteur de l'image\n :param lien: Lien de l'iamge\n \"\"\"\n\n document_class.Document.__init__(self, titre,\"image\")\n self.ascii = art\n self.auteur = auteur\n self.lien = lien\n\n def showImage(self):\n \"\"\"\n :return: print du contenu de l'image\n \"\"\"\n print(\"Nom du document : \" + self.titre + \"\\nAuteur : \" + self.auteur + \"\\nLien : \" + self.lien + \"\\nAscii : \" + self.ascii)\n\n def menuEditTextDocument(self):\n \"\"\"\n :return: Menu d'edit du document\n \"\"\"\n try:\n print(\"Voulez-vouz vraiment editer \" + self.titre + \"? (Oui = 1 Non=2 )\")\n response = int(input())\n if response == 1:\n print(\"Qu'est ce que vous voulez éditer ? \\n\")\n count = 1\n for menu in menuEdit:\n print((str(count) + \". \" + menu.title()))\n count += 1\n response = int(input())\n if response == 1:\n self.editTitle()\n elif response == 2:\n self.editAuthor()\n else:\n self.errorValue()\n\n elif response == 2:\n return 0\n else:\n self.errorValue()\n except ValueError:\n self.errorValue()\n\n def errorValue(self):\n print(\"Mauvaise valeurs ! Retour au menu\")\n self.menuEditTextDocument()\n\n def editAuthor(self):\n print(\n \"Veuillez entrez le nouveau nom de l'auteur pour le document '\" + self.titre + \"' (Ancien auteur : \" + self.author + \")\")\n self.author = input()\n print(\"Le nouveau auteur est \" + self.author + \" pour le doccuement : \" + self.titre)\n"
},
{
"alpha_fraction": 0.5152542591094971,
"alphanum_fraction": 0.5227118730545044,
"avg_line_length": 41.157142639160156,
"blob_id": "7c4a474d6ffc57c5292dc964ae2853265200cb9b",
"content_id": "dcc2092c53f39ec4c2fc6c8f6910f5c0140e240a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2962,
"license_type": "no_license",
"max_line_length": 241,
"num_lines": 70,
"path": "/main.py",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "from typedocument.audio_class import AudioDocument\nfrom typedocument.image_class import ImageDocument\nfrom typedocument.text_class import textDocument\n\n\nart =str(\"\"\"\"\"\"\"\"\"-.\n ' \n |,. ,-. |\n |()L( ()| |\n |,' `\".| |\n |.___.',| `\n .j `--\"' ` `.\n / ' ' \n / / ` `.\n / / ` .\n / / l |\n . , | |\n ,\"`. .| |\n _.' ``. o | `..-'l\n| `.`, | `.\n| `. __.j )\n|__ |--\"\"___| ,-'\n `\"--...,+\"\"\"\" `._,.-' mh)\"\"\")\n\n\nfrom document_class import Document\n\ntext1= textDocument('La cigale et la fourmi',\"Jean De la fontaine\",\"La Cigale, ayant chanté \\nTout l'été,\\nSe trouva fort dépourvue\\nQuand la bise fut venue :\\nPas un seul petit morceau\\n\")\nimage1= ImageDocument('Tux',art,\"Linus Torvalds\",\"https://fr.wikipedia.org/wiki/Tux#/media/Fichier:Tux.svg\")\naudio1= AudioDocument('Valse n°2','Dimitri Chostakovitch',233,'Orchestre Universitaire de Lille','https://www.youtube.com/watch?v=tv8nF49alQk')\n\ncontinu =True\n\n\nprint(\"Bienvenue dans la médiathèque devloppée par Yohan Widogue\")\nwhile continu == True:\n print(\"Que voulez vous faire ? \\n 1.Consulter un document \\n2.Nouveau document\\n3.Quitter\")\n try:\n choix = int(input())\n\n if choix == 1:\n print(\"Voici les documents actuelement stocké: \")\n for object in Document.instances:\n print(str(object.id) + \" : \"+object.titre + \"(Type : \"+ object.__class__.__name__+\")\")\n print(\"Quel document voulez vous consulter ? \")\n choix = int(input())\n for object in Document.instances:\n if object.id==choix:\n if object.type == \"audio\":\n object.showAudio()\n elif object.type ==\"text\":\n object.showTextDocument()\n elif object.type ==\"image\":\n object.showImage()\n elif choix == 2:\n print(\"Quel type de document voulez vous crée ?\\n1.Audio\\n2.Text\\n3.Image\")\n choix = int(input())\n if choix == 1:\n newdocAudio=AudioDocument(input(\"Veuillez saisir le titre : \"),input(\"Veuillez saisir le Compositeur : \"),int(input(\"Veuillez saisir la durée : \")),input(\"Veuillez saisir l'interprète : \"),input(\"Veuillez saisir le lien : \"))\n elif choix ==2:\n newdocText=textDocument(input(\"Veuillez saisir le titre : \"),input(\"Veuillez saisir l'auteur : \"),input(\"Veuillez saisir le contenu: \"))\n elif choix ==3:\n newdocImage=ImageDocument(input(\"Veuillez saisir le titre : \"),input(\"Veuillez entrez l'ascii art : \"),input(\"Veuillez saisir l'auteur' : \"),input(\"Veuillez saisir le lien : \"))\n\n elif choix == 3:\n continu=False\n\n except ValueError:\n print(\"Mauvais choix, recommencer\")\n pass"
},
{
"alpha_fraction": 0.5682326555252075,
"alphanum_fraction": 0.5682326555252075,
"avg_line_length": 26.8125,
"blob_id": "25dab3bd773dbc78dcc4067aad287c7464f434e1",
"content_id": "14e001a16e6ebe48d73cd088d48f17decc6561a9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 895,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 32,
"path": "/document_class.py",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "import weakref\n\n\nclass Document:\n \"\"\"\n Classe mère d'un document\n \"\"\"\n instances=[]\n def __init__(self,titre,type):\n \"\"\"\n Init de Document\n :param titre: Titre du document\n :param type: Type du document\n \"\"\"\n self.__class__.instances.append(weakref.proxy(self)) #Ajoute l'object dans la listes d'instances\n self.titre = titre\n self.id = len(self.__class__.instances) #Prend l'id sur la longeurs de instence\n self.type = type\n\n def getTitre(self):\n \"\"\"\n :return: Titre du document\n \"\"\"\n return self.titre\n\n def editTitle(self):\n \"\"\"\n :return: Permet de changer le titre d'un document\n \"\"\"\n print(\"Choissisez le nouveau titre pour le document : \" + self.titre)\n self.titre = input()\n print(\"Le nouveau nom du document est \" + self.titre)\n\n\n\n\n"
},
{
"alpha_fraction": 0.5916585922241211,
"alphanum_fraction": 0.5916585922241211,
"avg_line_length": 27.61111068725586,
"blob_id": "76fd125de0fcb4363feab07b9b8b08e0d2d35700",
"content_id": "cb24bf60c8870ca0e8d44846e35d2e2b4c93a4f5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1033,
"license_type": "no_license",
"max_line_length": 190,
"num_lines": 36,
"path": "/typedocument/audio_class.py",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "import document_class\n\nmenuEdit = [\n \"Titre\",\n \"Auteur\"\n]\n\n\nclass AudioDocument(document_class.Document):\n def __init__(self,titre,compositeur,duree,interprete,lien):\n \"\"\"\n\n :param titre: Titre de l'audio\n :type titre: str\n :param compositeur: Compositeur de l'audio\n :type compositeur: str\n :param duree: duree en seconde\n :type duree: int\n :param interprete: Interprete de l'audio\n :type interprete: str\n :param lien: Lien de l'audio\n :type lien: str\n \"\"\"\n document_class.Document.__init__(self,titre,\"audio\")\n self.compositeur=compositeur\n self.duree =duree\n self.interprete=interprete\n self.lien=lien\n\n\n def showAudio(self):\n \"\"\"\n\n :return: Print des informations de la musique\n \"\"\"\n print(\"Nom du document : \" + self.titre + \"\\nCompositeur : \" + self.compositeur + \"\\nInterprète : \" + self.interprete + \"\\nDurée : \" + str(self.duree) + \" SEC \\n Lien: \" + self.lien)\n\n"
},
{
"alpha_fraction": 0.5089882016181946,
"alphanum_fraction": 0.5136106610298157,
"avg_line_length": 28.96923065185547,
"blob_id": "881833ec13dcc6665df78b0d9f8525f6be95ac06",
"content_id": "ca8e7e2d81dacd6df1b7c01ec69a7a159d6558e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1948,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 65,
"path": "/typedocument/text_class.py",
"repo_name": "YohanWildz/medialibrary_project_python",
"src_encoding": "UTF-8",
"text": "import document_class\n\nmenuEdit = [\n \"Titre\",\n \"Auteur\"\n]\n\n\nclass textDocument(document_class.Document):\n \"\"\"\n Classe enfant de document_class , classe d'un document texte\n \"\"\"\n\n\n def __init__(self, titre, auteur, contenu):\n \"\"\"\n\n :param titre: Titre du text\n :type titre: str\n :param auteur: Auteur du text\n :type auteur: str\n :param contenu: Contenu du text\n :type contenu: str\n \"\"\"\n document_class.Document.__init__(self, titre,\"text\")\n self.content = contenu\n self.author = auteur\n\n def showTextDocument(self):\n print(\"Titre : \" + self.titre + \"\\n Autheur : \" + self.author + \"\\n Contenu : \" + self.content)\n\n def menuEditTextDocument(self):\n try:\n print(\"Voulez-vouz vraiment editer \" + self.titre + \"? (Oui = 1 Non=2 )\")\n response = int(input())\n if response == 1:\n print(\"Qu'est ce que vous voulez éditer ? \\n\")\n count = 1\n for menu in menuEdit:\n print((str(count) +\". \"+ menu.title()))\n count += 1\n response = int(input())\n if response == 1:\n self.editTitle()\n elif response == 2:\n self.editAuthor()\n else:\n self.errorValue()\n\n elif response == 2:\n return 0\n else:\n self.errorValue()\n except ValueError:\n self.errorValue()\n\n\n def errorValue(self):\n print(\"Mauvaise valeurs ! Retour au menu\")\n self.menuEditTextDocument()\n\n def editAuthor(self):\n print(\"Veuillez entrez le nouveau nom de l'auteur pour le document '\"+self.titre + \"' (Ancien auteur : \"+ self.author + \")\")\n self.author=input()\n print(\"Le nouveau auteur est \" +self.author +\" pour le doccuement : \" + self.titre)"
}
] | 6 |
gtldrititannk/wordcloud-demo
|
https://github.com/gtldrititannk/wordcloud-demo
|
48565a4d144ea9f908cb8e68e8038058eb21892a
|
fd43f0bc162a10be5a1c93442e63aa2778926307
|
595f3aa0e08c0bdc09b8976484d59973fa744130
|
refs/heads/master
| 2023-08-14T02:26:59.222929 | 2021-09-09T08:37:06 | 2021-09-09T08:37:06 | 403,977,384 | 0 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7111368775367737,
"alphanum_fraction": 0.7378190159797668,
"avg_line_length": 22.324323654174805,
"blob_id": "f8a1efb6f37547d07ef6f9cff0747229021f7740",
"content_id": "279aa49aa1bd4649428a39a12061dd7a6434031a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 862,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 37,
"path": "/readme.md",
"repo_name": "gtldrititannk/wordcloud-demo",
"src_encoding": "UTF-8",
"text": "# WordCloud Demo\n_This project demonstrates wordcloud feature_\n\n> Word Cloud is a data visualization technique used for representing text data in which \n> the size of each word indicates its frequency or importance. Significant textual data points \n>can be highlighted using a word cloud. Word clouds are widely used for analyzing data \n>from social network websites.\n\n##### Libraries\n\n - sqlalchemy = 1.4.23\n - wordcloud = 1.8.1\n - numpy==1.19.5\n - pandas==1.1.5\n - matplotlib==3.3.4\n\n##### Installation steps:\n\n1. Clone the repository\n2. Create virtual enviornment\n\n> virtualenv -p python3.6 venv_wc_demo\n>\n> .venv_wc_demo/bin/activate\n\n3. Install dependencies/packages:\n\n> pip install -r requirements.txt\n\n4. Run the following command:\n\n> python sql_convertor.py \n> python word_cloud.py\n\n##### Word cloud Example\n\n"
},
{
"alpha_fraction": 0.5617977380752563,
"alphanum_fraction": 0.5686196088790894,
"avg_line_length": 29.75308609008789,
"blob_id": "16752dfb03561f9e28ee3b9fd6055211db2cec79",
"content_id": "f5938b77cc2d9701260d67b2882906df6170a4f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2492,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 81,
"path": "/word_cloud.py",
"repo_name": "gtldrititannk/wordcloud-demo",
"src_encoding": "UTF-8",
"text": "import nltk\nfrom nltk.corpus import stopwords\n\nfrom sklearn.model_selection import train_test_split\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom wordcloud import WordCloud, STOPWORDS\n\n\ndef generate_wordcloud(data, color='black'):\n \"\"\"\n This method generates the wordcloud for the given data\n \"\"\"\n words = ' '.join(data)\n filtered_word = \" \".join([word for word in words.split()\n if 'http' not in word\n and not word.startswith('@')\n and not word.startswith('#')\n and word != 'RT'\n ])\n wordcloud = WordCloud(stopwords=STOPWORDS,\n background_color=color,\n width=2500,\n height=2000\n ).generate(filtered_word)\n\n plt.figure(1, figsize=(13, 13))\n plt.imshow(wordcloud)\n plt.axis('off')\n\n plt.savefig('output/train_ds_wc.png')\n\n\ndef get_words_in_tweets(tweets):\n \"\"\"\n This method generates the overall words list\n \"\"\"\n all = []\n for (words, sentiment) in tweets:\n all.extend(words)\n return all\n\n\ndef get_word_features(wordlist):\n \"\"\"\n This method calculates the word frequency in the given words list.\n \"\"\"\n wordlist = nltk.FreqDist(wordlist)\n features = wordlist.keys()\n return features\n\n\nif __name__ == '__main__':\n u_tweets = []\n stopwords_set = set(stopwords.words(\"english\"))\n\n ds = pd.read_csv('input/sentiment.csv')\n train, test = train_test_split(ds, test_size=0.1)\n\n train = train[train.sentiment != \"Neutral\"]\n\n train_pos = train[train['sentiment'] == 'Positive']\n train_pos = train_pos['text']\n train_neg = train[train['sentiment'] == 'Negative']\n train_neg = train_neg['text']\n\n for index, row in train.iterrows():\n words_filtered = [e.lower() for e in row.text.split() if len(e) >= 3]\n words_cleaned = [word for word in words_filtered\n if 'http' not in word\n and not word.startswith('@')\n and not word.startswith('#')\n and word != 'RT']\n words_without_stopwords = [word for word in words_cleaned if not word in stopwords_set]\n u_tweets.append((words_without_stopwords, row.sentiment))\n\n w_features = get_word_features(get_words_in_tweets(u_tweets))\n\n generate_wordcloud(w_features, color='#FFFAF0')\n\n"
},
{
"alpha_fraction": 0.6704288721084595,
"alphanum_fraction": 0.6704288721084595,
"avg_line_length": 33,
"blob_id": "ce7dd1dbc48a7c212e38eac51a18d51f758790f1",
"content_id": "4e32796c083192aa882790d12adfce5cd6c884b0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 443,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 13,
"path": "/sql_convertor.py",
"repo_name": "gtldrititannk/wordcloud-demo",
"src_encoding": "UTF-8",
"text": "import pandas as pd\n\nfrom sqlalchemy import create_engine\n\n\nif __name__ == '__main__':\n # Create sqlite engine\n engine = create_engine(\"sqlite:///input/sentiment_db.sqlite\")\n # Read database table and creates the dataframe\n sql_df = pd.read_sql_table('Sentiment', engine, columns=['text', 'sentiment'], index_col='id')\n # Create csv file\n sql_df.to_csv('input/sentiment.csv')\n print('\\n\\n CSV File Created Sucessfully!')\n\n"
}
] | 3 |
Novritch/Comment-bot-for-Youtube
|
https://github.com/Novritch/Comment-bot-for-Youtube
|
76076cb9befcfc1fb2741f52d1fe1c9e77527c1b
|
5a66e12f2766a09fded9afcc77a2c58dd65e08d5
|
112abb5b464ee1940c7c018d7b9b469c22229e88
|
refs/heads/master
| 2022-11-15T07:12:45.902280 | 2020-07-04T19:24:50 | 2020-07-04T19:24:50 | 277,170,045 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6531678438186646,
"alphanum_fraction": 0.7082517147064209,
"avg_line_length": 60.94520568847656,
"blob_id": "9fa401d8b8e059a204ccbb3ad481b4c11d3bad54",
"content_id": "53baace2316aa19de7385d58f7fe36f7910a1f56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4593,
"license_type": "no_license",
"max_line_length": 698,
"num_lines": 73,
"path": "/Comment Bot for YouTube.py",
"repo_name": "Novritch/Comment-bot-for-Youtube",
"src_encoding": "UTF-8",
"text": "################################\r\n####Made by Novritch - GitHub###\r\n# [email protected] #\r\n#################################\r\n# Requirements to run this script correctly :\r\n# - Work with Microsoft Edge (if it's another brower you can change it line 20, ex : webdriver.firefox(), webdriver.chrome(), webdriver.ie()...)\r\n# - WebDriver for your Browser (here Edge)\r\n# - Selenium module\r\n# Once this script started, all your current tabs on the selected brower will be automatically closed, be careful !\r\n# This script work unically with YouTube playlist links\r\n# This script was realized with my loadings times, so you can change lines with time.sleep(x) as your please to increase the speed, if your browser and connection allow it\r\n\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.common.exceptions import TimeoutException\r\n\r\ndef PosterCommentaire(commentaire,playlist):\r\n driver = webdriver.Edge()\r\n driver.get(playlist)\r\n driver.maximize_window()\r\n try:\r\n myElem = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.ID, 'thumbnail')))\r\n print (\"Playlist's content loaded successfully !\")\r\n elementParent = driver.find_element_by_xpath(\"//div[(@id='contents') and (@class = 'style-scope ytd-playlist-video-list-renderer')]\")\r\n nombreDeVideos = len(elementParent.find_elements_by_xpath(\"//ytd-playlist-video-renderer[(@class = 'style-scope ytd-playlist-video-list-renderer')]\"))\r\n driver.find_element_by_id('thumbnail').click()\r\n for i in range(nombreDeVideos):\r\n time.sleep(10)\r\n # Ecriture commentaire\r\n driver.execute_script(\"window.scrollTo(0, 750)\")\r\n time.sleep(3)\r\n driver.find_element_by_id('placeholder-area').click()\r\n inputBox = driver.find_element_by_id('contenteditable-root')\r\n inputBox.send_keys(commentaire)\r\n driver.find_element_by_id('submit-button').click()\r\n time.sleep(2)\r\n driver.execute_script(\"window.scrollTo(0, -750)\")\r\n driver.find_element_by_xpath(\"//a[(@class='ytp-next-button ytp-button')]\").click()\r\n print(\"Process completed !\")\r\n except TimeoutException:\r\n print (\"The PlayList takes too long to load (<20 seconds) or there is a problem studying the Web page\")\r\n\r\n\r\n# Connexion au compte Google\r\ndef ConnexionGoogle(email,MDP):\r\n driver = webdriver.Edge()\r\n driver.get(\"https://accounts.google.com/signin/oauth/identifier?client_id=717762328687-iludtf96g1hinl76e4lc1b9a82g457nn.apps.googleusercontent.com&scope=profile%20email&redirect_uri=https%3A%2F%2Fstackauth.com%2Fauth%2Foauth2%2Fgoogle&state=%7B%22sid%22%3A1%2C%22st%22%3A%2259%3A3%3ABBC%2C16%3A59aa2292b79a6ba4%2C10%3A1593795256%2C16%3A5340420ffe98a9f0%2C26978fbbeb4f365b1c584b05ac01158b1379fd0eb20732ec7437658da0cc3e36%22%2C%22cdl%22%3Anull%2C%22cid%22%3A%22717762328687-iludtf96g1hinl76e4lc1b9a82g457nn.apps.googleusercontent.com%22%2C%22k%22%3A%22Google%22%2C%22ses%22%3A%2265784dfa8081468fb90a9fc123c46818%22%7D&response_type=code&o2v=1&as=uIUgZGCNL2eXi6vXPoq9WQ&flowName=GeneralOAuthFlow\")\r\n time.sleep(1)\r\n driver.find_element_by_name('identifier').send_keys(email)\r\n driver.find_element_by_id('identifierNext').click()\r\n time.sleep(1)\r\n driver.find_element_by_name('password').send_keys(MDP)\r\n time.sleep(1)\r\n driver.find_element_by_id('passwordNext').click()\r\n time.sleep(1)\r\n driver.close()\r\n PosterCommentaire(commentaire,playlist)\r\n\r\n# Dialogue avec l'utilisateur\r\nreponse = input(str(\"Is your Google account currently connected ? (yes OR no)\")) #There must not be a single account saved in your brower, delete all, otherwise it wouldn't work\r\nif reponse == \"no\":\r\n email = input(str(\"Enter your Google account email\"))\r\n MDP = input(str(\"Enter your Google account password\"))\r\n playlist = input(str(\"Enter the link of the playlist containing the videos under which to put the comments (ex : https://www.youtube.com/playlist?list=SPECIFICID)\"))\r\n commentaire = input(str(\"Enter the comment that you want to post\"))\r\n ConnexionGoogle(email,MDP)\r\nif reponse == \"yes\":\r\n playlist = input(str(\"Enter the link of the playlist containing the videos under which to put the comments (ex : https://www.youtube.com/playlist?list=SPECIFICID)\"))\r\n commentaire = input(str(\"Enter the comment that you want to post\"))\r\n PosterCommentaire(commentaire,playlist)"
},
{
"alpha_fraction": 0.7724137902259827,
"alphanum_fraction": 0.7724137902259827,
"avg_line_length": 95.66666412353516,
"blob_id": "03e795c98006e37a9fdc3dbfa6bbf7500b097014",
"content_id": "d60fe9f26f0c1a59826dccb5ce9584c9f61a071a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 290,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 3,
"path": "/README.md",
"repo_name": "Novritch/Comment-bot-for-Youtube",
"src_encoding": "UTF-8",
"text": "# Comment-bot-for-Youtube\nThis is my very first time I publish a script on GitHub, so there may be things done wrong, if it's the case I apologize.\nIt's a bot that takes your YouTube playlist, and it automatically write the comment you choosed before on the videos, I hope you'll like it !\n"
}
] | 2 |
babushka78/alex
|
https://github.com/babushka78/alex
|
a8a31df0eaca256e623cab2579493514e57642da
|
fd665c6c5d5579bc35f3c6939f9955350a4d46d8
|
233a711000bb67d24493c8a95f968e81a649601b
|
refs/heads/main
| 2023-08-14T13:27:47.802306 | 2021-10-01T16:43:14 | 2021-10-01T16:43:14 | 401,775,525 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7570921778678894,
"alphanum_fraction": 0.7570921778678894,
"avg_line_length": 28.6842098236084,
"blob_id": "265893b89c947cb139b11cac04fd5db946d9a32e",
"content_id": "15b8ae2c795fc61313514417bf1d6300f7e7c629",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 685,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 19,
"path": "/3main3.py",
"repo_name": "babushka78/alex",
"src_encoding": "UTF-8",
"text": "# Импорт библиотек\nfrom binance.client import Client\nimport configparser\n\n# Загрузка ключей из файла config\nconfig = configparser.ConfigParser()\nconfig.read_file(open('secret.cfg'))\ntest_api_key = config.get('BINANCE', 'TEST_API_KEY')\ntest_secret_key = config.get('BINANCE', 'TEST_SECRET_KEY')\n\n\n\nclient = Client(test_api_key, test_secret_key, testnet=True)\n\nclient.API_URL = 'https://testnet.binance.vision/api' # Это нужно, чтобы изменить URL-адрес конечной точки тестового аккаунта\n\ninfo = client.get_account() # Получение информации об аккаунте\n\nprint(info)\n"
}
] | 1 |
anujparakh/image-blending
|
https://github.com/anujparakh/image-blending
|
c0df7ecbf5f4989d4176e22a6fbd12476ca35019
|
4d8ef3ec3ba78e553370c4a79dd154ea7e051723
|
b388c2733270c708519379a519ce293e2d5e00e5
|
refs/heads/master
| 2022-04-10T02:19:00.414798 | 2020-03-17T20:15:07 | 2020-03-17T20:15:07 | 247,187,417 | 1 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.739629864692688,
"alphanum_fraction": 0.749202311038971,
"avg_line_length": 27.870370864868164,
"blob_id": "cbf75935d349a1783f4c83c71ede5e24d8c58694",
"content_id": "f270217329a602a7e5b781873085ee1bd49ecaac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1567,
"license_type": "no_license",
"max_line_length": 152,
"num_lines": 54,
"path": "/README.md",
"repo_name": "anujparakh/image-blending",
"src_encoding": "UTF-8",
"text": "# image-blending\nImage blending is the process of blending a source onto a target image with a mask such that it appears that\nthe source is blending nicely into the target image's background. It can be implemented in a variety of ways. I have\nimplemented Pyramid Blending and Poisson Blending.\n\nThe repo is organized in three folders:\n- **Code :** `main.py` contains the main blending code that works for images one to nine. `getMask.py` can be used to generate a mask for a given image.\n- **Images :** This folder contains all the source, target and mask images. They are numbered one to nine.\n- **Results :** This is the folder where the generated results are stored. All the blends for images one to nine are present here.\n\n## Running Code\n\nTo run the code, Python 3 and the following libraries must be installed:\n- numpy\n- cv2\n- scipy\n- matplotlib\n\nThen simply use the following command to run with python:\n```\npython3 main.py\n```\n\n\nExamples of the blending are given below:\n\n## Pyramid Blending\n\nPyramid Blending is not as good as Poisson Blending, but can work well in certain cases.\nA good example is blending the source image of an apple:\n\n\n\nwith an orange\n\n\n\nusing Pyramid Blending results in this:\n\n\n\n## Poisson Blending\n\nBlending the following source:\n\n\n\nwith the following target:\n\n\n\nresults in the following:\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5440741777420044,
"alphanum_fraction": 0.5643644332885742,
"avg_line_length": 31.67420768737793,
"blob_id": "b357070df18c1b9452766961e04fa26bc022f6c7",
"content_id": "60fd9d67973cf4a02bdb1944137fa31637c72069",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7442,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 221,
"path": "/Code/main.py",
"repo_name": "anujparakh/image-blending",
"src_encoding": "UTF-8",
"text": "# Import required libraries\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\nimport scipy.sparse\r\nfrom scipy.sparse.linalg import spsolve\r\n\r\n# Read source, target and mask for a given id\r\ndef Read(id, path = \"\"):\r\n source = np.float32(cv2.imread(path + \"source_\" + id + \".jpg\", 1))\r\n target = np.float32(cv2.imread(path + \"target_\" + id + \".jpg\", 1))\r\n mask = np.float32(cv2.imread(path + \"mask_\" + id + \".jpg\", 1))\r\n return source, mask, target\r\n\r\n\r\n# Adjust parameters, source and mask for negative offsets or out of bounds of offsets\r\ndef AlignImages(mask, source, target, offset):\r\n sourceHeight, sourceWidth, _ = source.shape\r\n targetHeight, targetWidth, _ = target.shape\r\n xOffset, yOffset = offset\r\n \r\n if (xOffset < 0):\r\n mask = mask[abs(xOffset):, :]\r\n source = source[abs(xOffset):, :]\r\n sourceHeight -= abs(xOffset)\r\n xOffset = 0\r\n if (yOffset < 0):\r\n mask = mask[:, abs(yOffset):]\r\n source = source[:, abs(yOffset):]\r\n sourceWidth -= abs(yOffset)\r\n yOffset = 0\r\n # Source image outside target image after applying offset\r\n if (targetHeight < (sourceHeight + xOffset)):\r\n sourceHeight = targetHeight - xOffset\r\n mask = mask[:sourceHeight, :]\r\n source = source[:sourceHeight, :]\r\n if (targetWidth < (sourceWidth + yOffset)):\r\n sourceWidth = targetWidth - yOffset\r\n mask = mask[:, :sourceWidth]\r\n source = source[:, :sourceWidth]\r\n \r\n maskLocal = np.zeros_like(target)\r\n maskLocal[xOffset:xOffset + sourceHeight, yOffset:yOffset + sourceWidth] = mask\r\n sourceLocal = np.zeros_like(target)\r\n sourceLocal[xOffset:xOffset + sourceHeight, yOffset:yOffset + sourceWidth] = source\r\n\r\n return sourceLocal, maskLocal\r\n\r\n# Pyramid Blend\r\ndef PyramidBlend(source, mask, target, numLayers): \r\n # Generate Gaussians for source, mask and target\r\n # Temp images that are scaled down every iteration\r\n GS = source.copy()\r\n GT = target.copy()\r\n GM = mask.copy()\r\n # The pyramids\r\n gSource = [GS]\r\n gTarget = [GT]\r\n gMask = [GM]\r\n for i in range(0, numLayers):\r\n # scale down\r\n GS = cv2.pyrDown(GS)\r\n GT = cv2.pyrDown(GT)\r\n GM = cv2.pyrDown(GM)\r\n # append to pyramid\r\n gSource.append(GS)\r\n gTarget.append(GT)\r\n gMask.append(GM)\r\n\r\n # Generate Laplacian for source and target\r\n lpSource = [gSource[numLayers - 1]]\r\n lpTarget = [gTarget[numLayers - 1]]\r\n # Flip the gMask so the layers match the laplacians\r\n gMaskFlipped = [gMask[numLayers - 1]]\r\n for i in range(numLayers - 1, 0, -1):\r\n # get high frequencies by subtracting\r\n size = (gSource[i-1].shape[1], gSource[i-1].shape[0])\r\n LS = np.subtract(gSource[i-1], cv2.pyrUp(gSource[i], dstsize=size))\r\n size = (gTarget[i-1].shape[1], gTarget[i-1].shape[0])\r\n LT = np.subtract(gTarget[i-1], cv2.pyrUp(gTarget[i], dstsize=size))\r\n \r\n # Add to the pyramid\r\n lpSource.append(LS)\r\n lpTarget.append(LT)\r\n\r\n gMaskFlipped.append(gMask[i - 1])\r\n \r\n # Perform the Calculation \r\n LCs = []\r\n for Ls, Lt, Gm in zip(lpSource, lpTarget, gMaskFlipped):\r\n # Given formula\r\n lc = Ls * Gm + Lt * (1.0 - Gm)\r\n LCs.append(lc)\r\n\r\n # Reconstruct Image at each level\r\n finalImage = LCs[0]\r\n for i in range(1, numLayers):\r\n size = (LCs[i].shape[1], LCs[i].shape[0])\r\n # Scale it up and add to the final image\r\n finalImage = cv2.pyrUp(finalImage, dstsize=size)\r\n finalImage = cv2.add(finalImage, LCs[i])\r\n\r\n print(\"Pyramid Done!\")\r\n return finalImage\r\n\r\ndef createMatrixA(numRows, numCols):\r\n # use scipy.sparse\r\n D = scipy.sparse.lil_matrix((numRows, numRows))\r\n D.setdiag(-1, -1)\r\n D.setdiag(4)\r\n D.setdiag(-1, 1)\r\n A = scipy.sparse.block_diag([D] * numCols).tolil()\r\n A.setdiag(-1, 1 * numRows)\r\n A.setdiag(-1, -1 * numRows)\r\n \r\n return A\r\n\r\n# Poisson Blend\r\ndef PoissonBlend(source, mask, target, isMix):\r\n \r\n # Get the size of the target\r\n maxY, maxX = target.shape[:-1]\r\n A = createMatrixA(maxX, maxY)\r\n\r\n converted = A.tocsc()\r\n\r\n for y in range(1, maxY - 1):\r\n for x in range(1, maxX - 1):\r\n if mask[y][x] == 0: # region outside of mask\r\n # Update A matrix\r\n k = x + y * maxX\r\n A[k, k] = 1\r\n A[k, k + 1] = 0\r\n A[k, k - 1] = 0\r\n A[k, k + maxX] = 0\r\n A[k, k - maxX] = 0\r\n\r\n A = A.tocsc()\r\n flatMask = mask.flatten()\r\n \r\n # Go through each color channel\r\n for channel in range(source.shape[2]):\r\n # Flatten matrices for given channel\r\n flatSource = source[0:maxY, 0:maxX, channel].flatten()\r\n flatTarget = target[0:maxY, 0:maxX, channel].flatten() \r\n\r\n # create B matrix\r\n B = converted.dot(flatSource)\r\n B[flatMask==0] = flatTarget[flatMask==0]\r\n \r\n # Solve the matrix\r\n x = spsolve(A, B)\r\n\r\n # Normalize the solution\r\n x = x.reshape((maxY, maxX))\r\n x[x > 255] = 255\r\n x[x < 0] = 0\r\n x = x.astype('uint8')\r\n\r\n # Set target's channel to solution x\r\n target[0:maxY, 0:maxX, channel] = x\r\n\r\n print(\"Poisson Done!\")\r\n\r\n return target\r\n\r\ndef NaiveBlend(source, target, mask):\r\n return source * mask + target * (1 - mask)\r\n \r\nif __name__ == '__main__':\r\n # Setting up the input output paths\r\n inputDir = '../Images/'\r\n outputDir = '../Results/'\r\n \r\n # False for source gradient, true for mixing gradients\r\n isMix = False\r\n\r\n # Source offsets in target\r\n offsets = [[0, 0], [0, 0], [210, 10], [10, 28], [140, 80], [-40, 90], [60, 100], [20, 20], [-28, 88], [350, 200]]\r\n\r\n # main area to specify files and display blended image\r\n for index in range(1, len(offsets)):\r\n\r\n print (\"Doing \" + str(index))\r\n # Read data and clean mask\r\n source, maskOriginal, target = Read(str(index).zfill(2), inputDir)\r\n\r\n # Cleaning up the mask\r\n mask = np.ones_like(maskOriginal)\r\n mask[maskOriginal < 127] = 0\r\n\r\n # Align the source and mask using the provided offest\r\n source, mask = AlignImages(mask, source, target, offsets[index])\r\n\r\n ### The main part of the code ###\r\n \r\n # Implement the PyramidBlend function (Task 1)\r\n pyramidOutput = PyramidBlend(source, mask, target, 6)\r\n cv2.imwrite(\"{}pyramid_{}.jpg\".format(outputDir, str(index).zfill(2)), pyramidOutput)\r\n\r\n maskGrayscale = []\r\n for i in range(0, mask.shape[0]):\r\n temp = []\r\n for j in range(0, mask.shape[1]):\r\n if np.any(mask[i][j]):\r\n temp.append(1)\r\n else:\r\n temp.append(0)\r\n\r\n maskGrayscale.append(temp)\r\n\r\n maskGrayscale = np.array(maskGrayscale)\r\n # Implement the PoissonBlend function (Task 2)\r\n poissonOutput = PoissonBlend(source, maskGrayscale, target, isMix)\r\n \r\n # Writing the result\r\n\r\n if not isMix:\r\n cv2.imwrite(\"{}poisson_{}.jpg\".format(outputDir, str(index).zfill(2)), poissonOutput)\r\n else:\r\n cv2.imwrite(\"{}poisson_{}_Mixing.jpg\".format(outputDir, str(index).zfill(2)), poissonOutput)\r\n"
},
{
"alpha_fraction": 0.6056680083274841,
"alphanum_fraction": 0.6348178386688232,
"avg_line_length": 31.37837791442871,
"blob_id": "0dd32542b5828bca0e42ff84268a9301f3339f4b",
"content_id": "474f795418ab2bb8f2dd6f61c48a76f8db425547",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1235,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 37,
"path": "/Code/GetMask.py",
"repo_name": "anujparakh/image-blending",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport sys\r\n\r\ndef GetMask(image):\r\n ### You can add any number of points by using \r\n ### mouse left click. Delete points with mouse\r\n ### right click and finish adding by mouse\r\n ### middle click. More info:\r\n ### https://matplotlib.org/api/_as_gen/matplotlib.pyplot.ginput.html\r\n\r\n plt.imshow(image)\r\n plt.axis('image')\r\n points = plt.ginput(-1, timeout=-1)\r\n plt.close()\r\n\r\n ### The code below is based on this answer from stackoverflow\r\n ### https://stackoverflow.com/a/15343106\r\n\r\n mask = np.zeros(image.shape, dtype=np.uint8)\r\n roi_corners = np.array([points], dtype=np.int32)\r\n # fill the ROI so it doesn't get wiped out when the mask is applied\r\n channel_count = image.shape[2] # i.e. 3 or 4 depending on your image\r\n ignore_mask_color = (255,)*channel_count\r\n cv2.fillPoly(mask, roi_corners, ignore_mask_color)\r\n np.set_printoptions(threshold=sys.maxsize)\r\n return mask\r\n\r\n\r\nimg = cv2.imread(\"../Images/tempmask_09.png\", 0)\r\nfor y in range(0, img.shape[0]):\r\n for x in range(0, img.shape[1]):\r\n if (img [y] [x] != 0):\r\n img[y][x] = 255\r\n\r\ncv2.imwrite(\"../Images/mask_09.jpg\", img)\r\n"
}
] | 3 |
mehuldhokia/demo-dbcon
|
https://github.com/mehuldhokia/demo-dbcon
|
b961ec286994f9e5a53b209e3c49eb557d91ab0c
|
b6496154d548dce4a7427c2b99a4d0ace27ce413
|
5545b3e877f030e6775b74e400781ba3a290fa57
|
refs/heads/master
| 2021-06-21T23:02:52.860530 | 2019-10-03T04:15:58 | 2019-10-03T04:15:58 | 212,495,098 | 0 | 0 | null | 2019-10-03T04:12:13 | 2019-10-03T04:17:27 | 2021-06-10T19:01:08 |
Python
|
[
{
"alpha_fraction": 0.6178451180458069,
"alphanum_fraction": 0.627946138381958,
"avg_line_length": 24.826086044311523,
"blob_id": "9157277900cecc1214f8c67a9e3c4651edbfd20a",
"content_id": "4ac2a3e830860e05ed62cf8768369930d449f308",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 594,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 23,
"path": "/dbapp/models.py",
"repo_name": "mehuldhokia/demo-dbcon",
"src_encoding": "UTF-8",
"text": "from django.db import models\n\n# Create your models here.\n\nclass friends (models.Model):\n\tfname = models.CharField(max_length=30)\n\tage = models.IntegerField()\n\n\tdef __str__(self):\n\t\treturn '%2d - %s - %4d\\n' % (self.id, self.fname, self.age)\n\t\t#return '\\nID : %d\\nName : %s\\nAge: %d\\n' % (self.id, self.fname, self.age)\n\n\t'''\n\tdef __unicode__(self):\n\t\treturn u'\\nID : %d\\nName : %s\\nAge: %d\\n' % (self.id, self.fname, self.age)\n\t'''\n\nclass event (models.Model):\n\tename = models.CharField(max_length=30)\n\tdate = models.DateField()\n\n\tdef __str__(self):\n\t\treturn 'Event Name : %s\\n' % (self.ename)\t"
},
{
"alpha_fraction": 0.6521239876747131,
"alphanum_fraction": 0.6572904586791992,
"avg_line_length": 29.578947067260742,
"blob_id": "654ed1565a7d7f699f3a452e35b08f06cc147fdd",
"content_id": "6aeeefb463cf89754a1d4d7c5f597f8d0e26ed92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1742,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 57,
"path": "/dbapp/views.py",
"repo_name": "mehuldhokia/demo-dbcon",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\n\nfrom django.http import HttpResponse, HttpResponseRedirect\n\nfrom dbapp.models import friends\nfrom .forms import NameForm\n\n# Create your views here.\ndef site_info(request):\n\tsite = \"<h1>Friends Information</h1>\"\n\tm = \"<a href='/'>Home</a><br>\"\n\tm += \"<a href='fi/'>Add Friend</a><br>\"\n\tm += \"<a href='f/'>View Friends</a><br>\"\n\tm += \"<a href='fd/'>Remove Friends</a><br>\"\n\tm += \"<a href='fu/'>Edit Friends</a><br>\"\n\treturn HttpResponse(site + \"<hr>\" + m + \"<hr>\")\n\n# For Page Friend Insertion Form\ndef frnd_ins(request):\n\tfi = friends(fname='Kumbhkaran', age=38)\n\tfi.save()\n\treturn HttpResponse(\"Record has been inserted...\")\n\n# For Page View Friend Information\ndef frnd_read(request):\n\tf = friends.objects.all()\n\treturn HttpResponse(f)\n\ndef frnd_del(request):\n\tfriends.objects.filter(id=12).delete()\n\treturn HttpResponse(\"Record has been deleted...\")\n\ndef frnd_edit(request):\n\tfriends.objects.filter(id=5).update(age=20)\n\treturn HttpResponse(\"Record has been updated...\")\n\ndef get_name(request):\n # if this is a POST request we need to process the form data\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = NameForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n # process the data in form.cleaned_data as required\n # ...\n # redirect to a new URL:\n return HttpResponseRedirect('/thanks')\n # return HttpResponse(\"Thanks\")\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = NameForm()\n\n return render(request, 'name.html', {'form': form})\n\ndef thankyou(request):\n\treturn render(request, 'thanks.html')"
},
{
"alpha_fraction": 0.5625,
"alphanum_fraction": 0.5625,
"avg_line_length": 14,
"blob_id": "4ac0136aafa1646cc8d3f17161dba601626bf8b9",
"content_id": "44eda0f1fb266e42fd114aedaf4f83be2be23d98",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 16,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 1,
"path": "/README.md",
"repo_name": "mehuldhokia/demo-dbcon",
"src_encoding": "UTF-8",
"text": "\"# demo-dbcon\" \n"
}
] | 3 |
Jerryg6j3/prelabParser
|
https://github.com/Jerryg6j3/prelabParser
|
a3012532fa58d001c700a4f92623e32b6c4d0daa
|
62ecb11c5868c94470360b3f432c097867cfcf0a
|
e4623758b9139d7bb6b63fa685a9847ffad3cdc4
|
refs/heads/master
| 2016-09-14T03:13:55.954268 | 2016-05-17T17:28:59 | 2016-05-17T17:28:59 | 55,964,874 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6207792162895203,
"alphanum_fraction": 0.6363636255264282,
"avg_line_length": 17.33333396911621,
"blob_id": "7290fecb279b4b4ab96d391d0bb0d5a1987c9a8a",
"content_id": "66a01aeb2f39549bca183d9e07cf2e719dbd3efb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 21,
"path": "/main.py",
"repo_name": "Jerryg6j3/prelabParser",
"src_encoding": "UTF-8",
"text": "import prelabParser\n\nf = open('../studentInfo/studentList', 'r')\ntable = []\nfor i in f:\n\tx = i.split()\n\tif len(x) is 0:\n\t\tpass\n\telse:\n\t\ttable.append(x)\nquestionList = []\nfor i in range(0, len(table)):\n\tprint('\\n', i, ':')\n\ttemp = prelabParser.getQuestions( table[i][2], '10')\n\tif len(temp) is 0:\n\t\tcontinue\n\tquestionList.append( temp)\n\tfor x in temp:\n\t\tprint(x)\n\n#print( questionList)\n"
},
{
"alpha_fraction": 0.6984127163887024,
"alphanum_fraction": 0.7061346769332886,
"avg_line_length": 29.259740829467773,
"blob_id": "e638bf7b18bf1c602f42dd690316a98b22fd4d6c",
"content_id": "ebc28cba8fca80ccb7f9e7b5143f363ab72c2786",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2331,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 77,
"path": "/prelabParser.py",
"repo_name": "Jerryg6j3/prelabParser",
"src_encoding": "UTF-8",
"text": "import urllib.request\nimport re\nimport logging, sys\n\ntagPattern = re.compile('<[^>]*>')\nlineofEng = re.compile('\\n[a-zA-z .,()0-9]+\\n')\nmultipleNewline = re.compile('\\n+')\n\ndef getQuestions(studentGithubUrl, labNum):\n\tpattern = re.compile('[lL]ab[ _]*'+labNum)\n\tURL = studentGithubUrl+'/wiki'\n\ttargetStart = b\"boxed-group-inner wiki-auxiliary-content wiki-auxiliary-content-no-bg\"\n\tlabsUrls = []\n\ttargetEnd = b\"</div>\"\n\n\t# get the entire webpage\n\twith urllib.request.urlopen(URL) as urlResult:\n\t\twiki = urlResult.read()\n\t\n\t# cut out the wiki pages catalogue section from the entire webpage\n\tstartIndex = wiki.find(targetStart)\n\twiki = wiki[startIndex:]\n\tendIndex = wiki.find(targetEnd)\n\twiki = wiki[:endIndex]\n\twiki = wiki.decode(\"utf-8\")\n\t\n\t# split the catalogue entries\n\threfSplit = wiki.split('a href=\"')\n\tlabUrl = ''\n\tfor i in hrefSplit:\n\t\tif pattern.search(i) is not None:\n\t\t\tlabUrl = i.split('\"')[0]\n\t\t\t#print(i.split('\"')[0])\n\t\t\t#logging.debug(i.split('\"')[0])\n\t#print()\n\t\n\t# get the prelab url for certain lab\n\tif labUrl is '':\n\t\tprint(\"no target prelab found\")\n\t#print(labUrl)\n\t#logging.debug(labUrl)\n\t\n\t# get the prelab page\n\tlabPage = ''\n\tgithubURL = 'https://github.com'\n\t#print(githubURL+labUrl)\n\t#logging.debug(githubURL+labUrl)\n\treq = urllib.request.Request(url=githubURL+labUrl, method='GET')\n\twith urllib.request.urlopen(req) as labUrlResult:\n\t\tlabPage = labUrlResult.read()\n\t\n\t# extract the question\n\tlabPage = labPage.decode(\"utf-8\")\n\tmarkdownBody = labPage[labPage.find('<div class=\"markdown-body\">'):]\n\tend = markdownBody.find(\"</div>\")\n\tmarkdownBody = markdownBody[:end]\n\n\tmarkdownBody = re.sub(tagPattern, '', markdownBody)\n\tmarkdownBody += \"\\n\\nEND\\n\\n\"\n\t#logging.debug(markdownBody)\n\tmarkdownBodySplit = markdownBody.split(\"Questions about the topic or our lab\")\n\tquestionList = []\n\tfor i in range(1, len(markdownBodySplit)):\n\t\tend = re.search(lineofEng, markdownBodySplit[i]).start()\n\t\t#logging.debug(end)\n\n\t\tquestionList.append(re.sub(multipleNewline, '\\n', markdownBodySplit[i][:end].strip()))\n\t\t#logging.debug(markdownBodySplit[i][:end])\n\treturn questionList\n\t\t\n\nif __name__ == \"__main__\":\n\tlogging.basicConfig(stream=sys.stderr, level=logging.DEBUG)\n\tstudentGithubUrl = \"https://github.com/chunyou0830/EE2405/wiki\"\n\tlabNum = \"10\"\n\tquestions = getQuestions(studentGithubUrl, labNum)\n\tprint(questions)\n\n"
}
] | 2 |
alexeiskachykhin/node-alienfx
|
https://github.com/alexeiskachykhin/node-alienfx
|
0059e5969a24f29166f93714de24b338395beb69
|
a87d77bbab0f93476d72770e2a708006370bceca
|
bd62e6f3f5abbe4bba3291fbf10fc9e8a5eec802
|
refs/heads/master
| 2020-12-09T14:32:35.726871 | 2016-09-07T20:50:22 | 2016-09-07T20:50:22 | 25,884,236 | 8 | 2 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5777438879013062,
"alphanum_fraction": 0.5807926654815674,
"avg_line_length": 20.129032135009766,
"blob_id": "61ea831dd2ceddeb386b4068ae75994e05934042",
"content_id": "82d7842318bd04b79fb0e22a84f18e5ece8040e0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 656,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 31,
"path": "/tests/all.js",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "var Mocha = require('mocha');\nvar utilities = require('./utilities');\n\n\nvar mocha = new Mocha({\n reporter: 'spec'\n});\n\nutilities.ask.whichTestsToRun([\n 'Structural Tests',\n 'Behavioral Tests'], function (answers) {\n\n var testModules = {\n 'tests/structural/exports.js': answers[0],\n 'tests/behavioral/exports.js': answers[1]\n };\n\n\n Object.keys(testModules).forEach(function (testModule) {\n if (testModules[testModule]) {\n mocha.addFile(testModule);\n }\n });\n\n\n mocha.run(function (failures) {\n process.on('exit', function () {\n process.exit(failures);\n });\n });\n});\n\n"
},
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.7264957427978516,
"avg_line_length": 18.66666603088379,
"blob_id": "ba276a7f825bca4532644b710c60afa86c2250ae",
"content_id": "e8417a2c7c7f42120d2fafa14d387f912463b1c9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 117,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 6,
"path": "/sources/binding/sync/alienfxSync.h",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <node.h>\n\n\nvoid InitSyncBindings(v8::Local<v8::Object> exports, v8::Local<v8::Object> module);"
},
{
"alpha_fraction": 0.7021019458770752,
"alphanum_fraction": 0.7062907814979553,
"avg_line_length": 28.34551429748535,
"blob_id": "8d3a55490e47c1faf6805c38de030649c60e9ef5",
"content_id": "4b48811c3f770b7a1a9d1f5c9aade2fa622b1339",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 26499,
"license_type": "permissive",
"max_line_length": 575,
"num_lines": 903,
"path": "/README.md",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "\n\nnode-alienfx\n============\n\n[Node.js][Node] native extension for Dell [AlienFX][AlienFX] API.\n\n\nThis module offers bindings for AlienFX API provided by AlienFX.dll. The main design goal of this project is to keep JavaScript bindings close to their native counterparts as much as possible. It allows line-by-line porting of existing AlienFX enabled apps to [Node.js][Node]. Provided APIs feels bit alien to JavaScript so high-level wrapper around `node-alienfx` is comming soon. Stay tuned.\n\nInstallation\n------------\nFirst of all make sure that AlienFX.dll is installed on your system, the easiest way to do so - install Alienware Command Center.\n\nNPM package is comming soon...\n\nCompatibility\n-------------\n**Operating Systems**: Windows\n\n**Node**: 4.4.5 (32 bit, unfortunatelly there is a bug in 64-bit version of LightFX.dll that prevents AlienFX from initializing correctly)\n\n\nCurrently we are bound to operating systems that AlienFX.dll can run on. Strictly speaking it is possible to bypass [AlienFX][AlienFX] API and talk directly to the underlaying hardware, which requires us to send byte arrays to USB HID device. This will allow to support wider range of operating systems, but it is significantly harder to implement and what's more important, all of the device differences have to be handled. Awesome libraries implemented this way exist [pyalienfx][pyalienfx]. Please let me know if you really interested to see this module working on Linux. \n\nExample\n-------\n### Async\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n \n var position = alienfx.Position.ALL;\n var color = alienfx.Color.GREEN | alienfx.Brightness.FULL;\n \n alienfx.light(position, color);\n alienfx.update();\n \n alienfx.release();\n});\n```\n\n### Sync\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initializeSync();\nalienfx.reset();\n\nvar position = alienfx.Position.ALL;\nvar color = alienfx.Color.GREEN | alienfx.Brightness.FULL;\n\nalienfx.light(position, color);\nalienfx.update();\n\nalienfx.releaseSync();\n```\n\nMore samples can be found in samples folder. It contains line-by-line ported apps from [AlienFX][AlienFX] SDK.\n\nBuild & Test\n-----\nInstall [node-gyp]:\n```javascript\nnpm install -g node-gyp\n```\n\nBuild:\n```javascript\nnode-gyp configure\nnode-gyp build\n```\n\nTest:\n```javascript\nnpm test\n```\n\n\nDebugging\n---------\nIn order to debug extension in Visual Studio, open ```build/Release/binding.sln``` go to ```Project Property Settings -> Debugging``` and put following settings:\n\n| Property | Value |\n| ----------------- |------------------------------------------------------|\n| Command | node.exe |\n| Command Arguments | ./tests/all.js |\n| Working Directory | $(ProjectDir)..\\ |\n\n\nThis will allow to run unit tests with Visual Studio native debugger attached every time you hit F5.\n\n\nAPI Reference\n---\n- [Functions & Properties](#functions-&-properties)\n - [isAvailable -> Boolean](#isavailable---boolean)\n - [initialize([callback]) -> Undefined](#initializecallback---undefined)\n - [initializeSync() -> Number](#initializesync---number)\n - [release([callback]) -> Undefined](#releasecallback---undefined)\n - [releaseSync() -> Number](#releasesync---number)\n - [getVersion([callback]) -> Undefined](#getversioncallback---undefined)\n - [getVersionSync(*out* version) -> Number](#getversionsyncout-version---number)\n - [reset() -> Number](#reset---number)\n - [update() -> Number](#update---number)\n - [updateDefault() -> Number](#updatedefault---number)\n - [light(position, color) -> Number](#lightposition-color---number)\n - [actionColor(position, action, color) -> Number](#actioncolorposition-action-color---number)\n - [actionColorEx(position, action, primaryColor, secondaryColor) -> Number](#actioncolorexposition-action-primarycolor-secondarycolor---number)\n - [getNumDevices([callback]) -> Undefined](#getnumdevicescallback---undefined)\n - [getNumDevicesSync(*out* numberOfDevices) -> Number](#getnumdevicessyncout-numberofdevices---number)\n - [getDeviceDescription(deviceIndex[, callback]) -> Undefined](#getdevicedescriptiondeviceindex-callback---undefined)\n - [getDeviceDescriptionSync(deviceIndex, *out* deviceDescription) -> Number](#getdevicedescriptionsyncdeviceindex-out-devicedescription---number)\n - [getNumLights(deviceIndex[, callback]) -> Undefined](#getnumlightsdeviceindex-callback---undefined)\n - [getNumLightsSync(deviceIndex, *out* numberOfLights) -> Undefined](#getnumlightssyncdeviceindex-out-numberoflights---undefined)\n - [getLightDescription(deviceIndex, lightIndex[, callback]) -> Undefined](#getlightdescriptiondeviceindex-lightindex-callback---undefined)\n - [getLightDescriptionSync(deviceIndex, lightIndex, *out* lightDescription) -> Undefined](#getlightdescriptionsyncdeviceindex-lightindex-out-lightdescription---undefined)\n - [getLightLocation(deviceIndex, lightIndex[, callback]) -> Undefined](#getlightlocationdeviceindex-lightindex-callback---undefined)\n - [getLightLocationSync(deviceIndex, lightIndex, *out* lightLocation) -> Undefined](#getlightlocationsyncdeviceindex-lightindex-out-lightlocation---undefined)\n - [getLightColor(deviceIndex, lightIndex[, callback]) -> Undefined](#getlightcolordeviceindex-lightindex-callback---undefined)\n - [getLightColorSync(deviceIndex, lightIndex, *out* lightColor) -> Number](#getlightcolorsyncdeviceindex-lightindex-out-lightcolor---number)\n - [setLightColor(deviceIndex, lightIndex, color) -> Number](#setlightcolordeviceindex-lightindex-color---number)\n - [setLightActionColor(deviceIndex, lightIndex, action, color) -> Number](#setlightactioncolordeviceindex-lightindex-action-color---number)\n - [setLightActionColorEx(deviceIndex, lightIndex, action, primaryColor, secondaryColor) -> Number](#setlightactioncolorexdeviceindex-lightindex-action-primarycolor-secondarycolor---number)\n - [setTiming(timing) -> Number](#settimingtiming---number)\n- [Data Structures](#data-structures)\n - [Result](#result)\n - [Color](#color)\n - [Brightness](#brightness)\n - [DeviceType](#devicetype)\n - [Position](#position)\n - [Action](#action)\n\n### Functions & Properties\n\n#### isAvailable -> Boolean\n\n*Description*: Indicates whether AlienFX.dll is found. If its not, all other functions will fail.\n\n```javascript\nvar alienfx = require('alienfx');\nalienfx.isAvailable; // Boolean\n```\n\n#### initialize([callback]) -> Undefined\n\n*Description*: Initializes Alineware AlienFX system. It must be called prior to other library calls made. If this function is not called, the system will not be initialized and the other library functions will return ```Result.NOINIT``` or ```Result.FAILURE```.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n data.result; // Status code\n});\n```\n\n\n#### initializeSync() -> Number\n\n*Description*: Synchronously initializes Alineware AlienFX system. It must be called prior to other library calls made. If this function is not called, the system will not be initialized and the other library functions will return ```Result.NOINIT``` or ```Result.FAILURE```.\n\n*Behavior*: Blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\nvar result = alienfx.initializeSync();\n\nresult; // Status code\n```\n\n\n#### release([callback]) -> Undefined\n\n*Description*: Releases Alienware AlienFX system. It may be called when the system is no longer needed. An application may choose to release the system and reinitialize it again, in response to a device arrival notification. Doing so will account for new devices added while the application is running.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.release(function (err, data) {\n data.result; // Status code\n });\n});\n```\n\n\n#### releaseSync() -> Number\n\n*Description*: Synchronously releases Alienware AlienFX system. It may be called when the system is no longer needed. An application may choose to release the system and reinitialize it again, in response to a device arrival notification. Doing so will account for new devices added while the application is running.\n\n*Behavior*: Blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n var result = alienfx.releaseSync();\n result; // Status code\n});\n```\n\n\n#### getVersion([callback]) -> Undefined\n\n*Description*: Gets version of AlienFX SDK installed.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.getVersion(function (err, data) {\n data.version; // String\n data.result; // Status code\n \n alienfx.release();\n });\n});\n```\n\n\n#### getVersionSync(*out* version) -> Number\n\n*Description*: Gets version of AlienFX SDK installed in ```version``` argument and status code as return value.\n\n*Behavior*: Blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n \n result = alienfx.getVersionSync(out);\n \n result; // Status code\n out.version; // String\n \n alienfx.release();\n});\n```\n\n\n#### reset() -> Number\n\n*Description*: Sets all lights in the Alienware AlienFX system to their \"off\" or uncolored state. Note that the change to the physical lights do not occur immediately. These changes occur only after a call to ```update```. For example, to disable all lights, call ```reset``` followed by ```update```.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n var result = alienfx.reset();\n alienfx.release();\n \n result; // Status code\n});\n```\n\n\n#### update() -> Number\n\n*Description*: Updates the Alienware AlienFX system by submitting any state changes (since the last call to ```reset```) to hardware.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n var result = alienfx.update();\n alienfx.release();\n \n result; // Status code\n});\n```\n\n\n#### updateDefault() -> Number\n\n*Description*: Updates the Alienware AlienFX system by submitting any state changes (since the last call to ```reset```) to hardware, as well as setting the appropriate flags to enable the updated state to be the new power-on default. **Important Note**: as of now, this function has no effect. Heads up for future updates.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n var result = alienfx.updateDefault();\n alienfx.release();\n \n result; // Status code\n});\n```\n\n\n#### light(position, color) -> Number\n\n*Description*: Submits a light command into the command queue, which sets the current color of any lights within the provided location mask to the provided color setting. Similar to ```setLightColor```, settings are changed in the active state and must be submitted with a call to ```update```. Location mask is a 32-bit field, where each of the first 27 bits represents a zone in the virtual cube representing the system. Color is packed into a 32-bit value as ARGB, with the alpha value corresponding to brightness.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n \n var position = alienfx.Position.ALL;\n var color = alienfx.Color.GREEN | alienfx.Brightness.FULL;\n \n var result = alienfx.light(position, color);\n result; // Status code\n \n alienfx.update();\n alienfx.release();\n});\n```\n\n#### actionColor(position, action, color) -> Number\n\n*Description*: Sets the primary color and an action type for any devices with lights in a location. This function changes the current primary color and action type stored in the active state since the last ```reset``` call. It does NOT immediately update the physical light settings, until a call to ```update``` is made. If the action type is a morph, then the secondary color for the action is black.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n\n var position = alienfx.Position.ALL;\n var action = alienfx.Action.MORPH;\n var color = alienfx.Color.GREEN | alienfx.Brightness.FULL;\n\n alienfx.actionColor(position, action, color);\n alienfx.update();\n \n alienfx.release();\n});\n```\n\n#### actionColorEx(position, action, primaryColor, secondaryColor) -> Number\n\n*Description*: Sets the primary and secondary color and an action type for any devices with lights in a location. It does NOT immediately update the physical light settings, until a call to ```update``` is made. If the action type is not a morph, then the secondary color is ignored.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n\n var position = alienfx.Position.ALL;\n var action = alienfx.Action.MORPH;\n var primaryColor = alienfx.Color.GREEN | alienfx.Brightness.FULL;\n var secondaryColor = alienfx.Color.RED | alienfx.Brightness.FULL;\n\n alienfx.actionColorEx(position, action, primaryColor, secondaryColor);\n alienfx.update();\n \n alienfx.release();\n});\n```\n\n#### getNumDevices([callback]) -> Undefined\n\n*Description*: Gets the number of Alienware AlienFX devices attached to the system.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.getNumDevices(function (err, data) {\n data.result; // Status code\n data.numberOfDevices; // Number\n \n alienfx.release();\n });\n});\n```\n\n\n#### getNumDevicesSync(*out* numberOfDevices) -> Number\n\n*Description*: Synchronously gets the number of Alienware AlienFX devices attached to the system.\n\n*Behavior*: Blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getNumDevicesSync(out);\n \n result; // Status code\n out.numberOfDevices; // Number\n \n alienfx.release();\n});\n```\n\n#### getDeviceDescription(deviceIndex[, callback]) -> Undefined\n\n*Description*: Gets the description and type of a device attached to the system.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nvar alienfx = require('alienfx');\n\nalienfx.initialize(function (err, data) {\n alienfx.getDeviceDescription(0, function (err, data) {\n data.result; // Status code\n data.model; // String\n data.type; // Number\n \n alienfx.release();\n });\n});\n```\n\n#### getDeviceDescriptionSync(deviceIndex, *out* deviceDescription) -> Number\n\n*Description*: Synchronously gets the description and type of a device attached to the system.\n\n*Behavior*: Blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getDeviceDescriptionSync(0, out);\n \n result; // Status code\n out.model; // String\n out.type; // Number\n \n alienfx.release();\n});\n```\n\n\n#### getNumLights(deviceIndex[, callback]) -> Undefined\n\n*Description*: Gets the number of Alienware AlienFX lights attached to a device in the system.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.getNumLights(0, function (err, data) {\n data.result; // Status code\n data.numberOfLights; // Number\n \n alienfx.release();\n });\n});\n```\n\n#### getNumLightsSync(deviceIndex, *out* numberOfLights) -> Undefined\n\n*Description*: Synchronously gets the number of Alienware AlienFX lights attached to a device in the system.\n\n*Behavior*: Blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getNumLightsSync(0, out);\n \n result; // Status code\n out.numberOfLights; // Number\n \n alienfx.release();\n});\n```\n\n#### getLightDescription(deviceIndex, lightIndex[, callback]) -> Undefined\n\n*Description*: Gets the description of a light attached to the system.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.getLightDescription(0, 0, function (err, data) {\n data.result; // Status code\n data.lightDescription; // String\n \n alienfx.release();\n });\n});\n```\n\n#### getLightDescriptionSync(deviceIndex, lightIndex, *out* lightDescription) -> Undefined\n\n*Description*: Synchronously gets the description of a light attached to the system.\n\n*Behavior*: Blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getLightDescriptionSync(0, 0, out);\n \n result; // Status code\n out.lightDescription; // String\n \n alienfx.release();\n});\n```\n\n\n#### getLightLocation(deviceIndex, lightIndex[, callback]) -> Undefined\n\n*Description*: Gets the location of a light attached to the system.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.getLightLocation(0, 0, function (err, data) {\n data.result; // Status code\n data.lightLocation.x; // Number\n data.lightLocation.y; // Number\n data.lightLocation.z; // Number\n \n alienfx.release();\n });\n});\n```\n\n\n#### getLightLocationSync(deviceIndex, lightIndex, *out* lightLocation) -> Undefined\n\n*Description*: Synchronously gets the location of a light attached to the system.\n\n*Behavior*: Blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getLightLocationSync(0, 0, out);\n \n result; // Status code\n out.lightLocation.x; // Number\n out.lightLocation.y; // Number\n out.lightLocation.z; // Number\n \n alienfx.release();\n});\n```\n\n\n#### getLightColor(deviceIndex, lightIndex[, callback]) -> Undefined\n\n*Description*: Gets the color of a light attached to the system. This function provides the current color stored in the active state. It does not necessarily represent the color of the physical light. To ensure that the returned value represents the state of the physical light, call this function immediately after a call to ```update``` and before the next call to ```reset```. Also note that some hardware has limitations such as index color, which preclude obtaining the exact RGB representation.\n\n*Behavior*: Non-blocking\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.getLightColor(0, 0, function (err, data) {\n data.result; // Status code\n data.lightColor.red; // Number\n data.lightColor.green; // Number\n data.lightColor.blue; // Number\n data.lightColor.brightness; // Number\n \n alienfx.release();\n });\n});\n```\n\n\n#### getLightColorSync(deviceIndex, lightIndex, *out* lightColor) -> Number\n\n*Description*: Synchronously gets the color of a light attached to the system. This function provides the current color stored in the active state. It does not necessarily represent the color of the physical light. To ensure that the returned value represents the state of the physical light, call this function immediately after a call to ```update``` and before the next call to ```reset```. Also note that some hardware has limitations such as index color, which preclude obtaining the exact RGB representation.\n\n*Behavior*: Blocking\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n var out = {};\n var result;\n\n result = alienfx.getLightColorSync(0, 0, out);\n \n result; // Status code\n out.lightColor.red; // Number\n out.lightColor.green; // Number\n out.lightColor.blue; // Number\n out.lightColor.brightness; // Number\n \n alienfx.release();\n});\n```\n\n\n#### setLightColor(deviceIndex, lightIndex, color) -> Number\n\n*Description*: Submits a light command into the command queue, which sets the current color of a light to the provided color value. This function changes the current color stored in active state since the last reset. It does not immediately update the physical light settings, instead requiring a call to ```update```.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n \n var color = {\n red: 0xFF,\n green: 0x00,\n blue: 0x00,\n brightness: 0xFF\n };\n\n var result = alienfx.setLightColor(0, 0, color);\n result; // Status code\n \n alienfx.update();\n alienfx.release();\n});\n```\n\n\n#### setLightActionColor(deviceIndex, lightIndex, action, color) -> Number\n\n*Description*: Sets the primary color and an action type of a light. This function changes the current color and action type stored in the active state since the last ```reset``` call. It does NOT immediately update the physical light settings, until a call to ```update``` is made. If the action type is a morph, then the secondary color for the action is black.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n \n var color = {\n red: 0xFF,\n green: 0x00,\n blue: 0x00,\n brightness: 0xFF\n };\n \n var action = alienfx.Action.MORPH;\n\n var result = alienfx.setLightActionColor(0, 0, action, color);\n result; // Status code\n \n alienfx.update();\n alienfx.release();\n});\n```\n\n#### setLightActionColorEx(deviceIndex, lightIndex, action, primaryColor, secondaryColor) -> Number\n\n*Description*: Sets the primary and secondary colors and an action type of a light. This function changes the current color and action type stored in the active state since the last ```reset``` call. It does NOT immediately update the physical light settings, until a call to ```update``` is made. If the action type is a morph, then the secondary color for the action is black.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n \n var primaryColor = {\n red: 0xFF,\n green: 0x00,\n blue: 0x00,\n brightness: 0xFF\n };\n\n var secondaryColor = {\n red: 0x00,\n green: 0xFF,\n blue: 0x00,\n brightness: 0xFF\n };\n \n var action = alienfx.Action.MORPH;\n\n var result = alienfx.setLightActionColorEx(0, 0, action, primaryColor, secondaryColor);\n result; // Status code\n \n alienfx.update();\n alienfx.release();\n});\n```\n\n\n#### setTiming(timing) -> Number\n\n*Description*: Sets the tempo for actions. This function changes the current tempo or timing to be used for the next actions. It does NOT immediately update the physical light settings, until a call to ```update``` is made.\n\n*Behavior*: Non-blocking.\n\n\n```javascript\nalienfx.initialize(function (err, data) {\n alienfx.reset();\n\n var result = alienfx.setTiming(200);\n result; // Status code\n \n alienfx.update();\n alienfx.release();\n});\n```\n\n\n### Data Structures\n\n#### Result\n\n*Description*: Represents status code of an operation.\n\n*Type*: Number\n\n*Predefined values*:\n```javascript\nalienfx.Result.SUCCESS\nalienfx.Result.FAILURE\nalienfx.Result.NOINIT\nalienfx.Result.NODEVS\nalienfx.Result.NOLIGHTS\nalienfx.Result.BUFFSIZE\n```\n\n#### Color\n\n*Description*: 32-bit value as ARGB, with the alpha value corresponding to brightness.\n\n*Type*: Number\n\n*Predefined values*:\n```javascript\nalienfx.Color.OFF\nalienfx.Color.BLACK\nalienfx.Color.RED\nalienfx.Color.GREEN\nalienfx.Color.BLUE\nalienfx.Color.WHITE\nalienfx.Color.YELLOW\nalienfx.Color.ORANGE\nalienfx.Color.PINK\nalienfx.Color.CYAN\n```\n \n\n#### Brightness\n\n*Description*: 32-bit value represents brightness of a light. Actual brightness is encoded in 4-th byte of a value.\n\n*Type*: Number\n\n*Predefined values*:\n```javascript\nalienfx.Color.FULL\nalienfx.Color.HALF\nalienfx.Color.MIN\n```\n\n\n#### DeviceType\n\n*Description*: Represents type of AlienFX device.\n\n*Type*: Number.\n\n*Predefined values*:\n```javascript\nalienfx.DeviceType.UNKNOWN\nalienfx.DeviceType.NOTEBOOK\nalienfx.DeviceType.DESKTOP\nalienfx.DeviceType.SERVER\nalienfx.DeviceType.DISPLAY\nalienfx.DeviceType.MOUSE\nalienfx.DeviceType.KEYBOARD\nalienfx.DeviceType.GAMEPAD\nalienfx.DeviceType.SPEAKER\nalienfx.DeviceType.OTHER\n```\n\n#### Position\n\n*Description*: Represents position of a light.\n\n*Type*: Number\n\n*Predefined values*:\n```javascript\n// Near Z-plane light definitions\nalienfx.Position.FRONT_LOWER_LEFT\nalienfx.Position.FRONT_LOWER_CENTER\nalienfx.Position.FRONT_LOWER_RIGHT\nalienfx.Position.FRONT_MIDDLE_LEFT\nalienfx.Position.FRONT_MIDDLE_CENTER\nalienfx.Position.FRONT_MIDDLE_RIGHT\nalienfx.Position.FRONT_UPPER_LEFT\nalienfx.Position.FRONT_UPPER_CENTER\nalienfx.Position.FRONT_UPPER_RIGHT\n\n// Mid Z-plane light definitions\nalienfx.Position.MIDDLE_LOWER_LEFT\nalienfx.Position.MIDDLE_LOWER_CENTER\nalienfx.Position.MIDDLE_LOWER_RIGHT\nalienfx.Position.MIDDLE_MIDDLE_LEFT\nalienfx.Position.MIDDLE_MIDDLE_CENTER\nalienfx.Position.MIDDLE_MIDDLE_RIGHT\nalienfx.Position.MIDDLE_UPPER_LEFT\nalienfx.Position.MIDDLE_UPPER_CENTER\nalienfx.Position.MIDDLE_UPPER_RIGHT\n\n// Far Z-plane light definitions\nalienfx.Position.REAR_LOWER_LEFT\nalienfx.Position.REAR_LOWER_CENTER\nalienfx.Position.REAR_LOWER_RIGHT\nalienfx.Position.REAR_MIDDLE_LEFT\nalienfx.Position.REAR_MIDDLE_CENTER\nalienfx.Position.REAR_MIDDLE_RIGHT\nalienfx.Position.REAR_UPPER_LEFT\nalienfx.Position.REAR_UPPER_CENTER\nalienfx.Position.REAR_UPPER_RIGHT\n\n// Combination bit masks\nalienfx.Position.ALL\nalienfx.Position.ALL_RIGHT\nalienfx.Position.ALL_LEFT\nalienfx.Position.ALL_UPPER\nalienfx.Position.ALL_LOWER\nalienfx.Position.ALL_FRONT\nalienfx.Position.ALL_REAR\n```\n\n#### Action\n\n*Description*: Represents type of an action that can be applied to a light.\n\n*Type*: Number\n\n*Predefined values*:\n```javascript\nalienfx.Action.MORPH\nalienfx.Action.PULSE\nalienfx.Action.COLOR\n```\n\n\n[Node]: http://nodejs.org\n[AlienFX]: http://www.alienware.com/landings/alienfx/\n[pyalienfx]: https://code.google.com/p/pyalienfx/\n[node-gyp]: https://github.com/TooTallNate/node-gyp\n"
},
{
"alpha_fraction": 0.7278077602386475,
"alphanum_fraction": 0.7376164793968201,
"avg_line_length": 51.20512771606445,
"blob_id": "0bbaf90a7f4bbaf45e92a41d191a32c7b5f31b6b",
"content_id": "05b638d980688c05abc68a266f86b91a70b11ee2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2039,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 39,
"path": "/sources/api/windows/alienfxApi.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <windows.h>\n#include \"../alienfxApi.h\"\n\n\n_ALIENFX_API DiscoverAlienFxAPI()\n{\n HMODULE hLibrary = LoadLibrary(LFX_DLL_NAME);\n\n _ALIENFX_API api = { 0 };\n\n if (hLibrary)\n {\n api.IsAvailable = true;\n api.GetVersion = (LFX2GETVERSION)GetProcAddress(hLibrary, LFX_DLL_GETVERSION);\n api.Initialize = (LFX2INITIALIZE)GetProcAddress(hLibrary, LFX_DLL_INITIALIZE);\n api.Release = (LFX2RELEASE)GetProcAddress(hLibrary, LFX_DLL_RELEASE);\n api.Reset = (LFX2RESET)GetProcAddress(hLibrary, LFX_DLL_RESET);\n api.Update = (LFX2UPDATE)GetProcAddress(hLibrary, LFX_DLL_UPDATE);\n api.UpdateDefault = (LFX2UPDATEDEFAULT)GetProcAddress(hLibrary, LFX_DLL_UPDATEDEFAULT);\n api.Light = (LFX2LIGHT)GetProcAddress(hLibrary, LFX_DLL_LIGHT);\n api.ActionColor = (LFX2ACTIONCOLOR)GetProcAddress(hLibrary, LFX_DLL_ACTIONCOLOR);\n api.ActionColorEx = (LFX2ACTIONCOLOREX)GetProcAddress(hLibrary, LFX_DLL_ACTIONCOLOREX);\n api.GetNumDevices = (LFX2GETNUMDEVICES)GetProcAddress(hLibrary, LFX_DLL_GETNUMDEVICES);\n api.GetDeviceDescription = (LFX2GETDEVDESC)GetProcAddress(hLibrary, LFX_DLL_GETDEVDESC);\n api.GetNumLights = (LFX2GETNUMLIGHTS)GetProcAddress(hLibrary, LFX_DLL_GETNUMLIGHTS);\n api.GetLightDescription = (LFX2GETLIGHTDESC)GetProcAddress(hLibrary, LFX_DLL_GETLIGHTDESC);\n api.GetLightLocation = (LFX2GETLIGHTLOC)GetProcAddress(hLibrary, LFX_DLL_GETLIGHTLOC);\n api.GetLightColor = (LFX2GETLIGHTCOL)GetProcAddress(hLibrary, LFX_DLL_GETLIGHTCOL);\n api.SetLightColor = (LFX2SETLIGHTCOL)GetProcAddress(hLibrary, LFX_DLL_SETLIGHTCOL);\n api.SetLightActionColor = (LFX2SETLIGHTACTIONCOLOR)GetProcAddress(hLibrary, LFX_DLL_SETLIGHTACTIONCOLOR);\n api.SetLightActionColorEx = (LFX2SETLIGHTACTIONCOLOREX)GetProcAddress(hLibrary, LFX_DLL_SETLIGHTACTIONCOLOREX);\n api.SetTiming = (LFX2SETTIMING)GetProcAddress(hLibrary, LFX_DLL_SETTIMING);\n }\n\n return api;\n}\n\n\n_ALIENFX_API ALIENFX_API = DiscoverAlienFxAPI();\n\n\n\n"
},
{
"alpha_fraction": 0.6885949373245239,
"alphanum_fraction": 0.6932427883148193,
"avg_line_length": 27.835052490234375,
"blob_id": "0ed4495eead3fffaa3fbd31d3b4ba6e91daa4410",
"content_id": "f58b58fa58dd6dad93777ab92d81c3dd9033c29c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2797,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 97,
"path": "/sources/binding/contracts.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <sstream>\n\n#include \"contracts.h\"\n\nusing namespace std;\nusing namespace v8;\n\n\nbool Contracts::RequireNumberOfArguments(const v8::FunctionCallbackInfo<Value>& args, int requiredNumberOfArguments)\n{\n Isolate* isolate = args.GetIsolate();\n\n if (args.Length() < requiredNumberOfArguments)\n {\n ostringstream exceptionMessageStream;\n exceptionMessageStream << \"Function expects \" << requiredNumberOfArguments << \" parameters.\";\n\n string exceptionMessage = exceptionMessageStream.str();\n\n Local<Value> exception = Exception::Error(String::NewFromUtf8(isolate, exceptionMessage.c_str()));\n isolate->ThrowException(exception);\n\n return false;\n }\n\n return true;\n}\n\nbool Contracts::RequireObjectArgument(const v8::FunctionCallbackInfo<Value>& args, int argumentIndex)\n{\n Isolate* isolate = args.GetIsolate();\n\n if (!args[argumentIndex]->IsObject())\n {\n ostringstream exceptionMessageStream;\n exceptionMessageStream << \"Argument \" << argumentIndex + 1 << \" must be of type object.\";\n\n string exceptionMessage = exceptionMessageStream.str();\n\n Local<Value> exception = Exception::TypeError(String::NewFromUtf8(isolate, exceptionMessage.c_str()));\n isolate->ThrowException(exception);\n\n return false;\n }\n\n return true;\n}\n\nbool Contracts::RequireNumberArgument(const v8::FunctionCallbackInfo<Value>& args, int argumentIndex)\n{\n Isolate* isolate = args.GetIsolate();\n\n if (!args[argumentIndex]->IsNumber())\n {\n ostringstream exceptionMessageStream;\n exceptionMessageStream << \"Argument \" << argumentIndex + 1 << \" must be of type number.\";\n\n string exceptionMessage = exceptionMessageStream.str();\n\n Local<Value> exception = Exception::TypeError(String::NewFromUtf8(isolate, exceptionMessage.c_str()));\n isolate->ThrowException(exception);\n\n return false;\n }\n\n return true;\n}\n\nbool Contracts::RequireFunctionArgument(const v8::FunctionCallbackInfo<Value>& args, int argumentIndex)\n{\n Isolate* isolate = args.GetIsolate();\n\n if (!args[argumentIndex]->IsFunction())\n {\n ostringstream exceptionMessageStream;\n exceptionMessageStream << \"Argument \" << argumentIndex + 1 << \" must be of type function.\";\n\n string exceptionMessage = exceptionMessageStream.str();\n\n Local<Value> exception = Exception::TypeError(String::NewFromUtf8(isolate, exceptionMessage.c_str()));\n isolate->ThrowException(exception);\n\n return false;\n }\n\n return true;\n}\n\nbool Contracts::OptionalFunctionArgument(const v8::FunctionCallbackInfo<Value>& args, int argumentIndex)\n{\n if (argumentIndex >= args.Length())\n {\n return true;\n }\n\n return RequireFunctionArgument(args, argumentIndex);\n}\n"
},
{
"alpha_fraction": 0.7127937078475952,
"alphanum_fraction": 0.7389034032821655,
"avg_line_length": 33.90909194946289,
"blob_id": "3cdeb4edf5987ef15effa6b2a5f675ac017dd524",
"content_id": "4890a9255307a5138074019d7378dc6dba928232",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 383,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 11,
"path": "/sources/binding/objects/alienfxObjects.h",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <node.h>\n#include \"../../api/alienfxApi.h\"\n\n\nvoid ObjectToColor(v8::Handle<v8::Object> object, LFX_COLOR& color);\nvoid ColorToObject(const LFX_COLOR& color, v8::Handle<v8::Object> object);\nvoid PositionToObject(const LFX_POSITION& position, v8::Handle<v8::Object> object);\n\nvoid InitObjectBindings(v8::Local<v8::Object> exports, v8::Local<v8::Object> module);;"
},
{
"alpha_fraction": 0.6782674193382263,
"alphanum_fraction": 0.6920380592346191,
"avg_line_length": 28.954999923706055,
"blob_id": "3c95adb370ae2485f7da0169b6aff65f1cf4d898",
"content_id": "cb0f9ffd595f096005ca3ca80b6a8b6f1d169887",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 11982,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 400,
"path": "/sources/binding/sync/alienfxSync.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <node.h>\n#include <string>\n\n#include \"../contracts.h\"\n#include \"../objects/alienfxObjects.h\"\n#include \"../../api/alienfxApi.h\"\n\nusing namespace v8;\nusing namespace std;\n\n\nvoid GetVersionSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_OBJECT(args, 0);\n\n\n string version(LFX_DEF_STRING_SIZE, 0);\n\n\n LFX_RESULT result = ALIENFX_API.GetVersion(\n const_cast<char*>(version.c_str()),\n version.size());\n\n if (result == LFX_SUCCESS) {\n Local<Object> out = Local<Object>::Cast(args[0]);\n out->Set(String::NewFromUtf8(isolate, \"result\"), String::NewFromUtf8(isolate, version.c_str()));\n }\n\n args.GetReturnValue().Set(Number::New(isolate, result));\n}\n\nvoid InitializeSync(const FunctionCallbackInfo<Value>& args)\n{\n LFX_RESULT result = ALIENFX_API.Initialize();\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid ReleaseSync(const FunctionCallbackInfo<Value>& args)\n{\n LFX_RESULT result = ALIENFX_API.Release();\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid Reset(const FunctionCallbackInfo<Value>& args)\n{\n LFX_RESULT result = ALIENFX_API.Reset();\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid Update(const FunctionCallbackInfo<Value>& args)\n{\n LFX_RESULT result = ALIENFX_API.Update();\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid UpdateDefault(const FunctionCallbackInfo<Value>& args)\n{\n LFX_RESULT result = ALIENFX_API.UpdateDefault();\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid Light(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 2);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n\n\n unsigned int locationMask = args[0]->Uint32Value();\n unsigned int colorValue = args[1]->Uint32Value();\n\n LFX_RESULT result = ALIENFX_API.Light(locationMask, colorValue);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid ActionColor(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 3);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_NUMBER(args, 2);\n\n\n unsigned int locationMask = args[0]->Uint32Value();\n unsigned int action = args[1]->Uint32Value();\n unsigned int colorValue = args[2]->Uint32Value();\n\n LFX_RESULT result = ALIENFX_API.ActionColor(locationMask, action, colorValue);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid ActionColorEx(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 4);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_NUMBER(args, 2);\n REQUIRE_NUMBER(args, 3);\n\n\n unsigned int locationMask = args[0]->Uint32Value();\n unsigned int action = args[1]->Uint32Value();\n unsigned int primaryColorValue = args[2]->Uint32Value();\n unsigned int secondaryColorValue = args[3]->Uint32Value();\n\n LFX_RESULT result = ALIENFX_API.ActionColorEx(locationMask, action, primaryColorValue, secondaryColorValue);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetNumDevicesSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_OBJECT(args, 0);\n\n\n unsigned int numberOfDevices = 0;\n\n\n LFX_RESULT result = ALIENFX_API.GetNumDevices(&numberOfDevices);\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> out = Local<Object>::Cast(args[0]);\n out->Set(String::NewFromUtf8(isolate, \"numberOfDevices\"), Number::New(isolate, numberOfDevices));\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetDeviceDescriptionSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 2);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_OBJECT(args, 1);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned char deviceType = 0;\n string deviceDescription(LFX_DEF_STRING_SIZE, 0);\n\n\n LFX_RESULT result = ALIENFX_API.GetDeviceDescription(\n deviceIndex,\n const_cast<char*>(deviceDescription.c_str()),\n deviceDescription.size(),\n &deviceType);\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> out = Local<Object>::Cast(args[1]);\n out->Set(String::NewFromUtf8(isolate, \"model\"), String::NewFromUtf8(isolate, deviceDescription.c_str()));\n out->Set(String::NewFromUtf8(isolate, \"type\"), Number::New(isolate, deviceType));\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetNumLightsSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 2);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_OBJECT(args, 1);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int numberOfLights = 0;\n\n\n LFX_RESULT result = ALIENFX_API.GetNumLights(deviceIndex, &numberOfLights);\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> out = Local<Object>::Cast(args[1]);\n out->Set(String::NewFromUtf8(isolate, \"numberOfLights\"), Number::New(isolate, numberOfLights));\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetLightDescriptionSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 3);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_OBJECT(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n\n string lightDescription(LFX_DEF_STRING_SIZE, 0);\n\n\n LFX_RESULT result = ALIENFX_API.GetLightDescription(\n deviceIndex,\n lightIndex,\n const_cast<char*>(lightDescription.c_str()),\n lightDescription.size());\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> out = Local<Object>::Cast(args[2]);\n out->Set(String::NewFromUtf8(isolate, \"lightDescription\"), String::NewFromUtf8(isolate, lightDescription.c_str()));\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetLightLocationSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 3);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_OBJECT(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n\n LFX_POSITION lightLocation{ 0 };\n\n\n LFX_RESULT result = ALIENFX_API.GetLightLocation(deviceIndex, lightIndex, &lightLocation);\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> location = Object::New(isolate);\n PositionToObject(lightLocation, location);\n\n Local<Object> out = Local<Object>::Cast(args[2]);\n out->Set(String::NewFromUtf8(isolate, \"lightLocation\"), location);\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid GetLightColorSync(const FunctionCallbackInfo<Value>& args)\n{\n Isolate* isolate = args.GetIsolate();\n\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 3);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_OBJECT(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n\n LFX_COLOR lightColor{ 0 };\n\n\n LFX_RESULT result = ALIENFX_API.GetLightColor(deviceIndex, lightIndex, &lightColor);\n\n if (result == LFX_SUCCESS)\n {\n Local<Object> color = Object::New(isolate);\n ColorToObject(lightColor, color);\n\n Local<Object> out = Local<Object>::Cast(args[2]);\n out->Set(String::NewFromUtf8(isolate, \"lightColor\"), color);\n }\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid SetLightColor(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 3);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_OBJECT(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n Local<Object> color = Local<Object>::Cast(args[2]);\n\n LFX_COLOR lightColor{ 0 };\n ObjectToColor(color, lightColor);\n\n\n LFX_RESULT result = ALIENFX_API.SetLightColor(deviceIndex, lightIndex, &lightColor);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid SetLightActionColor(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 4);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_NUMBER(args, 2);\n REQUIRE_OBJECT(args, 3);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n unsigned int action = args[2]->Uint32Value();\n Local<Object> color = Local<Object>::Cast(args[3]);\n\n LFX_COLOR lightColor{ 0 };\n ObjectToColor(color, lightColor);\n\n LFX_RESULT result = ALIENFX_API.SetLightActionColor(deviceIndex, lightIndex, action, &lightColor);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid SetLightActionColorEx(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 5);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n REQUIRE_NUMBER(args, 2);\n REQUIRE_OBJECT(args, 3);\n REQUIRE_OBJECT(args, 4);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n unsigned int action = args[2]->Uint32Value();\n Local<Object> primaryColor = Local<Object>::Cast(args[3]);\n Local<Object> secondaryColor = Local<Object>::Cast(args[4]);\n\n LFX_COLOR primaryLightColor{ 0 };\n ObjectToColor(primaryColor, primaryLightColor);\n\n LFX_COLOR secondaryLightColor{ 0 };\n ObjectToColor(secondaryColor, secondaryLightColor);\n\n\n LFX_RESULT result = ALIENFX_API.SetLightActionColorEx(deviceIndex, lightIndex, action, &primaryLightColor, &secondaryLightColor);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\nvoid SetTiming(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n\n\n int timing = args[0]->Int32Value();\n\n LFX_RESULT result = ALIENFX_API.SetTiming(timing);\n\n args.GetReturnValue().Set(Number::New(args.GetIsolate(), result));\n}\n\n\n\nvoid InitSyncBindings(Local<Object> exports, Local<Object> module)\n{\n Isolate* isolate = exports->GetIsolate();\n\n NODE_SET_METHOD(exports, \"getVersionSync\", GetVersionSync);\n NODE_SET_METHOD(exports, \"initializeSync\", InitializeSync);\n NODE_SET_METHOD(exports, \"releaseSync\", ReleaseSync);\n NODE_SET_METHOD(exports, \"reset\", Reset);\n NODE_SET_METHOD(exports, \"update\", Update);\n NODE_SET_METHOD(exports, \"updateDefault\", UpdateDefault);\n NODE_SET_METHOD(exports, \"light\", Light);\n NODE_SET_METHOD(exports, \"actionColor\", ActionColor);\n NODE_SET_METHOD(exports, \"actionColorEx\", ActionColorEx);\n NODE_SET_METHOD(exports, \"getNumDevicesSync\", GetNumDevicesSync);\n NODE_SET_METHOD(exports, \"getDeviceDescriptionSync\", GetDeviceDescriptionSync);\n NODE_SET_METHOD(exports, \"getNumLightsSync\", GetNumLightsSync);\n NODE_SET_METHOD(exports, \"getLightDescriptionSync\", GetLightDescriptionSync);\n NODE_SET_METHOD(exports, \"getLightLocationSync\", GetLightLocationSync);\n NODE_SET_METHOD(exports, \"getLightColorSync\", GetLightColorSync);\n NODE_SET_METHOD(exports, \"setLightColor\", SetLightColor);\n NODE_SET_METHOD(exports, \"setLightActionColor\", SetLightActionColor);\n NODE_SET_METHOD(exports, \"setLightActionColorEx\", SetLightActionColorEx);\n NODE_SET_METHOD(exports, \"setTiming\", SetTiming);\n\n\n exports->Set(String::NewFromUtf8(isolate, \"isAvailable\"), Boolean::New(isolate, ALIENFX_API.IsAvailable));\n}\n"
},
{
"alpha_fraction": 0.6873692274093628,
"alphanum_fraction": 0.6933398842811584,
"avg_line_length": 28.062612533569336,
"blob_id": "6e451f836935a508751b138f33225d379e7c9165",
"content_id": "f0091c5c22d68caa194d3447c828533a5d7d2b7f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 16246,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 559,
"path": "/sources/binding/async/alienfxAsync.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <node.h>\n#include <uv.h>\n#include <string>\n\n#include \"../contracts.h\"\n#include \"../async/alienfxAsync.h\"\n#include \"../objects/alienfxObjects.h\"\n#include \"../../api/alienfxApi.h\"\n\nusing namespace v8;\nusing namespace std;\n\n\n\nvoid Empty(const FunctionCallbackInfo<Value>& args)\n{\n args.GetReturnValue().SetUndefined();\n}\n\nLocal<Function> GetCallback(const FunctionCallbackInfo<Value>& args, int callbackArgumentIndex)\n{\n Local<Function> callback;\n\n if (callbackArgumentIndex < args.Length())\n {\n callback = Local<Function>::Cast(args[callbackArgumentIndex]);\n }\n else\n {\n callback = FunctionTemplate::New(args.GetIsolate(), Empty)->GetFunction();\n }\n\n return callback;\n}\n\n\n\nvoid GetVersionAsync(uv_work_t* request)\n{\n GetVersionBaton* baton = static_cast<GetVersionBaton*>(request->data);\n\n string version(LFX_DEF_STRING_SIZE, 0);\n\n LFX_RESULT result = ALIENFX_API.GetVersion(\n const_cast<char*>(version.c_str()), \n version.size());\n\n baton->Result = result;\n baton->Version = version;\n}\n\nvoid GetVersionAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetVersionBaton* baton = static_cast<GetVersionBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n data->Set(String::NewFromUtf8(isolate, \"version\"), String::NewFromUtf8(isolate, baton->Version.c_str()));\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n \n delete baton;\n}\n\nvoid GetVersion(const FunctionCallbackInfo<Value>& args)\n{\n OPTIONAL_FUNCTION(args, 0);\n\n\n Local<Function> callback = GetCallback(args, 0);\n\n GetVersionBaton* baton = new GetVersionBaton();\n baton->Request.data = baton;\n baton->Callback.Reset(Isolate::GetCurrent(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetVersionAsync, GetVersionAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid InitializeAsync(uv_work_t* request)\n{\n InitializeBaton* baton = static_cast<InitializeBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.Initialize();\n\n baton->Result = result;\n}\n\nvoid InitializeAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n InitializeBaton* baton = static_cast<InitializeBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid Initialize(const FunctionCallbackInfo<Value>& args)\n{\n OPTIONAL_FUNCTION(args, 0);\n\n\n Local<Function> callback = GetCallback(args, 0);\n\n InitializeBaton* baton = new InitializeBaton();\n baton->Request.data = baton;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, InitializeAsync, InitializeAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid ReleaseAsync(uv_work_t* request)\n{\n InitializeBaton* baton = static_cast<InitializeBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.Release();\n\n baton->Result = result;\n}\n\nvoid ReleaseAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n ReleaseBaton* baton = static_cast<ReleaseBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid Release(const FunctionCallbackInfo<Value>& args)\n{\n OPTIONAL_FUNCTION(args, 0);\n\n\n Local<Function> callback = GetCallback(args, 0);\n\n ReleaseBaton* baton = new ReleaseBaton();\n baton->Request.data = baton;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, ReleaseAsync, ReleaseAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetNumDevicesAsync(uv_work_t* request)\n{\n GetNumDevicesBaton* baton = static_cast<GetNumDevicesBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.GetNumDevices(&baton->NumberOfDevices);\n\n baton->Result = result;\n}\n\nvoid GetNumDevicesAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetNumDevicesBaton* baton = static_cast<GetNumDevicesBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n \n if (baton->Result == LFX_SUCCESS)\n {\n data->Set(String::NewFromUtf8(isolate, \"numberOfDevices\"), Number::New(isolate, baton->NumberOfDevices));\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetNumDevices(const FunctionCallbackInfo<Value>& args)\n{\n OPTIONAL_FUNCTION(args, 0);\n\n\n Local<Function> callback = GetCallback(args, 0);\n\n GetNumDevicesBaton* baton = new GetNumDevicesBaton();\n baton->Request.data = baton;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetNumDevicesAsync, GetNumDevicesAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetDeviceDescriptionAsync(uv_work_t* request)\n{\n GetDeviceDescriptionBaton* baton = static_cast<GetDeviceDescriptionBaton*>(request->data);\n \n string deviceDescription(LFX_DEF_STRING_SIZE, 0);\n\n LFX_RESULT result = ALIENFX_API.GetDeviceDescription(\n baton->DeviceIndex,\n const_cast<char*>(deviceDescription.c_str()),\n deviceDescription.size(),\n &baton->DeviceType);\n\n baton->Result = result;\n baton->DeviceModel = deviceDescription;\n}\n\nvoid GetDeviceDescriptionAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetDeviceDescriptionBaton* baton = static_cast<GetDeviceDescriptionBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n data->Set(String::NewFromUtf8(isolate, \"model\"), String::NewFromUtf8(isolate, baton->DeviceModel.c_str()));\n data->Set(String::NewFromUtf8(isolate, \"type\"), Number::New(isolate, baton->DeviceType));\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetDeviceDescription(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n OPTIONAL_FUNCTION(args, 1);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n Local<Function> callback = GetCallback(args, 1);\n\n GetDeviceDescriptionBaton* baton = new GetDeviceDescriptionBaton();\n baton->Request.data = baton;\n baton->DeviceIndex = deviceIndex;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetDeviceDescriptionAsync, GetDeviceDescriptionAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetNumLightsAsync(uv_work_t* request)\n{\n GetNumLightsBaton* baton = static_cast<GetNumLightsBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.GetNumLights(baton->DeviceIndex, &baton->NumberOfLights);\n\n baton->Result = result;\n}\n\nvoid GetNumLightsAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetNumLightsBaton* baton = static_cast<GetNumLightsBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n data->Set(String::NewFromUtf8(isolate, \"numberOfLights\"), Number::New(isolate, baton->NumberOfLights));\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetNumLights(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n OPTIONAL_FUNCTION(args, 1);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n Local<Function> callback = GetCallback(args, 1);\n\n GetNumLightsBaton* baton = new GetNumLightsBaton();\n baton->Request.data = baton;\n baton->DeviceIndex = deviceIndex;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetNumLightsAsync, GetNumLightsAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetLightDescriptionAsync(uv_work_t* request)\n{\n GetLightDescriptionBaton* baton = static_cast<GetLightDescriptionBaton*>(request->data);\n\n\n string lightDescription(LFX_DEF_STRING_SIZE, 0);\n\n LFX_RESULT result = ALIENFX_API.GetLightDescription(\n baton->DeviceIndex,\n baton->LightIndex,\n const_cast<char*>(lightDescription.c_str()),\n lightDescription.size());\n\n baton->Result = result;\n baton->LightDescription = lightDescription;\n}\n\nvoid GetLightDescriptionAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetLightDescriptionBaton* baton = static_cast<GetLightDescriptionBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n data->Set(String::NewFromUtf8(isolate, \"lightDescription\"), String::NewFromUtf8(isolate, baton->LightDescription.c_str()));\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetLightDescription(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n OPTIONAL_FUNCTION(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n Local<Function> callback = GetCallback(args, 2);\n\n GetLightDescriptionBaton* baton = new GetLightDescriptionBaton();\n baton->Request.data = baton;\n baton->DeviceIndex = deviceIndex;\n baton->LightIndex = lightIndex;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetLightDescriptionAsync, GetLightDescriptionAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetLightLocationAsync(uv_work_t* request)\n{\n GetLightLocationBaton* baton = static_cast<GetLightLocationBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.GetLightLocation(\n baton->DeviceIndex, \n baton->LightIndex, \n &baton->LightLocation);\n\n baton->Result = result;\n}\n\nvoid GetLightLocationAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetLightLocationBaton* baton = static_cast<GetLightLocationBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n Local<Object> location = Object::New(isolate);\n PositionToObject(baton->LightLocation, location);\n\n data->Set(String::NewFromUtf8(isolate, \"lightLocation\"), location);\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetLightLocation(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n OPTIONAL_FUNCTION(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n Local<Function> callback = GetCallback(args, 2);\n\n GetLightDescriptionBaton* baton = new GetLightDescriptionBaton();\n baton->Request.data = baton;\n baton->DeviceIndex = deviceIndex;\n baton->LightIndex = lightIndex;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetLightDescriptionAsync, GetLightDescriptionAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\nvoid GetLightColorAsync(uv_work_t* request)\n{\n GetLightColorBaton* baton = static_cast<GetLightColorBaton*>(request->data);\n\n LFX_RESULT result = ALIENFX_API.GetLightColor(\n baton->DeviceIndex,\n baton->LightIndex,\n &baton->LightColor);\n\n baton->Result = result;\n}\n\nvoid GetLightColorAsyncAfter(uv_work_t* request, int status)\n{\n Isolate* isolate = Isolate::GetCurrent();\n HandleScope scope(isolate);\n\n GetLightColorBaton* baton = static_cast<GetLightColorBaton*>(request->data);\n\n Local<Value> error = Null(isolate);\n Local<Object> data = Object::New(isolate);\n data->Set(String::NewFromUtf8(isolate, \"result\"), Number::New(isolate, baton->Result));\n\n if (baton->Result == LFX_SUCCESS)\n {\n Local<Object> color = Object::New(isolate);\n ColorToObject(baton->LightColor, color);\n\n data->Set(String::NewFromUtf8(isolate, \"lightColor\"), color);\n }\n\n\n Local<Value> argv[2] { error, data };\n Local<Function>::New(isolate, baton->Callback)->Call(isolate->GetCurrentContext()->Global(), 2, argv);\n baton->Callback.Reset();\n\n delete baton;\n}\n\nvoid GetLightColor(const FunctionCallbackInfo<Value>& args)\n{\n REQUIRE_NUMBER_OF_ARGUMENTS(args, 1);\n REQUIRE_NUMBER(args, 0);\n REQUIRE_NUMBER(args, 1);\n OPTIONAL_FUNCTION(args, 2);\n\n\n unsigned int deviceIndex = args[0]->Uint32Value();\n unsigned int lightIndex = args[1]->Uint32Value();\n Local<Function> callback = GetCallback(args, 2);\n\n GetLightColorBaton* baton = new GetLightColorBaton();\n baton->Request.data = baton;\n baton->DeviceIndex = deviceIndex;\n baton->LightIndex = lightIndex;\n baton->Callback.Reset(args.GetIsolate(), callback);\n\n uv_queue_work(uv_default_loop(), &baton->Request, GetLightColorAsync, GetLightColorAsyncAfter);\n\n args.GetReturnValue().SetUndefined();\n}\n\n\n\n\nvoid InitAsyncBindings(Local<Object> exports, Local<Object> module)\n{\n NODE_SET_METHOD(exports, \"getVersion\", GetVersion);\n NODE_SET_METHOD(exports, \"initialize\", Initialize);\n NODE_SET_METHOD(exports, \"release\", Release);\n NODE_SET_METHOD(exports, \"getNumDevices\", GetNumDevices);\n NODE_SET_METHOD(exports, \"getDeviceDescription\", GetDeviceDescription);\n NODE_SET_METHOD(exports, \"getNumLights\", GetNumLights);\n NODE_SET_METHOD(exports, \"getLightDescription\", GetLightDescription);\n NODE_SET_METHOD(exports, \"getLightLocation\", GetLightLocation);\n NODE_SET_METHOD(exports, \"getLightColor\", GetLightColor);\n}\n"
},
{
"alpha_fraction": 0.754889190196991,
"alphanum_fraction": 0.7809647917747498,
"avg_line_length": 25.482759475708008,
"blob_id": "5fab979a87fa8610ba341826d6bd6763456695d7",
"content_id": "4b1ab0cb8668f64ebbeaf6f9a5b8aee723b67cd7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 767,
"license_type": "permissive",
"max_line_length": 52,
"num_lines": 29,
"path": "/sources/api/alienfxApi.h",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <LFX2.h>\n\n\nstruct _ALIENFX_API {\n bool IsAvailable;\n LFX2GETVERSION GetVersion;\n LFX2INITIALIZE Initialize;\n LFX2RELEASE Release;\n LFX2RESET Reset;\n LFX2UPDATE Update;\n LFX2UPDATEDEFAULT UpdateDefault;\n LFX2LIGHT Light;\n LFX2ACTIONCOLOR ActionColor;\n LFX2ACTIONCOLOREX ActionColorEx;\n LFX2GETNUMDEVICES GetNumDevices;\n LFX2GETDEVDESC GetDeviceDescription;\n LFX2GETNUMLIGHTS GetNumLights;\n LFX2GETLIGHTDESC GetLightDescription;\n LFX2GETLIGHTLOC GetLightLocation;\n LFX2GETLIGHTCOL GetLightColor;\n LFX2SETLIGHTCOL SetLightColor;\n LFX2SETLIGHTACTIONCOLOR SetLightActionColor;\n LFX2SETLIGHTACTIONCOLOREX SetLightActionColorEx;\n LFX2SETTIMING SetTiming;\n};\n\nextern _ALIENFX_API ALIENFX_API;"
},
{
"alpha_fraction": 0.5448480248451233,
"alphanum_fraction": 0.5544847846031189,
"avg_line_length": 21.86440658569336,
"blob_id": "113c2782b858b58f95bdb061f538e400764bb3d9",
"content_id": "c17c6f1915c02ac0cec2fef172201f5532d8261c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1349,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 59,
"path": "/samples/sdk/sampleApp4.js",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "var extension = require('bindings')('alienfx.node');\n\n\nfunction light(colorComponent, callback) {\n if (colorComponent === 0) {\n callback();\n return;\n }\n\n\n var color =\n ((0xFF - colorComponent) << 16) +\n colorComponent +\n extension.Brightness.FULL;\n\n extension.light(extension.Position.ALL, color);\n extension.update();\n\n console.info('Color: %s', color.toString(16));\n\n\n setTimeout(function () {\n light(colorComponent - 1, callback);\n }, 100);\n}\n\n\n\nif (extension.isAvailable) {\n var result = extension.initializeSync();\n\n if (result === extension.Result.SUCCESS) {\n var version = {};\n extension.getVersionSync(version);\n console.info('SDK version: %s', version.result);\n\n extension.reset();\n\n light(255, function () {\n require('./utilities').waitForKeyPress(function () {\n extension.releaseSync();\n });\n });\n }\n else {\n switch (result) {\n case extension.Result.NODEVS:\n console.error('There are no AlienFX devices available.');\n break;\n\n default:\n console.error('There was an error initializing the AlienFX device.');\n break;\n }\n }\n}\nelse {\n console.error('Failed to load LightFX.dll.');\n}\n"
},
{
"alpha_fraction": 0.7025089859962463,
"alphanum_fraction": 0.7096773982048035,
"avg_line_length": 29.9777774810791,
"blob_id": "addf59bbf53f04554671fa1b9ab1065d5e3479e7",
"content_id": "742333b6246a6f70973ff821ad05cdea5379e5e9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1395,
"license_type": "permissive",
"max_line_length": 121,
"num_lines": 45,
"path": "/sources/binding/contracts.h",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <node.h>\n\n\nclass Contracts\n{\npublic:\n static bool RequireNumberOfArguments(const v8::FunctionCallbackInfo<v8::Value>& args, int requiredNumberOfArguments);\n static bool RequireObjectArgument(const v8::FunctionCallbackInfo<v8::Value>& args, int argumentIndex);\n static bool RequireNumberArgument(const v8::FunctionCallbackInfo<v8::Value>& args, int argumentIndex);\n static bool RequireFunctionArgument(const v8::FunctionCallbackInfo<v8::Value>& args, int argumentIndex);\n static bool OptionalFunctionArgument(const v8::FunctionCallbackInfo<v8::Value>& args, int argumentIndex);\n};\n\n\n#define REQUIRE_NUMBER_OF_ARGUMENTS(args, requiredNumberOfArguments) \\\n if (!Contracts::RequireNumberOfArguments(args, requiredNumberOfArguments)) \\\n { \\\n return; \\\n }\n\n#define REQUIRE_OBJECT(args, argumentIndex) \\\n if (!Contracts::RequireObjectArgument(args, argumentIndex)) \\\n { \\\n return; \\\n }\n\n#define REQUIRE_NUMBER(args, argumentIndex) \\\n if (!Contracts::RequireNumberArgument(args, argumentIndex)) \\\n { \\\n return; \\\n }\n\n#define REQUIRE_FUNCTION(args, argumentIndex) \\\n if (!Contracts::RequireFunctionArgument(args, argumentIndex)) \\\n { \\\n return; \\\n }\n\n#define OPTIONAL_FUNCTION(args, argumentIndex) \\\n if (!Contracts::OptionalFunctionArgument(args, argumentIndex)) \\\n { \\\n return; \\\n }\n\n"
},
{
"alpha_fraction": 0.7435158491134644,
"alphanum_fraction": 0.7463976740837097,
"avg_line_length": 20.6875,
"blob_id": "c15513e5ead46428f3f44d78624497bd5c34cf4d",
"content_id": "26be24997f51d015223c74c25e787e5638fe9eba",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 347,
"license_type": "permissive",
"max_line_length": 56,
"num_lines": 16,
"path": "/sources/binding/alienfx.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <node.h>\n\n#include \"sync/alienfxSync.h\"\n#include \"async/alienfxAsync.h\"\n#include \"objects/alienfxObjects.h\"\n\nusing namespace v8;\n\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n InitAsyncBindings(exports, module);\n InitSyncBindings(exports, module);\n InitObjectBindings(exports, module);\n}\n\nNODE_MODULE(alienfx, Init)\n"
},
{
"alpha_fraction": 0.7076451182365417,
"alphanum_fraction": 0.7167441248893738,
"avg_line_length": 55.48603439331055,
"blob_id": "82a56d6be423b4af5eccfe8e21e6c6d43398662d",
"content_id": "38f14e3d53cb42368907890d72980fddba8554b0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 10111,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 179,
"path": "/sources/binding/objects/alienfxObjects.cc",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#include <node.h>\n\n#include \"../../api/alienfxApi.h\"\n\nusing namespace v8;\nusing namespace std;\n\n\n\nvoid ObjectToColor(Local<Object> object, LFX_COLOR& color)\n{\n Isolate* isolate = object->GetIsolate();\n\n color.red = object->Get(String::NewFromUtf8(isolate, \"red\"))->Uint32Value();\n color.green = object->Get(String::NewFromUtf8(isolate, \"green\"))->Uint32Value();\n color.blue = object->Get(String::NewFromUtf8(isolate, \"blue\"))->Uint32Value();\n color.brightness = object->Get(String::NewFromUtf8(isolate, \"brightness\"))->Uint32Value();\n}\n\nvoid ColorToObject(const LFX_COLOR& color, Local<Object> object)\n{\n Isolate* isolate = object->GetIsolate();\n\n object->Set(String::NewFromUtf8(isolate, \"red\"), Number::New(isolate, color.red));\n object->Set(String::NewFromUtf8(isolate, \"green\"), Number::New(isolate, color.green));\n object->Set(String::NewFromUtf8(isolate, \"blue\"), Number::New(isolate, color.blue));\n object->Set(String::NewFromUtf8(isolate, \"brightness\"), Number::New(isolate, color.brightness));\n}\n\nvoid PositionToObject(const LFX_POSITION& position, Local<Object> object)\n{\n Isolate* isolate = object->GetIsolate();\n\n object->Set(String::NewFromUtf8(isolate, \"x\"), Number::New(isolate, position.x));\n object->Set(String::NewFromUtf8(isolate, \"y\"), Number::New(isolate, position.y));\n object->Set(String::NewFromUtf8(isolate, \"z\"), Number::New(isolate, position.z));\n}\n\n\nLocal<Value> CreateColorObject(Isolate* isolate)\n{\n Local<Object> color = Object::New(isolate);\n color->Set(String::NewFromUtf8(isolate, \"OFF\"), Number::New(isolate, LFX_OFF));\n color->Set(String::NewFromUtf8(isolate, \"BLACK\"), Number::New(isolate, LFX_BLACK));\n color->Set(String::NewFromUtf8(isolate, \"RED\"), Number::New(isolate, LFX_RED));\n color->Set(String::NewFromUtf8(isolate, \"GREEN\"), Number::New(isolate, LFX_GREEN));\n color->Set(String::NewFromUtf8(isolate, \"BLUE\"), Number::New(isolate, LFX_BLUE));\n color->Set(String::NewFromUtf8(isolate, \"WHITE\"), Number::New(isolate, LFX_WHITE));\n color->Set(String::NewFromUtf8(isolate, \"YELLOW\"), Number::New(isolate, LFX_YELLOW));\n color->Set(String::NewFromUtf8(isolate, \"ORANGE\"), Number::New(isolate, LFX_ORANGE));\n color->Set(String::NewFromUtf8(isolate, \"PINK\"), Number::New(isolate, LFX_PINK));\n color->Set(String::NewFromUtf8(isolate, \"CYAN\"), Number::New(isolate, LFX_CYAN));\n\n return color;\n}\n\nLocal<Value> CreateBrightnessObject(Isolate* isolate)\n{\n Local<Object> brightness = Object::New(isolate);\n brightness->Set(String::NewFromUtf8(isolate, \"FULL\"), Number::New(isolate, LFX_FULL_BRIGHTNESS));\n brightness->Set(String::NewFromUtf8(isolate, \"HALF\"), Number::New(isolate, LFX_HALF_BRIGHTNESS));\n brightness->Set(String::NewFromUtf8(isolate, \"MIN\"), Number::New(isolate, LFX_MIN_BRIGHTNESS));\n\n return brightness;\n}\n\nLocal<Value> CreateDeviceTypeObject(Isolate* isolate)\n{\n Local<Object> deviceType = Object::New(isolate);\n deviceType->Set(String::NewFromUtf8(isolate, \"UNKNOWN\"), Number::New(isolate, LFX_DEVTYPE_UNKNOWN));\n deviceType->Set(String::NewFromUtf8(isolate, \"NOTEBOOK\"), Number::New(isolate, LFX_DEVTYPE_NOTEBOOK));\n deviceType->Set(String::NewFromUtf8(isolate, \"DESKTOP\"), Number::New(isolate, LFX_DEVTYPE_DESKTOP));\n deviceType->Set(String::NewFromUtf8(isolate, \"SERVER\"), Number::New(isolate, LFX_DEVTYPE_SERVER));\n deviceType->Set(String::NewFromUtf8(isolate, \"DISPLAY\"), Number::New(isolate, LFX_DEVTYPE_DISPLAY));\n deviceType->Set(String::NewFromUtf8(isolate, \"MOUSE\"), Number::New(isolate, LFX_DEVTYPE_MOUSE));\n deviceType->Set(String::NewFromUtf8(isolate, \"KEYBOARD\"), Number::New(isolate, LFX_DEVTYPE_KEYBOARD));\n deviceType->Set(String::NewFromUtf8(isolate, \"GAMEPAD\"), Number::New(isolate, LFX_DEVTYPE_GAMEPAD));\n deviceType->Set(String::NewFromUtf8(isolate, \"SPEAKER\"), Number::New(isolate, LFX_DEVTYPE_SPEAKER));\n deviceType->Set(String::NewFromUtf8(isolate, \"OTHER\"), Number::New(isolate, LFX_DEVTYPE_OTHER));\n\n return deviceType;\n}\n\nLocal<Value> CreatePositionObject(Isolate* isolate)\n{\n Local<Object> position = Object::New(isolate);\n\n // Near Z-plane light definitions\n position->Set(String::NewFromUtf8(isolate, \"FRONT_LOWER_LEFT\"), Number::New(isolate, LFX_FRONT_LOWER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_LOWER_CENTER\"), Number::New(isolate, LFX_FRONT_LOWER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_LOWER_RIGHT\"), Number::New(isolate, LFX_FRONT_LOWER_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_MIDDLE_LEFT\"), Number::New(isolate, LFX_FRONT_MIDDLE_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_MIDDLE_CENTER\"), Number::New(isolate, LFX_FRONT_MIDDLE_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_MIDDLE_RIGHT\"), Number::New(isolate, LFX_FRONT_MIDDLE_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_UPPER_LEFT\"), Number::New(isolate, LFX_FRONT_UPPER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_UPPER_CENTER\"), Number::New(isolate, LFX_FRONT_UPPER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"FRONT_UPPER_RIGHT\"), Number::New(isolate, LFX_FRONT_UPPER_RIGHT));\n\n // Mid Z-plane light definitions\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_LOWER_LEFT\"), Number::New(isolate, LFX_MIDDLE_LOWER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_LOWER_CENTER\"), Number::New(isolate, LFX_MIDDLE_LOWER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_LOWER_RIGHT\"), Number::New(isolate, LFX_MIDDLE_LOWER_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_MIDDLE_LEFT\"), Number::New(isolate, LFX_MIDDLE_MIDDLE_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_MIDDLE_CENTER\"), Number::New(isolate, LFX_MIDDLE_MIDDLE_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_MIDDLE_RIGHT\"), Number::New(isolate, LFX_MIDDLE_MIDDLE_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_UPPER_LEFT\"), Number::New(isolate, LFX_MIDDLE_UPPER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_UPPER_CENTER\"), Number::New(isolate, LFX_MIDDLE_UPPER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"MIDDLE_UPPER_RIGHT\"), Number::New(isolate, LFX_MIDDLE_UPPER_RIGHT));\n\n // Far Z-plane light definitions\n position->Set(String::NewFromUtf8(isolate, \"REAR_LOWER_LEFT\"), Number::New(isolate, LFX_REAR_LOWER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"REAR_LOWER_CENTER\"), Number::New(isolate, LFX_REAR_LOWER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"REAR_LOWER_RIGHT\"), Number::New(isolate, LFX_REAR_LOWER_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"REAR_MIDDLE_LEFT\"), Number::New(isolate, LFX_REAR_MIDDLE_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"REAR_MIDDLE_CENTER\"), Number::New(isolate, LFX_REAR_MIDDLE_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"REAR_MIDDLE_RIGHT\"), Number::New(isolate, LFX_REAR_MIDDLE_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"REAR_UPPER_LEFT\"), Number::New(isolate, LFX_REAR_UPPER_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"REAR_UPPER_CENTER\"), Number::New(isolate, LFX_REAR_UPPER_CENTER));\n position->Set(String::NewFromUtf8(isolate, \"REAR_UPPER_RIGHT\"), Number::New(isolate, LFX_REAR_UPPER_RIGHT));\n\n // Combination bit masks\n position->Set(String::NewFromUtf8(isolate, \"ALL\"), Number::New(isolate, LFX_ALL));\n position->Set(String::NewFromUtf8(isolate, \"ALL_RIGHT\"), Number::New(isolate, LFX_ALL_RIGHT));\n position->Set(String::NewFromUtf8(isolate, \"ALL_LEFT\"), Number::New(isolate, LFX_ALL_LEFT));\n position->Set(String::NewFromUtf8(isolate, \"ALL_UPPER\"), Number::New(isolate, LFX_ALL_UPPER));\n position->Set(String::NewFromUtf8(isolate, \"ALL_LOWER\"), Number::New(isolate, LFX_ALL_LOWER));\n position->Set(String::NewFromUtf8(isolate, \"ALL_FRONT\"), Number::New(isolate, LFX_ALL_FRONT));\n position->Set(String::NewFromUtf8(isolate, \"ALL_REAR\"), Number::New(isolate, LFX_ALL_REAR));\n\n return position;\n}\n\nLocal<Value> CreateResutObject(Isolate* isolate)\n{\n Local<Object> result = Object::New(isolate);\n result->Set(String::NewFromUtf8(isolate, \"SUCCESS\"), Number::New(isolate, LFX_SUCCESS));\n result->Set(String::NewFromUtf8(isolate, \"FAILURE\"), Number::New(isolate, LFX_FAILURE));\n result->Set(String::NewFromUtf8(isolate, \"NOINIT\"), Number::New(isolate, LFX_ERROR_NOINIT));\n result->Set(String::NewFromUtf8(isolate, \"NODEVS\"), Number::New(isolate, LFX_ERROR_NODEVS));\n result->Set(String::NewFromUtf8(isolate, \"NOLIGHTS\"), Number::New(isolate, LFX_ERROR_NOLIGHTS));\n result->Set(String::NewFromUtf8(isolate, \"BUFFSIZE\"), Number::New(isolate, LFX_ERROR_BUFFSIZE));\n\n return result;\n}\n\nLocal<Value> CreateActionObject(Isolate* isolate)\n{\n Local<Object> action = Object::New(isolate);\n action->Set(String::NewFromUtf8(isolate, \"MORPH\"), Number::New(isolate, LFX_ACTION_MORPH));\n action->Set(String::NewFromUtf8(isolate, \"PULSE\"), Number::New(isolate, LFX_ACTION_PULSE));\n action->Set(String::NewFromUtf8(isolate, \"COLOR\"), Number::New(isolate, LFX_ACTION_COLOR));\n\n return action;\n}\n\n\n\nvoid InitObjectBindings(Local<Object> exports, Local<Object> module)\n{\n Isolate* isolate = exports->GetIsolate();\n\n Local<Value> color = CreateColorObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"Color\"), color);\n\n Local<Value> brightness = CreateBrightnessObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"Brightness\"), brightness);\n\n Local<Value> deviceType = CreateDeviceTypeObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"DeviceType\"), deviceType);\n\n Local<Value> position = CreatePositionObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"Position\"), position);\n\n Local<Value> result = CreateResutObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"Result\"), result);\n\n Local<Value> action = CreateActionObject(isolate);\n exports->Set(String::NewFromUtf8(isolate, \"Action\"), action);\n}\n"
},
{
"alpha_fraction": 0.5529458522796631,
"alphanum_fraction": 0.568869411945343,
"avg_line_length": 22.05504608154297,
"blob_id": "b9f576d6aeaeb7a642ec711ce25362648a27cfa0",
"content_id": "21d35718954f5a97a997e8ea764be28c252a9854",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2512,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 109,
"path": "/tests/utilities.js",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "var inquirer = require('inquirer');\nvar assert = require('assert');\n\n\nfunction checkboxPrompt(message, choices, callback) {\n inquirer.prompt([{\n type: 'checkbox',\n name: 'result',\n message: message,\n choices: choices\n }], function (answers) {\n var result = [];\n\n choices.forEach(function (choice, choiceIndex) {\n result[choiceIndex] = false;\n\n answers.result.forEach(function (answer) {\n if (choice === answer) {\n result[choiceIndex] = true;\n }\n });\n });\n\n callback(result);\n });\n}\n\n\nfunction promptAboutTests(choices, callback) {\n checkboxPrompt('Select tests', choices, callback);\n}\n\n\nfunction checkLightsColor(extension, color) {\n var devices = {};\n extension.getNumDevicesSync(devices);\n\n for (var deviceIndex = 0; deviceIndex < devices.numberOfDevices; deviceIndex++) {\n var lights = {};\n extension.getNumLightsSync(deviceIndex, lights);\n\n for (var lightIndex = 0; lightIndex < lights.numberOfLights; lightIndex++) {\n checkLightColor(extension, color, deviceIndex, lightIndex);\n }\n }\n}\n\nfunction checkLightColor(extension, color, deviceIndex, lightIndex) {\n var currentColor = {};\n extension.getLightColorSync(deviceIndex, lightIndex, currentColor);\n\n assert.deepEqual(currentColor.lightColor, normalizeColor(color));\n}\n\nfunction normalizeColor(color) {\n var normalizedColor;\n\n switch (typeof color) {\n case 'object': {\n normalizedColor = color;\n break;\n }\n\n case 'number': {\n normalizedColor = {\n brightness: (color & 0xFF000000) >>> 24,\n red: (color & 0x00FF0000) >>> 16,\n green: (color & 0x0000FF00) >>> 8,\n blue: (color & 0x000000FF) >>> 0\n };\n\n break;\n }\n }\n\n return normalizedColor;\n}\n\nfunction isEqualColors(a, b) {\n var normalized_a = normalizeColor(a);\n var normalized_b = normalizeColor(b);\n\n assert.deepEqual(normalized_a, normalized_b);\n}\n\n\nmodule.exports = exports = {\n colors: {\n NONE: {\n red: 0,\n green: 0,\n blue: 0,\n brightness: 0\n }\n },\n\n functions: {\n empty: function () { }\n },\n\n ask: {\n whichTestsToRun: promptAboutTests\n },\n\n lightsAre: checkLightsColor,\n lightIs: checkLightColor,\n\n equalColors: isEqualColors\n};"
},
{
"alpha_fraction": 0.7184054255485535,
"alphanum_fraction": 0.7234944701194763,
"avg_line_length": 18.66666603088379,
"blob_id": "4afebb64a1169df23723ee7405c32fcb46a1848e",
"content_id": "279265d9ee2edd34aa77ca4144244e630b8a9524",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1179,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 60,
"path": "/sources/binding/async/alienfxAsync.h",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "#pragma once\n\n#include <node.h>\n#include <uv.h>\n#include <string>\n\n#include \"../../api/alienfxApi.h\"\n\n\nstruct BaseBaton {\n uv_work_t Request;\n v8::Persistent<v8::Function> Callback;\n LFX_RESULT Result;\n};\n\n\nstruct GetVersionBaton : BaseBaton {\n std::string Version;\n};\n\nstruct InitializeBaton : BaseBaton {};\n\nstruct ReleaseBaton : BaseBaton {};\n\nstruct GetNumDevicesBaton : BaseBaton {\n unsigned int NumberOfDevices;\n};\n\nstruct GetDeviceDescriptionBaton : BaseBaton {\n unsigned int DeviceIndex;\n std::string DeviceModel;\n unsigned char DeviceType;\n};\n\nstruct GetNumLightsBaton : BaseBaton {\n unsigned int DeviceIndex;\n unsigned int NumberOfLights;\n};\n\nstruct GetLightDescriptionBaton : BaseBaton {\n unsigned int DeviceIndex;\n unsigned int LightIndex;\n std::string LightDescription;\n};\n\nstruct GetLightLocationBaton : BaseBaton {\n unsigned int DeviceIndex;\n unsigned int LightIndex;\n LFX_POSITION LightLocation;\n};\n\nstruct GetLightColorBaton : BaseBaton {\n unsigned int DeviceIndex;\n unsigned int LightIndex;\n LFX_COLOR LightColor;\n};\n\n\n\nvoid InitAsyncBindings(v8::Local<v8::Object> exports, v8::Local<v8::Object> module);"
},
{
"alpha_fraction": 0.45317724347114563,
"alphanum_fraction": 0.45317724347114563,
"avg_line_length": 27.4761905670166,
"blob_id": "de1f013642c7571a1296d1925c7058e6dec49e0a",
"content_id": "181b6746fc5e5bdc0a2c316370646838fe277ff8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 598,
"license_type": "permissive",
"max_line_length": 68,
"num_lines": 21,
"path": "/binding.gyp",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "{\n \"targets\": [{\n \"target_name\": \"alienfx\",\n \"sources\": [\n \"sources/binding/alienfx.cc\",\n \"sources/binding/sync/alienfxSync.cc\",\n \"sources/binding/async/alienfxAsync.cc\",\n \"sources/binding/objects/alienfxObjects.cc\",\n \"sources/binding/contracts.cc\"\n ],\n \"include_dirs\": [\"dependencies/alienfxsdk/include\"],\n \"conditions\": [\n [\n \"OS=='win'\",\n {\n \"sources\": [\"sources/api/windows/alienfxApi.cc\"]\n }\n ]\n ]\n }]\n}\n"
},
{
"alpha_fraction": 0.5213924646377563,
"alphanum_fraction": 0.538304328918457,
"avg_line_length": 31.405385971069336,
"blob_id": "3674789962bb67391dbf7e021f42b73d82fe8a5e",
"content_id": "c081dc71e4d982398761db7c39f3da6fb06f9a8a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 44525,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 1374,
"path": "/tests/structural/exports.js",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "var extension = require('bindings')('alienfx.node');\n\nvar assert = require('assert');\nvar utilities = require('../utilities');\n\n\ndescribe('exports: structural tests', function () {\n\n describe('getVersion()', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.getVersion, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.getVersion();\n }, Error);\n });\n\n it('should allow callback as a first argument', function (done) {\n assert.throws(function () {\n extension.getVersion(null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getVersion(done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getVersion(done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getVersionSync()', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.getVersionSync, 'function');\n });\n\n it('should require atleast 1 argument', function () {\n assert.doesNotThrow(function () {\n extension.getVersionSync({});\n });\n\n assert.throws(function () {\n extension.getVersionSync();\n }, Error);\n });\n\n it('should require first argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getVersionSync({});\n });\n\n assert.throws(function () {\n extension.getVersionSync(null);\n }, TypeError);\n });\n });\n\n\n describe('initialize()', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.initialize, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.initialize();\n }, Error);\n });\n\n it('should allow callback as a first argument', function (done) {\n assert.throws(function () {\n extension.initialize(null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.initialize(function () {\n extension.releaseSync();\n done();\n });\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.initialize(function () {\n extension.releaseSync();\n done();\n });\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('initializeSync()', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.initializeSync, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.initializeSync();\n });\n\n extension.releaseSync();\n });\n });\n\n\n describe('release', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.release, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.release();\n }, Error);\n });\n\n it('should allow callback as a first argument', function (done) {\n assert.throws(function () {\n extension.release(null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.release(done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.release(done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('releaseSync()', function () {\n this.timeout(0);\n\n it('should be a function', function () {\n assert.equal(typeof extension.releaseSync, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.releaseSync();\n });\n });\n });\n\n\n describe('reset()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.reset, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.reset();\n });\n });\n });\n\n\n describe('light()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.light, 'function');\n });\n\n it('should require atleast 2 arguments', function () {\n assert.doesNotThrow(function () {\n extension.light(0, 0);\n });\n\n assert.throws(function () {\n extension.light();\n }, Error);\n\n assert.throws(function () {\n extension.light(0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.light(0, 0);\n });\n\n assert.throws(function () {\n extension.light(null, 0);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.light(0, 0);\n });\n\n assert.throws(function () {\n extension.light(0, null);\n }, TypeError);\n });\n\n it('should allow negative numbers as second argument', function () {\n var color = (0x80000000 | 0);\n\n assert.doesNotThrow(function () {\n extension.light(0, color);\n });\n });\n });\n\n\n describe('actionColor()', function () {\n\n it('should be a function', function () {\n assert.strictEqual(typeof extension.actionColor, 'function');\n });\n\n it('should require atleast 3 arguments', function () {\n assert.doesNotThrow(function () {\n extension.actionColor(0, extension.Action.COLOR, 0);\n });\n\n assert.throws(function () {\n extension.actionColor();\n }, Error);\n\n assert.throws(function () {\n extension.actionColor(0, extension.Action.COLOR);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColor(0, extension.Action.COLOR, 0);\n });\n\n assert.throws(function () {\n extension.actionColor(null, extension.Action.COLOR, 0);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColor(0, extension.Action.COLOR, 0);\n });\n\n assert.throws(function () {\n extension.actionColor(0, null, 0);\n }, TypeError);\n });\n\n it('should require third argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColor(0, extension.Action.COLOR, 0);\n });\n\n assert.throws(function () {\n extension.actionColor(0, extension.Action.COLOR, null);\n }, TypeError);\n });\n\n it('should allow negative numbers as third argument', function () {\n var color = (0x80000000 | 0);\n\n assert.doesNotThrow(function () {\n extension.actionColor(0, extension.Action.COLOR, color);\n });\n });\n });\n\n\n describe('actionColorEx()', function () {\n\n it('should be a function', function () {\n assert.strictEqual(typeof extension.actionColorEx, 'function');\n });\n\n it('should require atleast 4 arguments', function () {\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, 0);\n });\n\n assert.throws(function () {\n extension.actionColorEx();\n }, Error);\n\n assert.throws(function () {\n extension.actionColorEx(0, extension.Action.COLOR);\n }, Error);\n\n assert.throws(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, 0);\n });\n\n assert.throws(function () {\n extension.actionColorEx(null, extension.Action.COLOR, 0, 0);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, 0);\n });\n\n assert.throws(function () {\n extension.actionColorEx(0, null, 0, 0);\n }, TypeError);\n });\n\n it('should require third argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, 0);\n });\n\n assert.throws(function () {\n extension.actionColorEx(0, extension.Action.COLOR, null, 0);\n }, TypeError);\n });\n\n it('should allow negative numbers as third argument', function () {\n var color = (0x80000000 | 0);\n\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, color, 0);\n });\n });\n\n it('should require fourth argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, 0);\n });\n\n assert.throws(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, null);\n }, TypeError);\n });\n\n it('should allow negative numbers as fourth argument', function () {\n var color = (0x80000000 | 0);\n\n assert.doesNotThrow(function () {\n extension.actionColorEx(0, extension.Action.COLOR, 0, color);\n });\n });\n });\n\n\n describe('update()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.update, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.update();\n });\n });\n });\n\n\n describe('updateDefault()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.updateDefault, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.updateDefault();\n });\n });\n });\n\n\n describe('Color', function () {\n\n it('should be an object', function () {\n assert.equal(typeof extension.Color, 'object');\n });\n\n it('should contain predefined colors constants', function () {\n assert.equal(extension.Color.OFF, 0x00000000);\n assert.equal(extension.Color.BLACK, 0x00000000);\n assert.equal(extension.Color.RED, 0x00FF0000);\n assert.equal(extension.Color.GREEN, 0x0000FF00);\n assert.equal(extension.Color.BLUE, 0x000000FF);\n assert.equal(extension.Color.WHITE, 0x00FFFFFF);\n assert.equal(extension.Color.YELLOW, 0x00FFFF00);\n assert.equal(extension.Color.ORANGE, 0x00FF8000);\n assert.equal(extension.Color.PINK, 0x00FF80FF);\n assert.equal(extension.Color.CYAN, 0x0000FFFF);\n });\n });\n\n\n describe('Brightness', function () {\n\n it('should be an object', function () {\n assert.equal(typeof extension.Brightness, 'object');\n });\n\n it('should contain predefined brightness constants', function () {\n assert.equal(extension.Brightness.FULL, 0xFF000000);\n assert.equal(extension.Brightness.HALF, 0x80000000);\n assert.equal(extension.Brightness.MIN, 0x00000000);\n });\n });\n\n\n describe('DeviceType', function () {\n\n it('should be an object', function () {\n assert.equal(typeof extension.DeviceType, 'object');\n });\n\n it('should contain predefined device type constants', function () {\n assert.equal(extension.DeviceType.UNKNOWN, 0x00);\n assert.equal(extension.DeviceType.NOTEBOOK, 0x01);\n assert.equal(extension.DeviceType.DESKTOP, 0x02);\n assert.equal(extension.DeviceType.SERVER, 0x03);\n assert.equal(extension.DeviceType.DISPLAY, 0x04);\n assert.equal(extension.DeviceType.MOUSE, 0x05);\n assert.equal(extension.DeviceType.KEYBOARD, 0x06);\n assert.equal(extension.DeviceType.GAMEPAD, 0x07);\n assert.equal(extension.DeviceType.SPEAKER, 0x08);\n assert.equal(extension.DeviceType.OTHER, 0xFF);\n });\n });\n\n\n describe('Position', function () {\n\n it('should be an object', function () {\n assert.equal(typeof extension.Position, 'object');\n });\n\n it('should contain predefined position constants', function () {\n\n // Near Z-plane light definitions\n assert.equal(extension.Position.FRONT_LOWER_LEFT, 0x00000001);\n assert.equal(extension.Position.FRONT_LOWER_CENTER, 0x00000002);\n assert.equal(extension.Position.FRONT_LOWER_RIGHT, 0x00000004);\n assert.equal(extension.Position.FRONT_MIDDLE_LEFT, 0x00000008);\n assert.equal(extension.Position.FRONT_MIDDLE_CENTER, 0x00000010);\n assert.equal(extension.Position.FRONT_MIDDLE_RIGHT, 0x00000020);\n assert.equal(extension.Position.FRONT_UPPER_LEFT, 0x00000040);\n assert.equal(extension.Position.FRONT_UPPER_CENTER, 0x00000080);\n assert.equal(extension.Position.FRONT_UPPER_RIGHT, 0x00000100);\n\n // Mid Z-plane light definitions\n assert.equal(extension.Position.MIDDLE_LOWER_LEFT, 0x00000200);\n assert.equal(extension.Position.MIDDLE_LOWER_CENTER, 0x00000400);\n assert.equal(extension.Position.MIDDLE_LOWER_RIGHT, 0x00000800);\n assert.equal(extension.Position.MIDDLE_MIDDLE_LEFT, 0x00001000);\n assert.equal(extension.Position.MIDDLE_MIDDLE_CENTER, 0x00002000);\n assert.equal(extension.Position.MIDDLE_MIDDLE_RIGHT, 0x00004000);\n assert.equal(extension.Position.MIDDLE_UPPER_LEFT, 0x00008000);\n assert.equal(extension.Position.MIDDLE_UPPER_CENTER, 0x00010000);\n assert.equal(extension.Position.MIDDLE_UPPER_RIGHT, 0x00020000);\n\n // Far Z-plane light definitions\n assert.equal(extension.Position.REAR_LOWER_LEFT, 0x00040000);\n assert.equal(extension.Position.REAR_LOWER_CENTER, 0x00080000);\n assert.equal(extension.Position.REAR_LOWER_RIGHT, 0x00100000);\n assert.equal(extension.Position.REAR_MIDDLE_LEFT, 0x00200000);\n assert.equal(extension.Position.REAR_MIDDLE_CENTER, 0x00400000);\n assert.equal(extension.Position.REAR_MIDDLE_RIGHT, 0x00800000);\n assert.equal(extension.Position.REAR_UPPER_LEFT, 0x01000000);\n assert.equal(extension.Position.REAR_UPPER_CENTER, 0x02000000);\n assert.equal(extension.Position.REAR_UPPER_RIGHT, 0x04000000);\n\n // Combination bit masks\n assert.equal(extension.Position.ALL, 0x07FFFFFF);\n assert.equal(extension.Position.ALL_RIGHT, 0x04924924);\n assert.equal(extension.Position.ALL_LEFT, 0x01249249);\n assert.equal(extension.Position.ALL_UPPER, 0x070381C0);\n assert.equal(extension.Position.ALL_LOWER, 0x001C0E07);\n assert.equal(extension.Position.ALL_FRONT, 0x000001FF);\n assert.equal(extension.Position.ALL_REAR, 0x07FC0000);\n });\n });\n\n\n describe('Result', function () {\n\n it('should be an object', function () {\n assert.equal(typeof extension.Result, 'object');\n });\n\n it('should contain predefined result constants', function () {\n assert.equal(extension.Result.SUCCESS, 0x00);\n assert.equal(extension.Result.FAILURE, 0x01);\n assert.equal(extension.Result.NOINIT, 0x02);\n assert.equal(extension.Result.NODEVS, 0x03);\n assert.equal(extension.Result.NOLIGHTS, 0x04);\n assert.equal(extension.Result.BUFFSIZE, 0x05);\n });\n });\n\n\n describe('Action', function () {\n \n it('should be an object', function () {\n assert.equal(typeof extension.Action, 'object');\n });\n\n it('should contain predefined action constants', function () {\n assert.equal(extension.Action.MORPH, 0x00000001);\n assert.equal(extension.Action.PULSE, 0x00000002);\n assert.equal(extension.Action.COLOR, 0x00000003);\n });\n });\n\n\n describe('isAvailable', function () {\n\n it('should be a boolean', function () {\n assert.equal(typeof extension.isAvailable, 'boolean');\n });\n });\n\n\n describe('getNumDevices()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getNumDevices, 'function');\n });\n\n it('should not require any arguments', function () {\n assert.doesNotThrow(function () {\n extension.getNumDevices();\n });\n });\n\n it('should allow callback as a first argument', function (done) {\n assert.throws(function () {\n extension.getNumDevices(null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getNumDevices(done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getNumDevices(done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getNumDevicesSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getNumDevicesSync, 'function');\n });\n\n it('should require atleast 1 argument', function () {\n assert.doesNotThrow(function () {\n extension.getNumDevicesSync({});\n });\n\n assert.throws(function () {\n extension.getNumDevicesSync();\n }, Error);\n });\n\n it('should require first argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getNumDevicesSync({});\n });\n\n assert.throws(function () {\n extension.getNumDevicesSync(null);\n }, TypeError);\n });\n });\n\n\n describe('getDeviceDescription()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getDeviceDescription, 'function');\n });\n\n it('should require atleast 1 argument', function (done) {\n assert.throws(function () {\n extension.getDeviceDescription();\n }, Error);\n\n assert.doesNotThrow(function () {\n extension.getDeviceDescription(0, done);\n }, Error);\n });\n\n it('should require first argument of type number', function (done) {\n assert.throws(function () {\n extension.getDeviceDescription(null, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getDeviceDescription(0, done);\n });\n });\n\n it('should allow callback as a second argument', function (done) {\n assert.throws(function () {\n extension.getDeviceDescription(0, null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getDeviceDescription(0, done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getDeviceDescription(0, done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getDeviceDescriptionSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getDeviceDescriptionSync, 'function');\n });\n\n it('should require atleast 2 arguments', function () {\n assert.doesNotThrow(function () {\n extension.getDeviceDescriptionSync(0, {});\n });\n\n assert.throws(function () {\n extension.getDeviceDescriptionSync();\n }, Error);\n\n assert.throws(function () {\n extension.getDeviceDescriptionSync(0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getDeviceDescriptionSync(0, {});\n });\n\n assert.throws(function () {\n extension.getDeviceDescriptionSync(null, {});\n }, TypeError);\n });\n\n it('should require second argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getDeviceDescriptionSync(0, {});\n });\n\n assert.throws(function () {\n extension.getDeviceDescriptionSync(0, null);\n }, TypeError);\n });\n });\n\n\n describe('getNumLights()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getNumLights, 'function');\n });\n\n it('should require atleast 1 argument', function (done) {\n assert.throws(function () {\n extension.getNumLights();\n }, Error);\n\n assert.doesNotThrow(function () {\n extension.getNumLights(0, done);\n }, Error);\n });\n\n it('should require first argument of type number', function (done) {\n assert.throws(function () {\n extension.getNumLights(null, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getNumLights(0, done);\n });\n });\n\n it('should allow callback as a second argument', function (done) {\n assert.throws(function () {\n extension.getNumLights(0, null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getNumLights(0, done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getNumLights(0, done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getNumLightsSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getNumLightsSync, 'function');\n });\n\n it('should require atleast 2 arguments', function () {\n assert.doesNotThrow(function () {\n extension.getNumLightsSync(0, {});\n });\n\n assert.throws(function () {\n extension.getNumLightsSync();\n }, Error);\n\n assert.throws(function () {\n extension.getNumLightsSync(0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getNumLightsSync(0, {});\n });\n\n assert.throws(function () {\n extension.getNumLightsSync(null, {});\n }, TypeError);\n });\n\n it('should require second argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getNumLightsSync(0, {});\n });\n\n assert.throws(function () {\n extension.getNumLightsSync(0, null);\n }, TypeError);\n });\n });\n\n\n describe('getLightDescription()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightDescription, 'function');\n });\n\n it('should require atleast 2 arguments', function (done) {\n assert.throws(function () {\n extension.getLightDescription();\n }, Error);\n\n assert.throws(function () {\n extension.getLightDescription(0);\n }, Error);\n\n assert.doesNotThrow(function () {\n extension.getLightDescription(0, 0, done);\n });\n });\n\n it('should require first argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightDescription(null, 0, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightDescription(0, 0, done);\n });\n });\n\n it('should require second argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightDescription(0, null, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightDescription(0, 0, done);\n });\n });\n\n it('should allow callback as a third argument', function (done) {\n assert.throws(function () {\n extension.getLightDescription(0, 0, null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightDescription(0, 0, done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getLightDescription(0, 0, done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getLightDescriptionSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightDescriptionSync, 'function');\n });\n\n it('should require atleast 3 arguments', function () {\n assert.doesNotThrow(function () {\n extension.getLightDescriptionSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightDescriptionSync();\n }, Error);\n\n assert.throws(function () {\n extension.getLightDescriptionSync(0);\n }, Error);\n\n assert.throws(function () {\n extension.getLightDescriptionSync(0, 0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightDescriptionSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightDescriptionSync(null, 0, {});\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightDescriptionSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightDescriptionSync(0, null, {});\n }, TypeError);\n });\n\n it('should require third argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getLightDescriptionSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightDescriptionSync(0, 0, null);\n }, TypeError);\n });\n });\n\n\n describe('getLightLocation()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightLocation, 'function');\n });\n\n it('should require atleast 2 arguments', function (done) {\n assert.throws(function () {\n extension.getLightLocation();\n }, Error);\n\n assert.throws(function () {\n extension.getLightLocation(0);\n }, Error);\n\n assert.doesNotThrow(function () {\n extension.getLightLocation(0, 0, done);\n });\n });\n\n it('should require first argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightLocation(null, 0, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightLocation(0, 0, done);\n });\n });\n\n it('should require second argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightLocation(0, null, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightLocation(0, 0, done);\n });\n });\n\n it('should allow callback as a third argument', function (done) {\n assert.throws(function () {\n extension.getLightLocation(0, 0, null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightLocation(0, 0, done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getLightLocation(0, 0, done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getLightLocationSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightLocationSync, 'function');\n });\n\n it('should require atleast 3 arguments', function () {\n assert.doesNotThrow(function () {\n extension.getLightLocationSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightLocationSync();\n }, Error);\n\n assert.throws(function () {\n extension.getLightLocationSync(0);\n }, Error);\n\n assert.throws(function () {\n extension.getLightLocationSync(0, 0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightLocationSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightLocationSync(null, 0, {});\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightLocationSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightLocationSync(0, null, {});\n }, TypeError);\n });\n\n it('should require third argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getLightLocationSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightLocationSync(0, 0, 0);\n }, TypeError);\n });\n });\n\n\n describe('getLightColor()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightColor, 'function');\n });\n\n it('should require atleast 2 arguments', function (done) {\n assert.throws(function () {\n extension.getLightColor();\n }, Error);\n\n assert.throws(function () {\n extension.getLightColor(0);\n }, Error);\n\n assert.doesNotThrow(function () {\n extension.getLightColor(0, 0, done);\n });\n });\n\n it('should require first argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightColor(null, 0, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightColor(0, 0, done);\n });\n });\n\n it('should require second argument of type number', function (done) {\n assert.throws(function () {\n extension.getLightColor(0, null, utilities.functions.empty);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightColor(0, 0, done);\n });\n });\n\n it('should allow callback as a third argument', function (done) {\n assert.throws(function () {\n extension.getLightColor(0, 0, null);\n }, TypeError);\n\n assert.doesNotThrow(function () {\n extension.getLightColor(0, 0, done);\n });\n });\n\n it('should not complete synchonously', function (done) {\n var completed = false;\n\n extension.getLightColor(0, 0, done);\n\n assert.strictEqual(completed, false);\n });\n });\n\n\n describe('getLightColorSync()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.getLightColorSync, 'function');\n });\n\n it('should require atleast 3 arguments', function () {\n assert.doesNotThrow(function () {\n extension.getLightColorSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightColorSync();\n }, Error);\n\n assert.throws(function () {\n extension.getLightColorSync(0);\n }, Error);\n\n assert.throws(function () {\n extension.getLightColorSync(0, 0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightColorSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightColorSync(null, 0, {});\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.getLightColorSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightColorSync(0, null, {});\n }, TypeError);\n });\n\n it('should require third argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.getLightColorSync(0, 0, {});\n });\n\n assert.throws(function () {\n extension.getLightColorSync(0, 0, null);\n }, TypeError);\n });\n });\n\n\n describe('setLightColor()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.setLightColor, 'function');\n });\n\n it('should require atleast 3 arguments', function () {\n assert.doesNotThrow(function () {\n extension.setLightColor(0, 0, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightColor();\n }, Error);\n\n assert.throws(function () {\n extension.setLightColor(0);\n }, Error);\n\n assert.throws(function () {\n extension.setLightColor(0, 0);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightColor(0, 0, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightColor(null, 0, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightColor(0, 0, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightColor(0, null, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require third argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.setLightColor(0, 0, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightColor(0, 0, null);\n }, TypeError);\n });\n });\n\n\n describe('setLightActionColor()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.setLightActionColor, 'function');\n });\n\n it('should require atleast 4 arguments', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColor();\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColor(0);\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColor(0, 0);\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColor(null, 0, extension.Action.MORPH, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColor(0, null, extension.Action.MORPH, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require third argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColor(0, 0, null, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require fourth argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColor(0, 0, extension.Action.MORPH, null);\n }, TypeError);\n });\n });\n\n\n describe('setLightActionColorEx()', function () {\n\n it('should be a function', function () {\n assert.equal(typeof extension.setLightActionColorEx, 'function');\n });\n\n it('should require atleast 5 arguments', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx();\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColorEx(0);\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, 0);\n }, Error);\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE);\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx(null, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require second argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, null, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require third argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, 0, null, utilities.colors.NONE, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require fourth argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, null, utilities.colors.NONE);\n }, TypeError);\n });\n\n it('should require fifth argument of type object', function () {\n assert.doesNotThrow(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, utilities.colors.NONE);\n });\n\n assert.throws(function () {\n extension.setLightActionColorEx(0, 0, extension.Action.MORPH, utilities.colors.NONE, null);\n }, TypeError);\n });\n });\n\n\n describe('setTiming()', function () {\n\n it('should be a function', function () {\n assert.strictEqual(typeof extension.setTiming, 'function');\n });\n\n it('should require atleast 1 argument', function () {\n assert.doesNotThrow(function () {\n extension.setTiming(200);\n });\n\n assert.throws(function () {\n extension.setTiming();\n }, Error);\n });\n\n it('should require first argument of type number', function () {\n assert.doesNotThrow(function () {\n extension.setTiming(200);\n });\n\n assert.throws(function () {\n extension.setTiming(null);\n }, TypeError);\n });\n });\n\n});\n"
},
{
"alpha_fraction": 0.5092524290084839,
"alphanum_fraction": 0.5173945426940918,
"avg_line_length": 28.69230842590332,
"blob_id": "8e87ac89149a337e98409a19c51bd12b6da6a44f",
"content_id": "8be9b1e8501841567998931131008c6c8ef7aee7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2702,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 91,
"path": "/samples/sdk/sampleApp1.js",
"repo_name": "alexeiskachykhin/node-alienfx",
"src_encoding": "UTF-8",
"text": "var extension = require('bindings')('alienfx.node');\n\n\nif (extension.isAvailable) {\n var result = extension.initializeSync();\n\n if (result === extension.Result.SUCCESS) {\n extension.reset();\n\n var devices = {};\n extension.getNumDevicesSync(devices);\n\n for (var deviceIndex = 0; deviceIndex < devices.numberOfDevices; deviceIndex++) {\n var lights = {};\n extension.getNumLightsSync(deviceIndex, lights);\n\n for (var lightIndex = 0; lightIndex < lights.numberOfLights; lightIndex++) {\n var redColor = {\n red: 0xFF,\n green: 0x00,\n blue: 0x00,\n brightness: 0xFF\n };\n\n var blueColor = {\n red: 0x00,\n green: 0x00,\n blue: 0xFF,\n brightness: 0xFF\n };\n\n var actualColor = (lightIndex % 2 === 0) ? redColor : blueColor;\n\n extension.setLightColor(deviceIndex, lightIndex, actualColor);\n }\n }\n\n extension.update();\n\n\n for (var deviceIndex = 0; deviceIndex < devices.numberOfDevices; deviceIndex++) {\n var deviceDescription = {};\n extension.getDeviceDescriptionSync(deviceIndex, deviceDescription);\n\n console.info('Description: %s', deviceDescription.model);\n\n\n var lights = {};\n extension.getNumLightsSync(deviceIndex, lights);\n\n for (var lightIndex = 0; lightIndex < lights.numberOfLights; lightIndex++) {\n var light = {};\n result = extension.getLightDescriptionSync(deviceIndex, lightIndex, light);\n\n if (result !== extension.Result.SUCCESS) {\n continue;\n }\n\n\n var color = {};\n result = extension.getLightColorSync(deviceIndex, lightIndex, color);\n\n if (result !== extension.Result.SUCCESS) {\n continue;\n }\n\n\n console.info('Light: %d\\tDescription: %s\\tColor: %j', lightIndex, light.lightDescription, color);\n }\n }\n\n\n require('./utilities').waitForKeyPress(function () {\n extension.releaseSync();\n });\n }\n else {\n switch (result) {\n case extension.Result.NODEVS:\n console.error('There are no AlienFX devices available.');\n break;\n\n default:\n console.error('There was an error initializing the AlienFX device.');\n break;\n }\n }\n}\nelse {\n console.error('Failed to load LightFX.dll.');\n}\n"
}
] | 18 |
overtheaurora/tensorflow
|
https://github.com/overtheaurora/tensorflow
|
b707dfbf67caa373447c65967e96584e409da6f4
|
74b961829e1a76a618e4706a892cafaf95d9d0ce
|
6a24e5c162e1a849a6a90c400d6e4294cc1a2928
|
refs/heads/master
| 2020-04-28T09:21:47.283929 | 2019-03-12T06:43:38 | 2019-03-12T06:48:32 | 175,164,349 | 1 | 0 |
Apache-2.0
| 2019-03-12T08:13:12 | 2019-03-12T08:11:40 | 2019-03-12T06:48:52 | null |
[
{
"alpha_fraction": 0.5263739228248596,
"alphanum_fraction": 0.5657631754875183,
"avg_line_length": 45.08165740966797,
"blob_id": "b479e61c910fc0249215e9dd1cfcfeb4cd2dc6bb",
"content_id": "60b55654855b72761d1f19a9a5c56dc9e351b165",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 160272,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 3478,
"path": "/tensorflow/lite/kernels/internal/optimized/depthwiseconv_uint8_transitional.h",
"repo_name": "overtheaurora/tensorflow",
"src_encoding": "UTF-8",
"text": "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n#ifndef TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_DEPTHWISECONV_UINT8_TRANSITIONAL_H_\n#define TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_DEPTHWISECONV_UINT8_TRANSITIONAL_H_\n\n// This file provides kernel implementations that are not used in shipped\n// inference code, but rather (a) show how model C++ code is designed and then\n// transformed into asm code, and (b) aid with maintenance and later development\n// of variations. Many projects (even including, say, the classic NAG libraries)\n// develop highly optimized code, but do not maintain intermediate versions.\n// Often the result is incomprehensible final-version code.\n\n#include <algorithm>\n\n#include \"fixedpoint/fixedpoint.h\"\n#include \"tensorflow/lite/kernels/internal/common.h\"\n#include \"tensorflow/lite/kernels/internal/compatibility.h\"\n#include \"tensorflow/lite/kernels/internal/optimized/depthwiseconv_uint8.h\"\n#include \"tensorflow/lite/kernels/internal/optimized/depthwiseconv_uint8_3x3_filter.h\"\n#include \"tensorflow/lite/kernels/internal/reference/depthwiseconv_uint8.h\"\n#include \"tensorflow/lite/kernels/internal/types.h\"\n\nnamespace tflite {\nnamespace optimized_ops {\nnamespace depthwise_conv {\n\n#if defined(USE_NEON)\n\n#define vst1_lane_u8x4(dst, reg, lane_num) \\\n vst1_lane_u32(reinterpret_cast<uint32_t*>(dst), vreinterpret_u32_u8(reg), \\\n lane_num)\n\n#define vst1q_lane_u8x4(dst, reg, lane_num) \\\n vst1q_lane_u32(reinterpret_cast<uint32_t*>(dst), vreinterpretq_u32_u8(reg), \\\n \\\n lane_num)\n\n#define vld1q_lane_s8x8(src, reg, lane_num) \\\n vld1q_lane_u64(reinterpret_cast<const uint64_t*>(src), reg, lane_num)\n\n#ifndef __aarch64__\ninline int8x16_t vqtbl4q_s8(int8x16x4_t a, uint8x16_t b) {\n const uint8x16_t mask = vtstq_u8(b, vdupq_n_u8(8));\n\n // Delete bit 3 from the indices.\n const uint8x16_t high_bits = vshrq_n_u8(b, 4);\n uint8x16_t deleted_bit_3 = b;\n deleted_bit_3 = vsliq_n_u8(deleted_bit_3, high_bits, 3);\n\n int8x8x4_t repacked_data;\n\n // Calculate for lower indices.\n repacked_data.val[0] = vget_low_u8(a.val[0]);\n repacked_data.val[1] = vget_low_u8(a.val[1]);\n repacked_data.val[2] = vget_low_u8(a.val[2]);\n repacked_data.val[3] = vget_low_u8(a.val[3]);\n const int8x16_t output_for_lower =\n vcombine_u8(vtbl4_s8(repacked_data, vget_low_u8(deleted_bit_3)),\n vtbl4_s8(repacked_data, vget_high_u8(deleted_bit_3)));\n\n // Calculate for high indices.\n repacked_data.val[0] = vget_high_u8(a.val[0]);\n repacked_data.val[1] = vget_high_u8(a.val[1]);\n repacked_data.val[2] = vget_high_u8(a.val[2]);\n repacked_data.val[3] = vget_high_u8(a.val[3]);\n const int8x16_t output_for_higher =\n vcombine_u8(vtbl4_s8(repacked_data, vget_low_u8(deleted_bit_3)),\n vtbl4_s8(repacked_data, vget_high_u8(deleted_bit_3)));\n\n // Merge.\n int8x16_t output = mask;\n output = vbslq_u8(output, output_for_higher, output_for_lower);\n return output;\n}\n#endif // !__aarch64__\n\n// Convenience-compatibility functions.\n// Compatibility: Intrinsics reflect a mixture of older and newer ARM\n// instructions. This actually results in ZIP1 / ZIP2 asm instructions, but\n// one intrinsic is provided. Also older instructions operated in place,\n// and it seems more defensive to assume that some versions of intrinsics\n// might reflect this\n// Convenience: Callers in these kernels want both ZIP1 and ZIP2, and we do not\n// want the calling code to get cluttered with unpacking int8x16x2_t.\ninline void vzipq_s8_in_place(int8x16_t* a, int8x16_t* b) {\n int8x16x2_t r8x16;\n r8x16 = vzipq_s8(*a, *b);\n *a = r8x16.val[0];\n *b = r8x16.val[1];\n}\n\ninline void vzipq_s8x2_in_place(int8x16_t* a, int8x16_t* b) {\n int16x8x2_t r16x8;\n r16x8 = vzipq_s16(vreinterpretq_s16_s8(*a), vreinterpretq_s16_s8(*b));\n *a = vreinterpretq_s8_s16(r16x8.val[0]);\n *b = vreinterpretq_s8_s16(r16x8.val[1]);\n}\n\n// Similar rationale to the zip-in_place functions, but callers only actually\n// need the TRN1 asm instruction result.\ninline void vtrn1_s8x2_in_place(int8x16_t* a, int8x16_t* b) {\n int16x8x2_t r16x8;\n r16x8 = vtrnq_s16(vreinterpretq_s16_s8(*a), vreinterpretq_s16_s8(*b));\n *a = vreinterpretq_s8_s16(r16x8.val[0]);\n}\n\ninline void biregister_rotate_8(int8x16_t* left, int8x16_t* right) {\n *left = vreinterpretq_s8_u32(vshrq_n_u32(vreinterpretq_u32_s8(*left), 8));\n *left = vreinterpretq_s8_u32(vsliq_n_u32(vreinterpretq_u32_s8(*left),\n vreinterpretq_u32_s8(*right), 24));\n *right = vreinterpretq_s8_u32(vshrq_n_u32(vreinterpretq_u32_s8(*right), 8));\n}\n\n#ifndef __aarch64__\ninline int32x4_t vpaddq_s32(int32x4_t a, int8x16_t b) {\n int32x4x2_t deinterleaved = vuzpq_s32(a, b);\n return vqaddq_s32(deinterleaved.val[0], deinterleaved.val[1]);\n}\n#endif // !__aarch64__\n\n#ifdef __ARM_FEATURE_DOTPROD\n// The vdotq_lane_s32 takes int8x8t for the rhs parameter, whereas the actual\n// instruction selects from between 4 32-bit (4x8-bit packed) sub-registers, an\n// unusual interpretation of \"lane\".\ninline int32x4_t vdotq_four_lane_s32(int32x4_t acc, int8x16_t lhs,\n int8x16_t rhs, const int lane) {\n switch (lane) {\n case 0:\n return vdotq_lane_s32(acc, lhs, vreinterpret_s32_s8(vget_low_s8(rhs)), 0);\n case 1:\n return vdotq_lane_s32(acc, lhs, vreinterpret_s32_s8(vget_low_s8(rhs)), 1);\n case 2:\n return vdotq_lane_s32(acc, lhs, vreinterpret_s32_s8(vget_high_s8(rhs)),\n 0);\n case 3:\n default:\n return vdotq_lane_s32(acc, lhs, vreinterpret_s32_s8(vget_high_s8(rhs)),\n 1);\n }\n}\n\n#else\n\ninline int32x4_t vdotq_s32(int32x4_t acc, int8x16_t lhs, int8x16_t rhs) {\n int32x4_t sum0 = vpaddlq_s16(vmull_s8(vget_low_s8(lhs), vget_low_s8(rhs)));\n int32x4_t sum1 = vpaddlq_s16(vmull_s8(vget_high_s8(lhs), vget_high_s8(rhs)));\n int32x4_t sum = vpaddq_s32(sum0, sum1);\n return vaddq_s32(acc, sum);\n}\n\ninline int32x4_t vdotq_four_lane_s32(int32x4_t acc, int8x16_t lhs,\n int8x16_t rhs, int lane) {\n int8x8_t lane_rhs;\n if (lane == 0) {\n lane_rhs = vreinterpret_s8_s32(\n vdup_lane_s32(vreinterpret_s32_s8(vget_low_s8(rhs)), 0));\n } else if (lane == 1) {\n lane_rhs = vreinterpret_s8_s32(\n vdup_lane_s32(vreinterpret_s32_s8(vget_low_s8(rhs)), 1));\n } else if (lane == 2) {\n lane_rhs = vreinterpret_s8_s32(\n vdup_lane_s32(vreinterpret_s32_s8(vget_high_s8(rhs)), 0));\n } else {\n lane_rhs = vreinterpret_s8_s32(\n vdup_lane_s32(vreinterpret_s32_s8(vget_high_s8(rhs)), 1));\n }\n int32x4_t sum0 = vpaddlq_s16(vmull_s8(vget_low_s8(lhs), lane_rhs));\n int32x4_t sum1 = vpaddlq_s16(vmull_s8(vget_high_s8(lhs), lane_rhs));\n int32x4_t sum = vpaddq_s32(sum0, sum1);\n return vaddq_s32(acc, sum);\n}\n#endif // !DOTPROD\n#endif // ARM NEON\n\ntemplate <DepthwiseConvOutputRounding output_rounding>\nstruct DivideByPOT {};\n\ntemplate <>\nstruct DivideByPOT<DepthwiseConvOutputRounding::kAwayFromZero> {\n template <typename IntegerType>\n static inline IntegerType Run(IntegerType x, int exponent) {\n return RoundingDivideByPOT(x, exponent);\n }\n};\n\n#if defined(USE_NEON)\ntemplate <>\nstruct DivideByPOT<DepthwiseConvOutputRounding::kUpward> {\n template <typename IntegerType>\n static inline IntegerType Run(IntegerType x, int exponent) {\n return vqrshlq_s32(x, vdupq_n_s32(static_cast<int32>(-exponent)));\n }\n};\n#endif // ARM NEON\n\ntemplate <>\nstruct ProcessPerDepth<DepthwiseConvImplementation::kUseCModel3x3DotProduct> {\n // Filter data is provided as filter_block[3][3][depth/8][2][4]: height 3,\n // width 3, sub-block 0 or 1, depth 4. Filter data is written as\n // filter_bank[3][2][4][4]; height 3, sub-block, depth 4, width 4.\n //\n // Note that this rearrangement is much like that performed on input data when\n // filling the workspace, and optimized versions will be similar.\n static inline void FillFilterBank(int depth, const uint8* filter_block,\n int8 filter_bank[3][2][4][4]) {\n constexpr int kSymmetricZeroPoint = 128;\n // Load filter data in, 8-bytes down depth / sub-block at a time.\n //\n // loaded_filter has dimensions height 3, width 4, sub-block 0 or 1,\n // depth 4.\n uint8 loaded_filter[3][4][2][4];\n for (int y = 0; y < 3; ++y) {\n for (int x = 0; x < 3; ++x) {\n memcpy(loaded_filter[y][x][0], &filter_block[3 * y * depth + x * depth],\n 8);\n }\n // Pad the filter with symmetric representation of 0, so that the values\n // become 0 when the zero-poing is added below. Thus these filter taps are\n // effectively disregarded in later filtering.\n memset(loaded_filter[y][3][0], kSymmetricZeroPoint, 8);\n }\n for (int y = 0; y < 3; ++y) {\n for (int z = 0; z < 4; ++z) {\n for (int x = 0; x < 4; ++x) {\n filter_bank[y][0][z][x] =\n loaded_filter[y][x][0][z] - kSymmetricZeroPoint;\n filter_bank[y][1][z][x] =\n loaded_filter[y][x][1][z] - kSymmetricZeroPoint;\n }\n }\n }\n }\n\n // Adjust the bias (weights) data according to the input offset.\n //\n // The output calculation is\n // out[h][w][d] = bias[d] + sum_ij (in[h+i][w+j][d] + in_offset) *\n // (filter[i][j][d] + filter_offset)\n // (where offsets are expressed as differences from 128).\n //\n // Since we cannot efficiently handle varying offsets / bias across the image,\n // we insist on filter_offset = 0.\n //\n // This function calculates\n // adjusted_bias[d] = bias[d] + sum_ij in_offset * filter[i][j][d]\n // which accounts for input offset. If the bias is constant over the depth,\n // the adjusted bias will vary.\n static inline void AdjustBias(int32 input_offset,\n const int8 filter_bank[3][2][4][4],\n const int32* bias_data,\n int32 adjusted_bias_block[2][4]) {\n constexpr int kSymmetricZeroPoint = 128;\n TFLITE_DCHECK_GE(input_offset, -255);\n TFLITE_DCHECK_LE(input_offset, 0);\n // For instance, if input_offset == 128, no adjustment is needed.\n const int32 input_offset_difference = input_offset + kSymmetricZeroPoint;\n\n for (int s = 0; s < 2; ++s) {\n for (int z = 0; z < 4; ++z) {\n adjusted_bias_block[s][z] = bias_data[4 * s + z];\n for (int i = 0; i < 9; ++i) {\n adjusted_bias_block[s][z] +=\n input_offset_difference * filter_bank[i % 3][s][z][i / 3];\n }\n }\n }\n }\n\n static void Run(const uint8* filter_data, const int32* bias_data,\n int8* shuffled_filter_data, int32* adjusted_bias_data,\n const DepthwiseConvDotProdParams* function_params) {\n constexpr int shuffled_filter_increment = 2 * 3 * 4 * 4;\n const int depth = function_params->output_depth;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int bias_increment = function_params->bias_increment;\n const int32 input_offset = function_params->input_offset;\n\n int8 filter_bank[3][2][4][4];\n int32 adjusted_bias_block[2][4];\n\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n FillFilterBank(depth, filter_data + 8 * j_depth, filter_bank);\n AdjustBias(input_offset, filter_bank,\n bias_data + 2 * bias_increment * j_depth, adjusted_bias_block);\n\n memcpy(shuffled_filter_data, filter_bank[0][0][0],\n shuffled_filter_increment);\n shuffled_filter_data += shuffled_filter_increment;\n memcpy(adjusted_bias_data, adjusted_bias_block[0],\n 8 * sizeof(adjusted_bias_block[0][0]));\n adjusted_bias_data += 8;\n }\n }\n};\n\n#if defined(USE_NEON)\ntemplate <>\nstruct ProcessPerDepth<\n DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct> {\n static void ProcessPerDepthIntrinsics(\n const uint8* filter_data, const int32* bias_data,\n int8* shuffled_filter_data, int32* adjusted_bias_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int depth = function_params->output_depth;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int bias_increment = function_params->bias_increment;\n\n constexpr int kSymmetricZeroPoint = 128;\n constexpr uint8 kSignBit = 0x80;\n const int32 input_offset = function_params->input_offset;\n TFLITE_DCHECK_GE(input_offset, -255);\n TFLITE_DCHECK_LE(input_offset, 0);\n const int32 input_offset_difference = input_offset + kSymmetricZeroPoint;\n const int8x16_t ones_vector = vdupq_n_s8(1);\n\n // Simulate NEON-register transposition of subset of filter.\n int8x16_t filter_reg_0_a;\n int8x16_t filter_reg_0_b;\n int8x16_t filter_reg_1_a;\n int8x16_t filter_reg_1_b;\n int8x16_t filter_reg_2_a;\n int8x16_t filter_reg_2_b;\n\n // Register pairs for each height.\n // Effect subtraction of zero-point = 128 by XOR of sign bit.\n const uint8x16_t sign_bit = vdupq_n_u8(kSignBit);\n\n const uint8* filter_block = filter_data;\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n // Filter data is provided as filter_block[3][3][depth/8][2][4].\n // height 3, width 3, micro-blocks, sub-block 0 or 1, depth 4.\n // filter_bank[3][2][4][4]; Sub-block, height 3, depth 4, width 4.\n\n // Load zero-point into effective position of zero-padding of filter\n // (register B, upper part).\n filter_reg_0_b = vdupq_n_u8(kSignBit);\n filter_reg_1_b = vdupq_n_u8(kSignBit);\n filter_reg_2_b = vdupq_n_u8(kSignBit);\n\n const uint8* filter_block_ptr = filter_block;\n filter_reg_0_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_0_a, 0);\n filter_block_ptr += depth;\n filter_reg_0_b = vld1q_lane_s8x8(filter_block_ptr, filter_reg_0_b, 0);\n filter_block_ptr += depth;\n filter_reg_0_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_0_a, 1);\n filter_block_ptr += depth;\n filter_reg_1_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_1_a, 0);\n filter_block_ptr += depth;\n filter_reg_1_b = vld1q_lane_s8x8(filter_block_ptr, filter_reg_1_b, 0);\n filter_block_ptr += depth;\n filter_reg_1_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_1_a, 1);\n filter_block_ptr += depth;\n filter_reg_2_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_2_a, 0);\n filter_block_ptr += depth;\n filter_reg_2_b = vld1q_lane_s8x8(filter_block_ptr, filter_reg_2_b, 0);\n filter_block_ptr += depth;\n filter_reg_2_a = vld1q_lane_s8x8(filter_block_ptr, filter_reg_2_a, 1);\n\n filter_reg_0_a = veorq_s8(filter_reg_0_a, sign_bit);\n filter_reg_0_b = veorq_s8(filter_reg_0_b, sign_bit);\n filter_reg_1_a = veorq_s8(filter_reg_1_a, sign_bit);\n filter_reg_1_b = veorq_s8(filter_reg_1_b, sign_bit);\n filter_reg_2_a = veorq_s8(filter_reg_2_a, sign_bit);\n filter_reg_2_b = veorq_s8(filter_reg_2_b, sign_bit);\n\n vzipq_s8_in_place(&filter_reg_0_a, &filter_reg_0_b);\n vzipq_s8_in_place(&filter_reg_1_a, &filter_reg_1_b);\n vzipq_s8_in_place(&filter_reg_2_a, &filter_reg_2_b);\n vzipq_s8x2_in_place(&filter_reg_0_a, &filter_reg_0_b);\n vzipq_s8x2_in_place(&filter_reg_1_a, &filter_reg_1_b);\n vzipq_s8x2_in_place(&filter_reg_2_a, &filter_reg_2_b);\n\n vst1q_s8(shuffled_filter_data, filter_reg_0_a);\n shuffled_filter_data += 16;\n vst1q_s8(shuffled_filter_data, filter_reg_0_b);\n shuffled_filter_data += 16;\n vst1q_s8(shuffled_filter_data, filter_reg_1_a);\n shuffled_filter_data += 16;\n vst1q_s8(shuffled_filter_data, filter_reg_1_b);\n shuffled_filter_data += 16;\n vst1q_s8(shuffled_filter_data, filter_reg_2_a);\n shuffled_filter_data += 16;\n vst1q_s8(shuffled_filter_data, filter_reg_2_b);\n shuffled_filter_data += 16;\n\n int32x4_t adjusted_bias_data_a = vld1q_s32(bias_data);\n bias_data += bias_increment;\n int32x4_t adjusted_bias_data_b = vld1q_s32(bias_data);\n bias_data += bias_increment;\n // For instance, if input_offset == 128, no adjustment is needed.\n\n int32x4_t filter_sum_a = vdupq_n_s32(0);\n filter_sum_a = vdotq_s32(filter_sum_a, filter_reg_0_a, ones_vector);\n filter_sum_a = vdotq_s32(filter_sum_a, filter_reg_1_a, ones_vector);\n filter_sum_a = vdotq_s32(filter_sum_a, filter_reg_2_a, ones_vector);\n int32x4_t filter_sum_b = vdupq_n_s32(0);\n filter_sum_b = vdotq_s32(filter_sum_b, filter_reg_0_b, ones_vector);\n filter_sum_b = vdotq_s32(filter_sum_b, filter_reg_1_b, ones_vector);\n filter_sum_b = vdotq_s32(filter_sum_b, filter_reg_2_b, ones_vector);\n\n adjusted_bias_data_a = vmlaq_n_s32(adjusted_bias_data_a, filter_sum_a,\n input_offset_difference);\n adjusted_bias_data_b = vmlaq_n_s32(adjusted_bias_data_b, filter_sum_b,\n input_offset_difference);\n\n vst1q_s32(adjusted_bias_data, adjusted_bias_data_a);\n adjusted_bias_data += 4;\n vst1q_s32(adjusted_bias_data, adjusted_bias_data_b);\n adjusted_bias_data += 4;\n\n filter_block += 8;\n }\n }\n\n static inline void Run(const uint8* filter_data, const int32* bias_data,\n int8* shuffled_filter_data, int32* adjusted_bias_data,\n const DepthwiseConvDotProdParams* function_params) {\n ProcessPerDepthIntrinsics(filter_data, bias_data, shuffled_filter_data,\n adjusted_bias_data, function_params);\n }\n};\n#endif\n\ntemplate <int32 max_padding>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseCModel3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n max_padding> {\n // A straight copy of a macro block of input data into a scratch buffer.\n //\n // Requirement: depth_micro_repeats > 0.\n static inline void CopyMacroBlock(\n int32 height_block_number, int32 width_block_number,\n const DepthwiseConvDotProdParams& function_params,\n const uint8* input_block_data, int8* scratch_block_data) {\n TFLITE_DCHECK_LE(max_padding, 1);\n\n // Strides.\n // The input depth and count of micro blocks provide the width strides.\n const int input_height_stride = function_params.input_height_stride;\n const int workspace_height_stride = function_params.workspace_height_stride;\n const int input_depth = function_params.input_depth;\n const int depth_micro_repeats = function_params.depth_micro_repeats;\n TFLITE_DCHECK_GT(depth_micro_repeats, 0);\n\n // Remaining iteration and dimension parameters.\n //\n // If width_overall_micro_repeats = input_width_micro_repeats + 1, then the\n // final micro block is incomplete.\n const int width_overall_micro_repeats =\n function_params.input_width_overall_micro_repeats;\n int input_width_micro_repeats = function_params.input_width_micro_repeats;\n const int residual_width = function_params.residual_width;\n const int block_height = function_params.inbound_block_height;\n\n const int padding_left = function_params.padding_left;\n const int padding_right = function_params.padding_right;\n const int padding_top = function_params.padding_top;\n const int padding_bottom = function_params.padding_bottom;\n\n const bool leading_width_padding =\n padding_left > 0 && width_block_number == 0;\n const bool trailing_width_padding =\n padding_right > 0 &&\n width_block_number == (function_params.width_macro_count - 1);\n const bool leading_height_padding =\n padding_top > 0 && height_block_number < 0;\n const bool trailing_height_padding =\n padding_bottom > 0 &&\n height_block_number == (function_params.height_macro_count - 1);\n\n // Modify the trailing case to reflect the input width.\n int input_residual_width =\n input_width_micro_repeats < width_overall_micro_repeats ? residual_width\n : 4;\n if (trailing_width_padding) {\n input_residual_width -= 1;\n input_width_micro_repeats = width_overall_micro_repeats - 1;\n }\n\n constexpr int kSymmetricZeroPoint = 128;\n const int32 input_offset_difference =\n function_params.input_offset + kSymmetricZeroPoint;\n\n // We load data into a temporary buffer and then save, to match subsequent\n // processing. This will make it easier to combine stages into one ASM\n // routine.\n int8 tmp_load[4][2][4];\n\n int copy_block_height = block_height;\n if (leading_height_padding) {\n memset(scratch_block_data, -input_offset_difference,\n workspace_height_stride);\n scratch_block_data += workspace_height_stride;\n input_block_data += input_height_stride;\n copy_block_height -= 1;\n }\n if (trailing_height_padding) {\n copy_block_height -= 1;\n }\n\n // The outer 3 loops go through all the micro blocks in a macro block.\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n for (int j_width = 0; j_width < width_overall_micro_repeats; ++j_width) {\n // Figure out division of work (available input vs trailing padding).\n int adjusted_residual_width =\n j_width == input_width_micro_repeats ? input_residual_width : 4;\n\n int start_width = 0;\n if (leading_width_padding && j_width == 0) {\n start_width = 1;\n memset(tmp_load[0][0], -input_offset_difference, 8);\n }\n if (adjusted_residual_width < 4) {\n for (int x = adjusted_residual_width; x < 4; ++x) {\n memset(tmp_load[x][0], -input_offset_difference, 8);\n }\n }\n\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n // The inner 3 loops go through the sub-block, depth and width within\n // each micro block.\n\n // Load, and apply symmetric offset.\n int8* scratch_data =\n scratch_block_data + k_height * workspace_height_stride +\n j_width * 4 * 8 + i_depth * 4 * 8 * width_overall_micro_repeats;\n const uint8* input_data = input_block_data +\n k_height * input_height_stride +\n j_width * 4 * input_depth + i_depth * 8;\n // Full-size macro blocks are 2*4*4 = 32 bytes.\n for (int x = start_width; x < adjusted_residual_width; ++x) {\n for (int s = 0; s < 2; ++s) {\n for (int d = 0; d < 4; ++d) {\n tmp_load[x][s][d] = input_data[x * input_depth + 4 * s + d] -\n kSymmetricZeroPoint;\n }\n }\n }\n\n // Save results.\n memcpy(&scratch_data[0], tmp_load[0][0], 8);\n memcpy(&scratch_data[8], tmp_load[1][0], 8);\n memcpy(&scratch_data[16], tmp_load[2][0], 8);\n memcpy(&scratch_data[24], tmp_load[3][0], 8);\n }\n }\n }\n\n if (trailing_height_padding) {\n memset(scratch_block_data + copy_block_height * workspace_height_stride,\n -input_offset_difference, workspace_height_stride);\n }\n }\n\n // Transpose 4x4 blocks within each sub-micro-block.\n //\n // Implemented somewhat like NEON register manipulation, so that we can see\n // equivalence of the two approaches.\n static inline void MicroTransposeBlocks(\n const DepthwiseConvDotProdParams& function_params,\n int8* scratch_block_data) {\n const int workspace_height_stride = function_params.workspace_height_stride;\n const int width_overall_micro_repeats =\n function_params.input_width_overall_micro_repeats;\n const int depth_micro_repeats = function_params.depth_micro_repeats;\n const int block_height = function_params.inbound_block_height;\n\n // Transpositions are 4x4, but doing 2 at a time is more efficient in the\n // NEON code we are simulating.\n int8 tmp_load[4][2][4]; // [width][sub-block][depth]\n int8 tmp_transposed[4][2][4]; // [depth][sub-block][width]\n int8 tmp_interleaved[2][4][4]; // [sub-block][depth][width]\n\n // The outer 3 loops go through all the micro blocks in a macro block.\n for (int k_height = 0; k_height < block_height; ++k_height) {\n for (int j_width = 0; j_width < width_overall_micro_repeats; ++j_width) {\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n int8* scratch_data =\n scratch_block_data + k_height * workspace_height_stride +\n j_width * 4 * 8 + i_depth * 4 * 8 * width_overall_micro_repeats;\n // A. Load data\n memcpy(tmp_load[0][0], &scratch_data[0], 8);\n memcpy(tmp_load[1][0], &scratch_data[8], 8);\n memcpy(tmp_load[2][0], &scratch_data[16], 8);\n memcpy(tmp_load[3][0], &scratch_data[24], 8);\n\n // B. Simulate between-register transposition.\n for (int x = 0; x < 4; ++x) {\n for (int y = 0; y < 4; ++y) {\n tmp_transposed[x][0][y] = tmp_load[y][0][x];\n tmp_transposed[x][1][y] = tmp_load[y][1][x];\n }\n }\n\n // C. Simulate between-register interleaving.\n for (int x = 0; x < 4; ++x) {\n for (int y = 0; y < 4; ++y) {\n tmp_interleaved[0][x][y] = tmp_transposed[x][0][y];\n tmp_interleaved[1][x][y] = tmp_transposed[x][1][y];\n }\n }\n // D. Simulate mangled storage arrangement.\n memcpy(&scratch_data[0], tmp_interleaved[0][0], 16);\n memcpy(&scratch_data[16], tmp_interleaved[1][0], 16);\n }\n }\n }\n }\n\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n CopyMacroBlock(height_block_number, width_block_number, *function_params,\n input_block_data, scratch_block_data);\n MicroTransposeBlocks(*function_params, scratch_block_data);\n }\n};\n\ntemplate <int32 max_padding>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseCModel3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n max_padding> {\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n // Currently support for padding is limited to 1 on any side.\n TFLITE_DCHECK_LE(max_padding, 1);\n\n // Strides.\n // The count of micro blocks (below) provides the width strides.\n const int input_height_stride = function_params->input_height_stride;\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n\n // Remaining iteration and dimension parameters.\n //\n // If width_overall_micro_repeats = input_width_micro_repeats + 1, then the\n // final micro block is incomplete.\n const int width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int input_width_micro_repeats =\n function_params->input_width_micro_repeats;\n const int residual_width = function_params->residual_width;\n const int block_height = function_params->inbound_block_height;\n TFLITE_DCHECK_GE(workspace_height_stride, 4 * width_overall_micro_repeats);\n\n const int padding_left = function_params->padding_left;\n const int padding_right = function_params->padding_right;\n const int padding_top = function_params->padding_top;\n const int padding_bottom = function_params->padding_bottom;\n\n const bool leading_width_padding =\n padding_left > 0 && width_block_number == 0;\n const bool trailing_width_padding =\n padding_right > 0 &&\n width_block_number == (function_params->width_macro_count - 1);\n const bool leading_height_padding =\n padding_top > 0 && height_block_number < 0;\n const bool trailing_height_padding =\n padding_bottom > 0 &&\n height_block_number == (function_params->height_macro_count - 1);\n\n constexpr int kSymmetricZeroPoint = 128;\n const int32 input_offset_difference =\n function_params->input_offset + kSymmetricZeroPoint;\n\n int copy_block_height = block_height;\n if (leading_height_padding) {\n memset(scratch_block_data, -input_offset_difference,\n workspace_height_stride + kWorkspaceExtension);\n scratch_block_data += workspace_height_stride;\n input_block_data += input_height_stride;\n copy_block_height -= 1;\n }\n if (trailing_height_padding) {\n copy_block_height -= 1;\n }\n\n int adjusted_residual_width =\n input_width_micro_repeats < width_overall_micro_repeats ? residual_width\n : 4;\n\n if (trailing_width_padding) {\n adjusted_residual_width -= 1;\n }\n int start_width = 0;\n if (leading_width_padding) {\n start_width = 1;\n input_block_data += 1;\n }\n\n const int copy_size = (width_overall_micro_repeats - 1) * 4 +\n adjusted_residual_width - start_width;\n\n TFLITE_DCHECK_LE(\n copy_size,\n input_height_stride - width_block_number * input_width_micro_repeats);\n // We may drop up to stride-1 of trailing input.\n TFLITE_DCHECK_GE(copy_size, input_height_stride - 1);\n\n // When there is unit input depth, the micro-block iteration need only be\n // through the height. The micro blocks are contiguous across the width.\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n const uint8* input_data =\n input_block_data + k_height * input_height_stride;\n int8* scratch_data =\n scratch_block_data + k_height * workspace_height_stride;\n\n // Handle leading padding. This is overwritten if there is no padding.\n scratch_data[0] = -input_offset_difference;\n\n memcpy(&scratch_data[start_width], input_data, copy_size);\n for (int i = 0; i < copy_size; ++i) {\n scratch_data[start_width + i] += -kSymmetricZeroPoint;\n }\n\n // Handle trailing padding, and fill in remainder of micro block.\n memset(&scratch_data[start_width + copy_size], -input_offset_difference,\n 4 - adjusted_residual_width + kWorkspaceExtension);\n }\n\n if (trailing_height_padding) {\n memset(scratch_block_data + copy_block_height * workspace_height_stride,\n -input_offset_difference,\n workspace_height_stride + kWorkspaceExtension);\n }\n }\n};\n\n#if defined(USE_NEON)\n#if defined(__aarch64__)\n// Experiments suggest that a modest performance improvement is seen, at least\n// on 855 chipset big cores, with cache hints.\ninline void PreloadInputBlock(\n const uint8* input_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n // Preload.\n const int input_width_micro_repeats =\n function_params->input_width_micro_repeats;\n const int block_height = function_params->inbound_block_height;\n const int residual_width = function_params->residual_width;\n const int input_height_stride = function_params->input_height_stride;\n const int input_depth = function_params->input_depth;\n\n {\n const int total_width = 4 * input_width_micro_repeats + residual_width;\n const uint8* row_ptr = input_block_data;\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const uint8* ptr = row_ptr;\n for (int j = 0; j < total_width; ++j) {\n // Input data is loaded once.\n asm volatile(\"prfm pldl1strm, [%[ptr]]\\n\" ::[ptr] \"r\"(ptr) :);\n ptr += input_depth;\n }\n row_ptr += input_height_stride;\n }\n }\n}\n#endif\n\ntemplate <>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n /*max_padding=*/0> {\n static inline void PackMacroBlockIntrinsics(\n const uint8* input_block_data, int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n TFLITE_DCHECK_EQ(function_params->padding_bottom, 0);\n TFLITE_DCHECK_EQ(function_params->padding_top, 0);\n TFLITE_DCHECK_EQ(function_params->padding_left, 0);\n TFLITE_DCHECK_EQ(function_params->padding_right, 0);\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int input_width_micro_repeats =\n function_params->input_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int block_height = function_params->inbound_block_height;\n const int residual_width = function_params->residual_width;\n const int input_height_stride = function_params->input_height_stride;\n const int input_depth = function_params->input_depth;\n\n static const uint8 perm_data[64] = {\n 0, 16, 32, 48, 1, 17, 33, 49, 2, 18, 34, 50, 3, 19, 35, 51, //\n 4, 20, 36, 52, 5, 21, 37, 53, 6, 22, 38, 54, 7, 23, 39, 55,\n 8, 24, 40, 56, 9, 25, 41, 57, 10, 26, 42, 58, 11, 27, 43, 59,\n 12, 28, 44, 60, 13, 29, 45, 61, 14, 30, 46, 62, 15, 31, 47, 63};\n\n TFLITE_DCHECK_GE(depth_micro_repeats, 0);\n constexpr uint8 kSignBit = 0x80;\n const int micro_block_size = 4 * 8;\n const int depth_advance = width_overall_micro_repeats * micro_block_size;\n const int width_advance =\n micro_block_size *\n (1 - depth_micro_repeats * width_overall_micro_repeats);\n const int height_advance = workspace_height_stride -\n width_overall_micro_repeats * micro_block_size;\n const int input_depth_skip = 4 * input_depth - 8 * depth_micro_repeats;\n\n // Transpositions are 4x4, but doing 2 at a time is more efficient in NEON\n // code. Note the blocks of 4x4 are still interleaved down the depth.\n int8x16_t work_reg_a;\n int8x16_t work_reg_b;\n const int8x16_t perm_data_0 = vld1q_u8(perm_data);\n const int8x16_t perm_data_1 = vld1q_u8(perm_data + 16);\n const int8x16_t perm_data_2 = vld1q_u8(perm_data + 32);\n const int8x16_t perm_data_3 = vld1q_u8(perm_data + 48);\n\n // Effect subtraction of zero-point = 128 by XOR of sign bit.\n const uint8x16_t sign_bit = vdupq_n_u8(kSignBit);\n\n // Work through one slice, by row, at a time.\n int8* scratch_data_0 = scratch_block_data;\n\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const uint8* input_data_0 = input_block_data;\n const uint8* input_data_1 = input_block_data + input_depth;\n const uint8* input_data_2 = input_block_data + 2 * input_depth;\n const uint8* input_data_3 = input_block_data + 3 * input_depth;\n\n // Traverse the width one point at a time, but the depth in (micro) blocks\n // of size 8.\n //\n // The depth and width margins, which are filled with \"zeros\", may be\n // larger than is strictly needed to calculate output. This is because the\n // conv calculation is performed across complete micro blocks.\n for (int j_width = 0; j_width < input_width_micro_repeats; ++j_width) {\n int i_depth = 0;\n for (; i_depth < depth_micro_repeats - 1; i_depth += 2) {\n int8x16x4_t input_data;\n input_data.val[0] = vld1q_u8(input_data_0);\n input_data.val[1] = vld1q_u8(input_data_1);\n input_data.val[2] = vld1q_u8(input_data_2);\n input_data.val[3] = vld1q_u8(input_data_3);\n input_data_1 += 16;\n input_data_0 += 16;\n\n int8x16_t tmp_0 = vqtbl4q_s8(input_data, perm_data_0);\n int8x16_t tmp_1 = vqtbl4q_s8(input_data, perm_data_1);\n work_reg_a = veorq_s8(tmp_0, sign_bit);\n work_reg_b = veorq_s8(tmp_1, sign_bit);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n input_data_2 += 16;\n input_data_3 += 16;\n\n tmp_0 = vqtbl4q_s8(input_data, perm_data_2);\n tmp_1 = vqtbl4q_s8(input_data, perm_data_3);\n work_reg_a = veorq_s8(tmp_0, sign_bit);\n work_reg_b = veorq_s8(tmp_1, sign_bit);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n }\n for (; i_depth < depth_micro_repeats; ++i_depth) {\n int8x16x4_t input_data;\n input_data.val[0] =\n vld1q_lane_s8x8(input_data_0, input_data.val[0], 0);\n input_data.val[1] =\n vld1q_lane_s8x8(input_data_1, input_data.val[1], 0);\n input_data.val[2] =\n vld1q_lane_s8x8(input_data_2, input_data.val[2], 0);\n input_data.val[3] =\n vld1q_lane_s8x8(input_data_3, input_data.val[3], 0);\n input_data_1 += 8;\n input_data_0 += 8;\n\n int8x16_t tmp_0 = vqtbl4q_s8(input_data, perm_data_0);\n int8x16_t tmp_1 = vqtbl4q_s8(input_data, perm_data_1);\n work_reg_a = veorq_s8(tmp_0, sign_bit);\n work_reg_b = veorq_s8(tmp_1, sign_bit);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n }\n if (width_overall_micro_repeats > input_width_micro_repeats) {\n TFLITE_DCHECK_EQ(width_overall_micro_repeats,\n input_width_micro_repeats + 1);\n TFLITE_DCHECK_GT(residual_width, 0);\n TFLITE_DCHECK_LT(residual_width, 4);\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n work_reg_a = vdupq_n_u8(kSignBit);\n work_reg_a = vld1q_lane_s8x8(input_data_0, work_reg_a, 0);\n work_reg_b = vdupq_n_u8(kSignBit);\n if (residual_width > 1) {\n work_reg_b =\n vld1q_lane_s8x8(input_data_0 + input_depth, work_reg_b, 0);\n if (residual_width == 3) {\n work_reg_a = vld1q_lane_s8x8(input_data_0 + 2 * input_depth,\n work_reg_a, 1);\n }\n }\n work_reg_a = veorq_s8(work_reg_a, sign_bit);\n work_reg_b = veorq_s8(work_reg_b, sign_bit);\n\n vzipq_s8_in_place(&work_reg_a, &work_reg_b);\n vzipq_s8x2_in_place(&work_reg_a, &work_reg_b);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n input_data_0 += 8;\n input_data_1 += 8;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n }\n scratch_data_0 += height_advance;\n input_block_data += input_height_stride;\n }\n TFLITE_DCHECK_EQ(\n scratch_data_0,\n scratch_block_data + block_height * workspace_height_stride);\n }\n\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n#if defined(__aarch64__)\n PreloadInputBlock(input_block_data, function_params);\n#endif\n\n PackMacroBlockIntrinsics(input_block_data, scratch_block_data,\n function_params);\n }\n};\n\ntemplate <>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n /*max_padding=*/1> {\n static inline void PackMacroBlockIntrinsics(\n int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data, int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n constexpr uint8 kSignBit = 0x80;\n\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int input_width_micro_repeats =\n function_params->input_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int block_height = function_params->inbound_block_height;\n const int residual_width = function_params->residual_width;\n const int input_height_stride = function_params->input_height_stride;\n const int input_depth = function_params->input_depth;\n\n const int padding_left = function_params->padding_left;\n const int padding_right = function_params->padding_right;\n const int padding_top = function_params->padding_top;\n const int padding_bottom = function_params->padding_bottom;\n\n TFLITE_DCHECK_GT(depth_micro_repeats, 0);\n constexpr int kSymmetricZeroPoint = 128;\n\n const int micro_block_size = 4 * 8;\n const int depth_advance = width_overall_micro_repeats * micro_block_size;\n const int width_advance =\n micro_block_size *\n (1 - depth_micro_repeats * width_overall_micro_repeats);\n const int height_advance = workspace_height_stride -\n width_overall_micro_repeats * micro_block_size;\n const int input_depth_skip = 4 * input_depth - 8 * depth_micro_repeats;\n\n const bool leading_width_padding =\n padding_left > 0 && width_block_number == 0;\n const bool trailing_width_padding =\n padding_right > 0 &&\n width_block_number == (function_params->width_macro_count - 1);\n const bool leading_height_padding =\n padding_top > 0 && height_block_number < 0;\n const bool trailing_height_padding =\n padding_bottom > 0 &&\n height_block_number == (function_params->height_macro_count - 1);\n\n const int32 input_offset = function_params->input_offset;\n const int32 input_offset_difference = input_offset + kSymmetricZeroPoint;\n\n // Transpositions are 4x4, but doing 2 at a time is more efficient in NEON\n // code. Note the blocks of 4x4 are still interleaved down the depth.\n int8x16_t work_reg_a;\n int8x16_t work_reg_b;\n\n // Effect subtraction of zero-point = 128 by XOR of sign bit.\n const uint8x16_t sign_bit = vdupq_n_u8(kSignBit);\n\n // Work through one slice, by row, at a time.\n int8* scratch_data_0 = scratch_block_data;\n\n int copy_block_height = block_height;\n if (leading_height_padding) {\n copy_block_height -= 1;\n memset(scratch_data_0, -input_offset_difference, workspace_height_stride);\n scratch_data_0 += workspace_height_stride;\n input_block_data += input_height_stride;\n }\n if (trailing_height_padding) {\n copy_block_height -= 1;\n }\n\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n const uint8* input_data_0 = input_block_data;\n const uint8* input_data_1 = input_block_data + input_depth;\n const uint8* input_data_2 = input_block_data + 2 * input_depth;\n const uint8* input_data_3 = input_block_data + 3 * input_depth;\n\n // Traverse the width one point at a time, but the depth in (micro) blocks\n // of size 8.\n //\n // The depth and width margins, which are filled with \"zeros\", may be\n // larger than is strictly needed to calculate output. This is because the\n // conv calculation is performed across complete micro blocks.\n for (int j_width = 0; j_width < width_overall_micro_repeats; ++j_width) {\n // Figure out division of work (available input vs zero-ed).\n int adjusted_residual_width =\n j_width == (input_width_micro_repeats) ? residual_width : 4;\n\n if (trailing_width_padding &&\n j_width == (width_overall_micro_repeats - 1)) {\n adjusted_residual_width -= 1;\n }\n int start_width = 0;\n if (leading_width_padding && j_width == 0) {\n start_width = 1;\n }\n if (start_width == 0) {\n if (adjusted_residual_width == 4) {\n // Load, then zero.\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n work_reg_a = vld1q_lane_s8x8(input_data_2, work_reg_a, 1);\n work_reg_b = vld1q_lane_s8x8(input_data_3, work_reg_b, 1);\n work_reg_b = vld1q_lane_s8x8(input_data_1, work_reg_b, 0);\n input_data_1 += 8;\n work_reg_a = vld1q_lane_s8x8(input_data_0, work_reg_a, 0);\n input_data_0 += 8;\n work_reg_a = veorq_s8(work_reg_a, sign_bit);\n work_reg_b = veorq_s8(work_reg_b, sign_bit);\n\n vzipq_s8_in_place(&work_reg_a, &work_reg_b);\n vzipq_s8x2_in_place(&work_reg_a, &work_reg_b);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n scratch_data_0 += 16;\n vst1q_s8(scratch_data_0, work_reg_b);\n\n scratch_data_0 += depth_advance - 16;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n } else {\n TFLITE_DCHECK_LT(adjusted_residual_width, 4);\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n work_reg_a = vdupq_n_u8(-input_offset);\n work_reg_b = vdupq_n_u8(-input_offset);\n if (adjusted_residual_width > 0) {\n work_reg_a = vld1q_lane_s8x8(input_data_0, work_reg_a, 0);\n if (adjusted_residual_width > 1) {\n work_reg_b = vld1q_lane_s8x8(input_data_0 + input_depth,\n work_reg_b, 0);\n if (adjusted_residual_width == 3) {\n work_reg_a = vld1q_lane_s8x8(input_data_0 + 2 * input_depth,\n work_reg_a, 1);\n }\n }\n }\n work_reg_a = veorq_s8(work_reg_a, sign_bit);\n work_reg_b = veorq_s8(work_reg_b, sign_bit);\n\n vzipq_s8_in_place(&work_reg_a, &work_reg_b);\n vzipq_s8x2_in_place(&work_reg_a, &work_reg_b);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n input_data_0 += 8;\n input_data_1 += 8;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n }\n } else {\n if (adjusted_residual_width == 4) {\n // Load, then zero.\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n work_reg_a = vdupq_n_u8(-input_offset);\n work_reg_a = vld1q_lane_s8x8(input_data_2, work_reg_a, 1);\n work_reg_b = vld1q_lane_s8x8(input_data_3, work_reg_b, 1);\n work_reg_b = vld1q_lane_s8x8(input_data_1, work_reg_b, 0);\n input_data_1 += 8;\n // Skip loading first column.\n input_data_0 += 8;\n work_reg_a = veorq_s8(work_reg_a, sign_bit);\n work_reg_b = veorq_s8(work_reg_b, sign_bit);\n\n vzipq_s8_in_place(&work_reg_a, &work_reg_b);\n vzipq_s8x2_in_place(&work_reg_a, &work_reg_b);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n scratch_data_0 += 16;\n vst1q_s8(scratch_data_0, work_reg_b);\n\n scratch_data_0 += depth_advance - 16;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n } else {\n TFLITE_DCHECK_LT(adjusted_residual_width, 4);\n for (int i_depth = 0; i_depth < depth_micro_repeats; ++i_depth) {\n work_reg_a = vdupq_n_u8(-input_offset);\n // Skip loading first column.\n work_reg_b = vdupq_n_u8(-input_offset);\n if (adjusted_residual_width > 1) {\n work_reg_b =\n vld1q_lane_s8x8(input_data_0 + input_depth, work_reg_b, 0);\n if (adjusted_residual_width == 3) {\n work_reg_a = vld1q_lane_s8x8(input_data_0 + 2 * input_depth,\n work_reg_a, 1);\n }\n }\n work_reg_a = veorq_s8(work_reg_a, sign_bit);\n work_reg_b = veorq_s8(work_reg_b, sign_bit);\n\n vzipq_s8_in_place(&work_reg_a, &work_reg_b);\n vzipq_s8x2_in_place(&work_reg_a, &work_reg_b);\n\n vst1q_s8(scratch_data_0, work_reg_a);\n vst1q_s8(scratch_data_0 + 16, work_reg_b);\n\n scratch_data_0 += depth_advance;\n input_data_0 += 8;\n input_data_1 += 8;\n input_data_2 += 8;\n input_data_3 += 8;\n }\n scratch_data_0 += width_advance;\n input_data_0 += input_depth_skip;\n input_data_1 += input_depth_skip;\n input_data_2 += input_depth_skip;\n input_data_3 += input_depth_skip;\n }\n }\n }\n scratch_data_0 += height_advance;\n input_block_data += input_height_stride;\n }\n\n if (trailing_height_padding) {\n memset(scratch_data_0, -input_offset_difference, workspace_height_stride);\n scratch_data_0 += workspace_height_stride;\n }\n\n TFLITE_DCHECK_EQ(\n scratch_data_0,\n scratch_block_data + block_height * workspace_height_stride);\n }\n\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n#if defined(__aarch64__)\n PreloadInputBlock(input_block_data, function_params);\n#endif\n\n PackMacroBlockIntrinsics(height_block_number, width_block_number,\n input_block_data, scratch_block_data,\n function_params);\n }\n};\n\ntemplate <>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n /*max_padding=*/1> {\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n TFLITE_CHECK(false); // TODO(b/127805639): Not yet implemented.\n }\n};\n\ntemplate <>\nstruct PackMacroBlock<DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n /*max_padding=*/0> {\n static inline void PackMacroBlockIntrinsics(\n int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data, int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int input_width_micro_repeats =\n function_params->input_width_micro_repeats;\n const int block_height = function_params->inbound_block_height;\n const int residual_width = function_params->residual_width;\n const int input_height_stride = function_params->input_height_stride;\n\n TFLITE_DCHECK_EQ(function_params->padding_left, 0);\n TFLITE_DCHECK_EQ(function_params->padding_right, 0);\n TFLITE_DCHECK_EQ(function_params->padding_top, 0);\n TFLITE_DCHECK_EQ(function_params->padding_bottom, 0);\n\n TFLITE_DCHECK_GE(workspace_height_stride, 4 * width_overall_micro_repeats);\n\n // Work through one slice, by row, at a time.\n int8* scratch_data_base = scratch_block_data;\n\n const int copy_block_height = block_height;\n\n int adjusted_residual_width =\n input_width_micro_repeats < width_overall_micro_repeats ? residual_width\n : 4;\n\n const int copy_size =\n (width_overall_micro_repeats - 1) * 4 + adjusted_residual_width;\n\n TFLITE_DCHECK_LE(\n copy_size,\n input_height_stride - width_block_number * input_width_micro_repeats);\n // We may drop up to stride-1 of trailing input.\n TFLITE_DCHECK_GE(copy_size, input_height_stride - 1);\n\n int scratch_data_offset = 0;\n int input_block_offset = 0;\n\n constexpr uint8 kSignBit = 0x80;\n\n // Transpositions are 4x4, but doing 2 at a time is more efficient in NEON\n // code. Note the blocks of 4x4 are still interleaved down the depth.\n int8x16_t work_reg;\n int8x8_t half_work_reg;\n\n // Effect subtraction of zero-point = 128 by XOR of sign bit.\n const uint8x16_t sign_bit = vdupq_n_u8(kSignBit);\n half_work_reg = vdup_n_s8(0);\n\n if (copy_size >= 16) {\n const int copy_remaining = copy_size & 0x7;\n\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n // Work through one slice, by row, at a time.\n int8* scratch_data = scratch_data_base + scratch_data_offset;\n\n int copy_done = 0;\n\n // Main copy loop.\n for (; (copy_done + 16) <= copy_size; copy_done += 16) {\n work_reg =\n vld1q_u8(input_block_data + input_block_offset + copy_done);\n work_reg = veorq_s8(work_reg, sign_bit);\n TFLITE_DCHECK_EQ(copy_done % 16, 0);\n vst1q_s8(scratch_data + copy_done, work_reg);\n }\n\n if (copy_done + 8 <= copy_size) {\n half_work_reg =\n vld1_u8(input_block_data + input_block_offset + copy_done);\n half_work_reg = veor_s8(half_work_reg, vget_low_s8(sign_bit));\n TFLITE_DCHECK_EQ(copy_done % 8, 0);\n vst1_s8(scratch_data + copy_done, half_work_reg);\n copy_done += 8;\n }\n\n TFLITE_DCHECK_EQ(copy_remaining, copy_size - copy_done);\n // Total amount\n // = copy_size - copy_done + 4 - adjusted_residual_width\n // = width_overall_micro_repeats * 4 - start_width - copy_done.\n // Undone micro blocks\n // = width_overall_micro_repeats - (start_width + copy_done) / 4.\n\n // Conditional is (copy_remaining > 0 || trailing_width_padding).\n if (copy_done < copy_size) {\n // Employ overlapping-load strategy in order to load full register,\n // but use only part.\n // This has the advantage of resulting in zeros after shifting.\n half_work_reg =\n vld1_u8(input_block_data + input_block_offset + copy_size - 8);\n\n half_work_reg =\n vshl_u64(half_work_reg, vdup_n_s64(-8 * (8 - copy_remaining)));\n\n half_work_reg = veor_s8(half_work_reg, vget_low_s8(sign_bit));\n TFLITE_DCHECK_EQ(copy_done % 8, 0);\n vst1_s8(scratch_data + copy_done, half_work_reg);\n copy_done += 8;\n }\n\n // Trailing guard.\n vst1_s8(scratch_data + copy_done, half_work_reg);\n vst1_s8(scratch_data + copy_done + 8, half_work_reg);\n\n scratch_data_offset += workspace_height_stride;\n input_block_offset += input_height_stride;\n }\n } else if (copy_size >= 4) {\n const int copy_remaining = copy_size & 0x3;\n\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n // Work through one slice, by row, at a time.\n int8* scratch_data = scratch_data_base + scratch_data_offset;\n\n int copy_done = 0;\n\n // Main copy loop.\n for (; (copy_done + 4) <= copy_size; copy_done += 4) {\n // Important! Most compilation configurations will compile and run\n // without the reinterpret_cast. Sanitizers may fail silently on\n // lane-loading, with a obscure bug or mis-feature probably in\n // unhygienic macro expansion.\n half_work_reg = vld1_lane_s32(\n reinterpret_cast<const int32*>(input_block_data +\n input_block_offset + copy_done),\n half_work_reg, 0);\n half_work_reg = veor_s8(half_work_reg, vget_low_s8(sign_bit));\n TFLITE_DCHECK_EQ(copy_done % 4, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done),\n half_work_reg, 0);\n }\n\n TFLITE_DCHECK_EQ(copy_remaining, copy_size - copy_done);\n // Total amount\n // = copy_size - copy_done + 4 - adjusted_residual_width\n // = width_overall_micro_repeats * 4 - start_width - copy_done.\n // Undone micro blocks\n // = width_overall_micro_repeats - (start_width + copy_done) / 4.\n\n // Conditional is (copy_remaining > 0 || trailing_width_padding).\n if (copy_done < copy_size) {\n TFLITE_DCHECK_LT(copy_remaining, 4);\n // Employ overlapping-load strategy in order to load full register,\n // but use only part.\n // This has the advantage of resulting in zeros after shifting.\n half_work_reg = vld1_lane_s32(\n reinterpret_cast<const int32*>(\n input_block_data + input_block_offset + copy_size - 4),\n half_work_reg, 0);\n\n half_work_reg =\n vshl_u64(half_work_reg, vdup_n_s64(-8 * (4 - copy_remaining)));\n\n half_work_reg = veor_s8(half_work_reg, vget_low_s8(sign_bit));\n TFLITE_DCHECK_EQ(copy_done % 4, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done),\n half_work_reg, 0);\n copy_done += 4;\n }\n // Trailing guard.\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done + 4),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done + 8),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data + copy_done + 12),\n half_work_reg, 0);\n\n scratch_data_offset += workspace_height_stride;\n input_block_offset += input_height_stride;\n }\n } else {\n TFLITE_DCHECK_EQ(width_overall_micro_repeats, 1);\n\n for (int k_height = 0; k_height < copy_block_height; ++k_height) {\n for (int i = 0; i < copy_size; ++i) {\n half_work_reg = vshl_n_u64(half_work_reg, 8);\n half_work_reg = vld1_lane_s8(\n reinterpret_cast<const int8*>(\n input_block_data + input_block_offset + copy_size - 1 - i),\n half_work_reg, 0);\n }\n\n half_work_reg = veor_s8(half_work_reg, vget_low_s8(sign_bit));\n TFLITE_DCHECK_EQ(scratch_data_offset % 4, 0);\n vst1_lane_s32(\n reinterpret_cast<int32*>(scratch_data_base + scratch_data_offset),\n half_work_reg, 0);\n\n // Trailing guard.\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data_base +\n scratch_data_offset + 4),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data_base +\n scratch_data_offset + 8),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data_base +\n scratch_data_offset + 12),\n half_work_reg, 0);\n vst1_lane_s32(reinterpret_cast<int32*>(scratch_data_base +\n scratch_data_offset + 16),\n half_work_reg, 0);\n\n scratch_data_offset += workspace_height_stride;\n input_block_offset += input_height_stride;\n }\n }\n\n scratch_data_base += copy_block_height * workspace_height_stride;\n\n TFLITE_DCHECK_EQ(\n scratch_data_base,\n scratch_block_data + block_height * workspace_height_stride);\n }\n\n static inline void Run(int32 height_block_number, int32 width_block_number,\n const uint8* input_block_data,\n int8* scratch_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n#if defined(__aarch64__)\n PreloadInputBlock(input_block_data, function_params);\n#endif\n\n PackMacroBlockIntrinsics(height_block_number, width_block_number,\n input_block_data, scratch_block_data,\n function_params);\n }\n};\n\n#endif // ARM NEON\n\n// Apply filter to macro block of input data and store results.\n//\n// Requirement: depth_micro_repeats > 0 || residual_depth > 0.\ntemplate <int32 stride>\nstruct KernelMacroBlock<DepthwiseConvImplementation::kUseCModel3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n stride> {\n // Construct a width-shifted combination of two input sub-blocks, effectively\n // concatenating them.\n //\n // The filter is applied using sub-blocks. These are in the needed form for\n // the first (width) offset. For subsequent offsets, the filter is applied to\n // shifted and combined data. The concatentation and shifting herein is fairly\n // straightforward, but in the optimized code is an area of creativity in\n // design because NEON instructions do not directly support the required\n // between-register permutation.\n //\n // In NEON optimized code, input data is grouped in 4-byte blocks. In order to\n // move along the width for each output point calculation, data is shifted, in\n // essence between two such blocks.\n //\n // selected_data has format height 3, depth 4, width 4.\n //\n // When the micro block is trailing (the last across the macro-block width),\n // it would be illegal to load the right (next) block, and the no_right_block\n // indicates this scenario.\n static inline void ConcatenateInputSubBlocks(int offset, int sub_block,\n int workspace_height_stride,\n int width_micro_stride,\n bool no_right_block,\n const int8* input_block,\n int8 selected_data[3][4][4]) {\n TFLITE_DCHECK_GE(offset, 0);\n TFLITE_DCHECK_LT(offset, 4);\n\n // The input banks have same format as selected_data.\n int8 left_bank[3][4][4];\n int8 right_bank[3][4][4];\n\n // Work through one slice, by row, at a time.\n for (int k_height = 0; k_height < 3; ++k_height) {\n // Simulate demangling of mangled storage arrangement.\n const int8* left_input_block =\n &input_block[k_height * workspace_height_stride + sub_block * 2 * 8];\n memcpy(left_bank[k_height][0], left_input_block, 16);\n if (no_right_block) {\n memset(right_bank[k_height][0], 0, 16);\n } else {\n const int8* right_input_block =\n &input_block[k_height * workspace_height_stride +\n sub_block * 2 * 8 + width_micro_stride];\n memcpy(right_bank[k_height][0], right_input_block, 16);\n }\n for (int depth_index = 0; depth_index < 4; ++depth_index) {\n memcpy(selected_data[k_height][depth_index],\n &left_bank[k_height][depth_index][offset], 4 - offset);\n memcpy(&selected_data[k_height][depth_index][4 - offset],\n right_bank[k_height][depth_index], offset);\n }\n }\n }\n\n // Straight implementation of 3x3 filter within sub-micro block.\n static inline void Calculate3x3FilterOutput(\n const DepthwiseConvDotProdParams& params, int sub_block,\n const int8 selected_data[3][4][4], const int8 filter_bank[3][2][4][4],\n const int32* bias_data, uint8 output_values[4]) {\n const int32 output_activation_min = params.quantized_activation_min;\n const int32 output_activation_max = params.quantized_activation_max;\n const int32 output_multiplier = params.output_multiplier;\n const int32 output_shift = params.output_shift;\n const int32 output_offset = params.output_offset;\n for (int d = 0; d < 4; ++d) {\n int32 acc = 0;\n for (int y = 0; y < 3; ++y) {\n for (int x = 0; x < 4; ++x) {\n int32 input_val = selected_data[y][d][x];\n int32 filter_val = filter_bank[y][sub_block][d][x];\n acc += filter_val * input_val;\n }\n }\n acc += bias_data[d];\n acc = reference_ops::depthwise_conv::DepthwiseConvRound<\n DepthwiseConvOutputRounding::kUpward>(acc, output_multiplier,\n output_shift);\n acc += output_offset;\n acc = std::max(acc, output_activation_min);\n acc = std::min(acc, output_activation_max);\n output_values[d] = static_cast<uint8>(acc);\n }\n }\n\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int input_width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int output_width_micro_repeats =\n function_params->output_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int depth = function_params->input_depth;\n const int stride_val = function_params->stride;\n const int four_over_stride = function_params->four_over_stride;\n\n const int output_width_overall_micro_repeats =\n function_params->output_width_overall_micro_repeats;\n const int block_height = function_params->outbound_block_height;\n const int residual_width = function_params->output_residual_width;\n const int output_height_stride = function_params->output_height_stride;\n constexpr int bias_increment = 4;\n TFLITE_DCHECK_EQ(function_params->bias_increment, bias_increment);\n\n TFLITE_DCHECK(depth_micro_repeats > 0);\n const int width_micro_stride = 4 * 8;\n const int depth_micro_stride =\n width_micro_stride * input_width_overall_micro_repeats;\n\n constexpr int shuffled_filter_increment = 2 * 3 * 4 * 4;\n\n // Simulate NEON-register transposition of subset of filter.\n int8 filter_bank[3][2][4][4]; // Height 3, sub-block, depth 4, width 4.\n // Simulate NEON-register input data concatenation + sub-selection.\n int8 sub_selected_input_data[3][4][4]; // Height 3, depth 4, width 4.\n uint8 output_values[4]; // Depth 4.\n\n // The outer 3 loops go through all the micro blocks in a macro block, and\n // separately treat the two sub-blocks within each micro block.\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n memcpy(filter_bank[0][0][0],\n filter_workspace + j_depth * shuffled_filter_increment,\n shuffled_filter_increment);\n\n for (int s = 0; s < 2; ++s) {\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const int8* scratch_data =\n scratch_block_data +\n workspace_height_stride * k_height * stride_val +\n depth_micro_stride * j_depth;\n uint8* output_data =\n output_block_data + output_height_stride * k_height + 8 * j_depth;\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n const int output_width = i_width == output_width_micro_repeats\n ? residual_width\n : four_over_stride;\n const bool no_right_block = (output_width - 1) * stride_val < 2;\n TFLITE_DCHECK_LE(output_width * stride_val, 4);\n const int8* input_data =\n scratch_data + width_micro_stride * i_width;\n // Iterate over input width shifts within sub-micro blocks.\n for (int x = 0; x < output_width; ++x) {\n ConcatenateInputSubBlocks(x * stride_val, s,\n workspace_height_stride,\n width_micro_stride, no_right_block,\n input_data, sub_selected_input_data);\n Calculate3x3FilterOutput(\n *function_params, s, sub_selected_input_data, filter_bank,\n bias_data + (2 * j_depth + s) * bias_increment,\n output_values);\n for (int d = 0; d < 4; ++d) {\n output_data[depth * (four_over_stride * i_width + x) + 4 * s +\n d] = output_values[d];\n }\n }\n }\n }\n }\n }\n }\n};\n\n// Apply filter to macro block of input data and store results.\n//\n// Parameters for repeats and residual sizes are in terms of outputs.\n//\n// Requirement: depth_micro_repeats > 0 || residual_depth > 0.\ntemplate <int32 stride>\nstruct KernelMacroBlock<DepthwiseConvImplementation::kUseCModel3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n stride> {\n // Construct a width-shifted combination of two input sub-blocks, effectively\n // concatenating them.\n //\n // The filter is applied using sub-blocks. These are in the needed form for\n // the first (width) offset. For subsequent offsets, the filter is applied to\n // shifted and combined data. The concatentation and shifting herein is fairly\n // straightforward, but in the optimized code is an area of creativity in\n // design because NEON instructions do not directly support the required\n // between-register permutation.\n //\n // In NEON optimized code, input data is grouped in 4-byte blocks. In order to\n // move along the width for each output point calculation, data is shifted, in\n // essence between two such blocks.\n //\n // selected_data has format height 3, width 4.\n //\n // When the micro block is trailing (the last across the macro-block width),\n // it would be illegal to load the right (next) block, and the no_right_block\n // indicates this scenario.\n static inline void ConcatenateInputSubBlocks(int offset,\n int workspace_height_stride,\n bool no_right_block,\n const int8* input_block,\n int8 selected_data[3][4]) {\n TFLITE_DCHECK_GE(offset, 0);\n TFLITE_DCHECK_LT(offset, 4);\n if (no_right_block) {\n for (int k_height = 0; k_height < 3; ++k_height) {\n memcpy(selected_data[k_height],\n &input_block[k_height * workspace_height_stride + offset],\n 4 - offset);\n }\n } else {\n for (int k_height = 0; k_height < 3; ++k_height) {\n memcpy(selected_data[k_height],\n &input_block[k_height * workspace_height_stride + offset], 4);\n }\n }\n }\n\n // Straight implementation of 3x3 filter within sub-micro block.\n static inline void Calculate3x3FilterOutput(\n const DepthwiseConvDotProdParams& function_params, int sub_block,\n const int8 selected_data[3][4], const int8 filter_bank[3][2][4][4],\n const int32* bias_data, uint8 output_values[4]) {\n const int32 output_activation_min =\n function_params.quantized_activation_min;\n const int32 output_activation_max =\n function_params.quantized_activation_max;\n const int32 output_multiplier = function_params.output_multiplier;\n const int32 output_shift = function_params.output_shift;\n const int32 output_offset = function_params.output_offset;\n for (int d = 0; d < 4; ++d) {\n int32 acc = 0;\n for (int y = 0; y < 3; ++y) {\n for (int x = 0; x < 4; ++x) {\n int32 input_val = selected_data[y][x];\n int32 filter_val = filter_bank[y][sub_block][d][x];\n acc += filter_val * input_val;\n }\n }\n acc += bias_data[d];\n acc = reference_ops::depthwise_conv::DepthwiseConvRound<\n DepthwiseConvOutputRounding::kUpward>(acc, output_multiplier,\n output_shift);\n acc += output_offset;\n acc = std::max(acc, output_activation_min);\n acc = std::min(acc, output_activation_max);\n output_values[d] = static_cast<uint8>(acc);\n }\n }\n\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int output_width_micro_repeats =\n function_params->output_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int depth = function_params->output_depth;\n const int stride_val = function_params->stride;\n const int four_over_stride = function_params->four_over_stride;\n\n const int workspace_width_micro_repeats =\n function_params->workspace_width_micro_repeats;\n const int output_width_overall_micro_repeats =\n function_params->output_width_overall_micro_repeats;\n const int block_height = function_params->outbound_block_height;\n const int residual_width = function_params->output_residual_width;\n const int output_height_stride = function_params->output_height_stride;\n constexpr int bias_increment = 4;\n TFLITE_DCHECK_EQ(function_params->bias_increment, bias_increment);\n\n TFLITE_DCHECK(depth_micro_repeats > 0);\n\n constexpr int shuffled_filter_increment = 2 * 3 * 4 * 4;\n\n // Simulate NEON-register transposition of subset of filter.\n int8 filter_bank[3][2][4][4]; // Height 3, sub-block, depth 4, width 4.\n // Simulate NEON-register input data concatenation + sub-selection.\n int8 sub_selected_input_data[3][4]; // Height 3, depth 4, width 4.\n uint8 output_values[4]; // Depth 4.\n\n // The outer 3 loops go through all the micro blocks in a macro block, and\n // separately treat the two sub-blocks within each micro block.\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n memcpy(filter_bank[0][0][0],\n filter_workspace + j_depth * shuffled_filter_increment,\n shuffled_filter_increment);\n\n for (int s = 0; s < 2; ++s) {\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const int8* scratch_data =\n scratch_block_data +\n workspace_height_stride * k_height * stride_val;\n uint8* output_data =\n output_block_data + output_height_stride * k_height + 8 * j_depth;\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n const int output_width = i_width == output_width_micro_repeats\n ? residual_width\n : four_over_stride;\n const bool no_right_block = i_width == output_width_micro_repeats &&\n output_width_overall_micro_repeats ==\n workspace_width_micro_repeats;\n TFLITE_DCHECK_LE(output_width * stride_val, 4);\n const int8* input_data = scratch_data + 4 * i_width;\n // Iterate over input width shifts within 4x4 blocks.\n for (int x = 0; x < output_width; ++x) {\n ConcatenateInputSubBlocks(x * stride_val, workspace_height_stride,\n no_right_block, input_data,\n sub_selected_input_data);\n Calculate3x3FilterOutput(\n *function_params, s, sub_selected_input_data, filter_bank,\n bias_data + (2 * j_depth + s) * bias_increment,\n output_values);\n for (int d = 0; d < 4; ++d) {\n output_data[depth * (four_over_stride * i_width + x) + 4 * s +\n d] = output_values[d];\n }\n }\n }\n }\n }\n }\n }\n};\n\n#if defined(USE_NEON)\ntemplate <>\nstruct KernelMacroBlock<\n DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n /*stride=*/1> {\n // Apply filter to macro block of input data and store results.\n //\n // Parameters for repeats and residual sizes are in terms of outputs.\n //\n // Requirement: depth_micro_repeats > 0 || residual_depth > 0.\n static inline void KernelMacroBlockIntrinsics(\n const int8* scratch_block_data, const int8* filter_workspace,\n const int32* bias_data, uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int input_width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int output_width_micro_repeats =\n function_params->output_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int depth = function_params->input_depth;\n\n const int output_width_overall_micro_repeats =\n function_params->output_width_overall_micro_repeats;\n const int block_height = function_params->outbound_block_height;\n const int residual_width = function_params->output_residual_width;\n const int output_height_stride = function_params->output_height_stride;\n const int bias_increment = function_params->bias_increment;\n\n TFLITE_DCHECK(depth_micro_repeats > 0);\n const int width_micro_stride = 4 * 8;\n const int depth_micro_stride =\n width_micro_stride * input_width_overall_micro_repeats;\n\n const int32 output_activation_min =\n function_params->quantized_activation_min;\n const int32 output_activation_max =\n function_params->quantized_activation_max;\n const int32 output_multiplier = function_params->output_multiplier;\n const int32 output_shift = function_params->output_shift;\n const int32 output_offset = function_params->output_offset;\n TFLITE_DCHECK_GE(output_activation_min, 0);\n TFLITE_DCHECK_LT(output_activation_min, 256);\n TFLITE_DCHECK_GE(output_activation_max, 0);\n TFLITE_DCHECK_LT(output_activation_max, 256);\n TFLITE_DCHECK_GE(output_offset, -32878);\n TFLITE_DCHECK_LT(output_offset, 32768);\n\n const int16x8_t output_offset_vec =\n vdupq_n_s16(static_cast<int16>(output_offset));\n const uint8x16_t output_activation_min_vec =\n vdupq_n_u8(static_cast<uint8>(output_activation_min));\n const uint8x16_t output_activation_max_vec =\n vdupq_n_u8(static_cast<uint8>(output_activation_max));\n\n const int8* input_data_depthwise = scratch_block_data;\n uint8* output_data_depthwise = output_block_data;\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n // Simulate NEON-register transposition of subset of filter.\n int8x16_t filter_reg_0_a;\n int8x16_t filter_reg_0_b;\n int8x16_t filter_reg_1_a;\n int8x16_t filter_reg_1_b;\n int8x16_t filter_reg_2_a;\n int8x16_t filter_reg_2_b;\n int8x16_t filter_reg_0_a_shifted;\n int8x16_t filter_reg_1_a_shifted;\n int8x16_t filter_reg_2_a_shifted;\n\n filter_reg_0_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_0_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_1_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_1_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_2_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_2_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n\n filter_reg_0_a_shifted = vshlq_n_u32(filter_reg_0_a, 8);\n filter_reg_1_a_shifted = vshlq_n_u32(filter_reg_1_a, 8);\n filter_reg_2_a_shifted = vshlq_n_u32(filter_reg_2_a, 8);\n\n if (block_height == 4) {\n for (int s = 0; s < 2; ++s) {\n // Work through one slice, by row, at a time.\n const int8* input_data_base = input_data_depthwise + 2 * 8 * s;\n uint8* output_data_base = output_data_depthwise + 4 * s;\n\n const int8* next_input_data = input_data_base;\n uint8* output_data = output_data_base;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n bias_data += bias_increment;\n\n // Load first sub-micro block of data into operational banks.\n int8x16_t left_bank_0_reg = vld1q_s8(next_input_data);\n int8x16_t left_bank_1_reg =\n vld1q_s8(next_input_data + workspace_height_stride);\n int8x16_t left_bank_2_reg =\n vld1q_s8(next_input_data + 2 * workspace_height_stride);\n int8x16_t left_bank_3_reg =\n vld1q_s8(next_input_data + 3 * workspace_height_stride);\n int8x16_t left_bank_4_reg =\n vld1q_s8(next_input_data + 4 * workspace_height_stride);\n int8x16_t left_bank_5_reg =\n vld1q_s8(next_input_data + 5 * workspace_height_stride);\n\n int32x4_t acc0;\n int32x4_t acc1;\n int32x4_t acc2;\n int32x4_t acc3;\n\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a, left_bank_2_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a, left_bank_3_reg);\n\n for (int i_width = 0; i_width < output_width_micro_repeats;\n ++i_width) {\n next_input_data += width_micro_stride;\n\n // Iterate over input width shifts within 4x4 blocks.\n {\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_1_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_2_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_1_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_2_a, left_bank_5_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n output_data += depth;\n }\n\n // Load next sub-micro block of data.\n int8x16_t right_bank_0_reg;\n int8x16_t right_bank_1_reg;\n int8x16_t right_bank_2_reg;\n int8x16_t right_bank_3_reg;\n int8x16_t right_bank_4_reg;\n int8x16_t right_bank_5_reg;\n // Logic: (i_width == output_width_micro_repeats) &&\n // ((residual_width - 1) * stride_val < 2)\n const bool no_right_block =\n i_width == output_width_micro_repeats && residual_width < 3;\n\n if (no_right_block) {\n // Only needed for santizer checks.\n right_bank_0_reg = vdupq_n_s8(0);\n right_bank_1_reg = vdupq_n_s8(0);\n right_bank_2_reg = vdupq_n_s8(0);\n right_bank_3_reg = vdupq_n_s8(0);\n right_bank_4_reg = vdupq_n_s8(0);\n right_bank_5_reg = vdupq_n_s8(0);\n } else {\n right_bank_0_reg = vld1q_s8(next_input_data);\n right_bank_1_reg =\n vld1q_s8(next_input_data + workspace_height_stride);\n right_bank_2_reg =\n vld1q_s8(next_input_data + 2 * workspace_height_stride);\n right_bank_3_reg =\n vld1q_s8(next_input_data + 3 * workspace_height_stride);\n right_bank_4_reg =\n vld1q_s8(next_input_data + 4 * workspace_height_stride);\n right_bank_5_reg =\n vld1q_s8(next_input_data + 5 * workspace_height_stride);\n }\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a_shifted, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a_shifted, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a_shifted, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a_shifted, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a_shifted, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a_shifted, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a_shifted, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_1_a_shifted, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_2_a_shifted, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a_shifted, left_bank_3_reg);\n acc3 = vdotq_s32(acc3, filter_reg_1_a_shifted, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_2_a_shifted, left_bank_5_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n left_bank_0_reg = vrev32q_u16(left_bank_0_reg);\n left_bank_1_reg = vrev32q_u16(left_bank_1_reg);\n left_bank_2_reg = vrev32q_u16(left_bank_2_reg);\n left_bank_3_reg = vrev32q_u16(left_bank_3_reg);\n left_bank_4_reg = vrev32q_u16(left_bank_4_reg);\n left_bank_5_reg = vrev32q_u16(left_bank_5_reg);\n vtrn1_s8x2_in_place(&left_bank_0_reg, &right_bank_0_reg);\n vtrn1_s8x2_in_place(&left_bank_1_reg, &right_bank_1_reg);\n vtrn1_s8x2_in_place(&left_bank_2_reg, &right_bank_2_reg);\n vtrn1_s8x2_in_place(&left_bank_3_reg, &right_bank_3_reg);\n vtrn1_s8x2_in_place(&left_bank_4_reg, &right_bank_4_reg);\n vtrn1_s8x2_in_place(&left_bank_5_reg, &right_bank_5_reg);\n\n output_data += depth;\n }\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_1_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_2_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a, left_bank_3_reg);\n acc3 = vdotq_s32(acc3, filter_reg_1_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_2_a, left_bank_5_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n output_data += depth;\n }\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a_shifted, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a_shifted, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a_shifted, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a_shifted, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a_shifted, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a_shifted, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a_shifted, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_1_a_shifted, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_2_a_shifted, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a_shifted, left_bank_3_reg);\n acc3 = vdotq_s32(acc3, filter_reg_1_a_shifted, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_2_a_shifted, left_bank_5_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n left_bank_0_reg = right_bank_0_reg;\n left_bank_1_reg = right_bank_1_reg;\n left_bank_2_reg = right_bank_2_reg;\n left_bank_3_reg = right_bank_3_reg;\n left_bank_4_reg = right_bank_4_reg;\n left_bank_5_reg = right_bank_5_reg;\n\n output_data += depth;\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a, left_bank_2_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a, left_bank_3_reg);\n }\n }\n\n if (residual_width > 0) {\n next_input_data += width_micro_stride;\n const int output_width = residual_width;\n\n // Load next sub-micro block of data.\n int8x16_t right_bank_0_reg;\n int8x16_t right_bank_1_reg;\n int8x16_t right_bank_2_reg;\n int8x16_t right_bank_3_reg;\n int8x16_t right_bank_4_reg;\n int8x16_t right_bank_5_reg;\n // Logic: (output_width - 1) * stride_val < 2.\n const bool no_right_block = output_width < 3;\n\n if (no_right_block) {\n // Only needed for santizer checks.\n right_bank_0_reg = vdupq_n_s8(0);\n right_bank_1_reg = vdupq_n_s8(0);\n right_bank_2_reg = vdupq_n_s8(0);\n right_bank_3_reg = vdupq_n_s8(0);\n right_bank_4_reg = vdupq_n_s8(0);\n right_bank_5_reg = vdupq_n_s8(0);\n } else {\n right_bank_0_reg = vld1q_s8(next_input_data);\n right_bank_1_reg =\n vld1q_s8(next_input_data + workspace_height_stride);\n right_bank_2_reg =\n vld1q_s8(next_input_data + 2 * workspace_height_stride);\n right_bank_3_reg =\n vld1q_s8(next_input_data + 3 * workspace_height_stride);\n right_bank_4_reg =\n vld1q_s8(next_input_data + 4 * workspace_height_stride);\n right_bank_5_reg =\n vld1q_s8(next_input_data + 5 * workspace_height_stride);\n }\n\n // Iterate over input width shifts within 4x4 blocks.\n for (int x = 0; x < output_width; ++x) {\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a, left_bank_1_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_1_a, left_bank_3_reg);\n acc2 = vdotq_s32(acc2, filter_reg_2_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_1_a, left_bank_4_reg);\n acc3 = vdotq_s32(acc3, filter_reg_2_a, left_bank_5_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n biregister_rotate_8(&left_bank_0_reg, &right_bank_0_reg);\n biregister_rotate_8(&left_bank_1_reg, &right_bank_1_reg);\n biregister_rotate_8(&left_bank_2_reg, &right_bank_2_reg);\n biregister_rotate_8(&left_bank_3_reg, &right_bank_3_reg);\n biregister_rotate_8(&left_bank_4_reg, &right_bank_4_reg);\n biregister_rotate_8(&left_bank_5_reg, &right_bank_5_reg);\n\n output_data += depth;\n\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_2_reg);\n acc2 = vdotq_s32(acc2, filter_reg_0_a, left_bank_2_reg);\n acc3 = vdotq_s32(acc3, filter_reg_0_a, left_bank_3_reg);\n }\n }\n input_data_base += 4 * workspace_height_stride;\n output_data_base += 4 * output_height_stride;\n\n // Move to next sub-block: advance to second set of filters, to new\n // bias.\n filter_reg_0_a = filter_reg_0_b;\n filter_reg_1_a = filter_reg_1_b;\n filter_reg_2_a = filter_reg_2_b;\n filter_reg_0_a_shifted = vshlq_n_u32(filter_reg_0_a, 8);\n filter_reg_1_a_shifted = vshlq_n_u32(filter_reg_1_a, 8);\n filter_reg_2_a_shifted = vshlq_n_u32(filter_reg_2_a, 8);\n }\n } else {\n for (int s = 0; s < 2; ++s) {\n // Work through one slice, by row, at a time.\n const int8* input_data_base = input_data_depthwise + 2 * 8 * s;\n uint8* output_data_base = output_data_depthwise + 4 * s;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n bias_data += bias_increment;\n\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const int8* next_input_data = input_data_base;\n uint8* output_data = output_data_base;\n\n // Load first sub-micro block of data into operational banks.\n int8x16_t left_bank_0_reg = vld1q_s8(next_input_data);\n int8x16_t left_bank_1_reg =\n vld1q_s8(next_input_data + workspace_height_stride);\n int8x16_t left_bank_2_reg =\n vld1q_s8(next_input_data + 2 * workspace_height_stride);\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n next_input_data += width_micro_stride;\n const int output_width =\n i_width == output_width_micro_repeats ? residual_width : 4;\n\n // Load next sub-micro block of data.\n int8x16_t right_bank_0_reg;\n int8x16_t right_bank_1_reg;\n int8x16_t right_bank_2_reg;\n // Logic: (output_width - 1) * stride_val < 2.\n const bool no_right_block = output_width < 3;\n\n if (no_right_block) {\n // Only needed for santizer checks.\n right_bank_0_reg = vdupq_n_s8(0);\n right_bank_1_reg = vdupq_n_s8(0);\n right_bank_2_reg = vdupq_n_s8(0);\n } else {\n right_bank_0_reg = vld1q_s8(next_input_data);\n right_bank_1_reg =\n vld1q_s8(next_input_data + workspace_height_stride);\n right_bank_2_reg =\n vld1q_s8(next_input_data + 2 * workspace_height_stride);\n }\n // Load next sub-micro block of data.\n\n // Iterate over input width shifts within 4x4 blocks.\n for (int x = 0; x < output_width; ++x) {\n int32x4_t acc = adjusted_bias_data;\n acc = vdotq_s32(acc, filter_reg_0_a, left_bank_0_reg);\n acc = vdotq_s32(acc, filter_reg_1_a, left_bank_1_reg);\n acc = vdotq_s32(acc, filter_reg_2_a, left_bank_2_reg);\n\n // Fixed-point multiplication.\n acc = vqrdmulhq_n_s32(acc, output_multiplier);\n acc = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc, -output_shift);\n // Add the output offset.\n // Note that we need to fill the top half with vcombine, but can\n // drop the instruction in ASM code.\n int16x8_t acc_s16_0_0 =\n vcombine_s16(vqmovn_s32(acc), vqmovn_s32(acc));\n acc_s16_0_0 = vqaddq_s16(acc_s16_0_0, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8_0_0 = vqmovun_s16(acc_s16_0_0);\n acc_u8_0_0 =\n vmax_u8(acc_u8_0_0, vget_low_u8(output_activation_min_vec));\n acc_u8_0_0 =\n vmin_u8(acc_u8_0_0, vget_low_u8(output_activation_max_vec));\n\n vst1_lane_u8x4(output_data, acc_u8_0_0, 0);\n\n biregister_rotate_8(&left_bank_0_reg, &right_bank_0_reg);\n biregister_rotate_8(&left_bank_1_reg, &right_bank_1_reg);\n biregister_rotate_8(&left_bank_2_reg, &right_bank_2_reg);\n\n output_data += depth;\n }\n }\n input_data_base += workspace_height_stride;\n output_data_base += output_height_stride;\n }\n\n // Move to next sub-block: advance to second set of filters.\n filter_reg_0_a = filter_reg_0_b;\n filter_reg_1_a = filter_reg_1_b;\n filter_reg_2_a = filter_reg_2_b;\n }\n }\n input_data_depthwise += depth_micro_stride;\n output_data_depthwise += 8;\n }\n } // NOLINT(readability/fn_size) Manually unrolled.\n\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n KernelMacroBlockIntrinsics(scratch_block_data, filter_workspace, bias_data,\n output_block_data, function_params);\n }\n};\n\ntemplate <>\nstruct KernelMacroBlock<\n DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kNoMultiplication,\n /*stride=*/2> {\n static inline void KernelMacroBlockIntrinsics(\n const int8* scratch_block_data, const int8* filter_workspace,\n const int32* bias_data, uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int input_width_overall_micro_repeats =\n function_params->input_width_overall_micro_repeats;\n const int output_width_micro_repeats =\n function_params->output_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int depth = function_params->input_depth;\n const int stride_val = function_params->stride;\n const int four_over_stride = function_params->four_over_stride;\n\n const int workspace_width_micro_repeats =\n function_params->workspace_width_micro_repeats;\n const int output_width_overall_micro_repeats =\n function_params->output_width_overall_micro_repeats;\n const int block_height = function_params->outbound_block_height;\n const int residual_width = function_params->output_residual_width;\n const int output_height_stride = function_params->output_height_stride;\n const int bias_increment = function_params->bias_increment;\n\n TFLITE_DCHECK(depth_micro_repeats > 0);\n const int width_micro_stride = 4 * 8;\n const int depth_micro_stride =\n width_micro_stride * input_width_overall_micro_repeats;\n\n const int32 output_activation_min =\n function_params->quantized_activation_min;\n const int32 output_activation_max =\n function_params->quantized_activation_max;\n const int32 output_multiplier = function_params->output_multiplier;\n const int32 output_shift = function_params->output_shift;\n const int32 output_offset = function_params->output_offset;\n TFLITE_DCHECK_GE(output_activation_min, 0);\n TFLITE_DCHECK_LT(output_activation_min, 256);\n TFLITE_DCHECK_GE(output_activation_max, 0);\n TFLITE_DCHECK_LT(output_activation_max, 256);\n TFLITE_DCHECK_GE(output_offset, -32878);\n TFLITE_DCHECK_LT(output_offset, 32768);\n\n // This version only does min/max on 64 bits.\n const int16x8_t output_offset_vec =\n vdupq_n_s16(static_cast<int16>(output_offset));\n const uint8x8_t output_activation_min_vec =\n vdup_n_u8(static_cast<uint8>(output_activation_min));\n const uint8x8_t output_activation_max_vec =\n vdup_n_u8(static_cast<uint8>(output_activation_max));\n\n constexpr int shuffled_filter_increment = 2 * 3 * 4 * 4;\n\n TFLITE_DCHECK_EQ(stride_val, 2);\n TFLITE_DCHECK_LE(block_height, 2);\n\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n const int8* filter_block =\n filter_workspace + shuffled_filter_increment * j_depth;\n\n if (block_height == 2) {\n for (int s = 0; s < 2; ++s) {\n // Simulate NEON-register transposition of subset of filter.\n int8x16_t filter_reg_0_a;\n int8x16_t filter_reg_1_a;\n int8x16_t filter_reg_2_a;\n\n filter_reg_0_a = vld1q_s8(filter_block + s * 16);\n filter_reg_1_a = vld1q_s8(filter_block + s * 16 + 32);\n filter_reg_2_a = vld1q_s8(filter_block + s * 16 + 64);\n\n const int8* scratch_data =\n scratch_block_data + depth_micro_stride * j_depth;\n uint8* output_data = output_block_data + 8 * j_depth;\n const int8* input_data_0 = scratch_data + s * 2 * 8;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n\n // Load first sub-micro block of data into operational banks.\n int8x16_t left_bank_0_reg = vld1q_s8(input_data_0);\n int8x16_t left_bank_1_reg =\n vld1q_s8(input_data_0 + workspace_height_stride);\n int8x16_t left_bank_2_reg =\n vld1q_s8(input_data_0 + 2 * workspace_height_stride);\n int8x16_t left_bank_3_reg =\n vld1q_s8(input_data_0 + 3 * workspace_height_stride);\n int8x16_t left_bank_4_reg =\n vld1q_s8(input_data_0 + 4 * workspace_height_stride);\n\n int8x16_t right_bank_0_reg;\n int8x16_t right_bank_1_reg;\n int8x16_t right_bank_2_reg;\n int8x16_t right_bank_3_reg;\n int8x16_t right_bank_4_reg;\n\n int32x4_t acc0;\n int32x4_t acc1;\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n const int output_width = i_width == output_width_micro_repeats\n ? residual_width\n : four_over_stride;\n TFLITE_DCHECK_LE(output_width * stride_val, 4);\n const int8* input_data =\n input_data_0 + width_micro_stride * i_width;\n const bool no_right_block = i_width == output_width_micro_repeats &&\n output_width_overall_micro_repeats ==\n workspace_width_micro_repeats;\n\n if (!no_right_block) {\n // Load next sub-micro block of data.\n right_bank_0_reg = vld1q_s8(input_data + width_micro_stride);\n right_bank_1_reg = vld1q_s8(input_data + width_micro_stride +\n workspace_height_stride);\n right_bank_2_reg = vld1q_s8(input_data + width_micro_stride +\n 2 * workspace_height_stride);\n right_bank_3_reg = vld1q_s8(input_data + width_micro_stride +\n 3 * workspace_height_stride);\n right_bank_4_reg = vld1q_s8(input_data + width_micro_stride +\n 4 * workspace_height_stride);\n }\n\n uint8* output_data_base = output_data + depth * 2 * i_width + 4 * s;\n\n // Iterate over input width shifts within 4x4 blocks.\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_3_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a, left_bank_4_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8 = vqmovun_s16(acc_s16_0_1);\n acc_u8 = vmax_u8(acc_u8, output_activation_min_vec);\n acc_u8 = vmin_u8(acc_u8, output_activation_max_vec);\n\n vst1_lane_u8x4(output_data_base, acc_u8, 0);\n vst1_lane_u8x4(output_data_base + output_height_stride, acc_u8,\n 1);\n\n left_bank_0_reg = vrev32q_u16(left_bank_0_reg);\n left_bank_1_reg = vrev32q_u16(left_bank_1_reg);\n left_bank_2_reg = vrev32q_u16(left_bank_2_reg);\n left_bank_3_reg = vrev32q_u16(left_bank_3_reg);\n left_bank_4_reg = vrev32q_u16(left_bank_4_reg);\n vtrn1_s8x2_in_place(&left_bank_0_reg, &right_bank_0_reg);\n vtrn1_s8x2_in_place(&left_bank_1_reg, &right_bank_1_reg);\n vtrn1_s8x2_in_place(&left_bank_2_reg, &right_bank_2_reg);\n vtrn1_s8x2_in_place(&left_bank_3_reg, &right_bank_3_reg);\n vtrn1_s8x2_in_place(&left_bank_4_reg, &right_bank_4_reg);\n }\n\n if (output_width > 1) {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_0_a, left_bank_2_reg);\n acc1 = vdotq_s32(acc1, filter_reg_1_a, left_bank_3_reg);\n acc1 = vdotq_s32(acc1, filter_reg_2_a, left_bank_4_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8 = vqmovun_s16(acc_s16_0_1);\n acc_u8 = vmax_u8(acc_u8, output_activation_min_vec);\n acc_u8 = vmin_u8(acc_u8, output_activation_max_vec);\n\n vst1_lane_u8x4(output_data_base + depth, acc_u8, 0);\n vst1_lane_u8x4(output_data_base + depth + output_height_stride,\n acc_u8, 1);\n\n left_bank_0_reg = right_bank_0_reg;\n left_bank_1_reg = right_bank_1_reg;\n left_bank_2_reg = right_bank_2_reg;\n left_bank_3_reg = right_bank_3_reg;\n left_bank_4_reg = right_bank_4_reg;\n }\n }\n bias_data += bias_increment;\n }\n } else {\n for (int s = 0; s < 2; ++s) {\n // Simulate NEON-register transposition of subset of filter.\n int8x16_t filter_reg_0_a;\n int8x16_t filter_reg_1_a;\n int8x16_t filter_reg_2_a;\n\n filter_reg_0_a = vld1q_s8(filter_block + s * 16);\n filter_reg_1_a = vld1q_s8(filter_block + s * 16 + 32);\n filter_reg_2_a = vld1q_s8(filter_block + s * 16 + 64);\n\n const int8* scratch_data =\n scratch_block_data + depth_micro_stride * j_depth;\n uint8* output_data = output_block_data + 8 * j_depth;\n const int8* input_data_0 = scratch_data + s * 2 * 8;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n\n // Load first sub-micro block of data into operational banks.\n int8x16_t left_bank_0_reg = vld1q_s8(input_data_0);\n int8x16_t left_bank_1_reg =\n vld1q_s8(input_data_0 + workspace_height_stride);\n int8x16_t left_bank_2_reg =\n vld1q_s8(input_data_0 + 2 * workspace_height_stride);\n\n int8x16_t right_bank_0_reg;\n int8x16_t right_bank_1_reg;\n int8x16_t right_bank_2_reg;\n\n int32x4_t acc0;\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n const int output_width = i_width == output_width_micro_repeats\n ? residual_width\n : four_over_stride;\n TFLITE_DCHECK_LE(output_width * stride_val, 4);\n const int8* input_data =\n input_data_0 + width_micro_stride * i_width;\n const bool no_right_block = i_width == output_width_micro_repeats &&\n output_width_overall_micro_repeats ==\n workspace_width_micro_repeats;\n\n if (!no_right_block) {\n // Load next sub-micro block of data.\n right_bank_0_reg = vld1q_s8(input_data + width_micro_stride);\n right_bank_1_reg = vld1q_s8(input_data + width_micro_stride +\n workspace_height_stride);\n right_bank_2_reg = vld1q_s8(input_data + width_micro_stride +\n 2 * workspace_height_stride);\n }\n\n uint8* output_data_base = output_data + depth * 2 * i_width + 4 * s;\n\n // Iterate over input width shifts within 4x4 blocks.\n {\n acc0 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc0));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8 = vqmovun_s16(acc_s16_0_1);\n acc_u8 = vmax_u8(acc_u8, output_activation_min_vec);\n acc_u8 = vmin_u8(acc_u8, output_activation_max_vec);\n\n vst1_lane_u8x4(output_data_base, acc_u8, 0);\n\n left_bank_0_reg = vrev32q_u16(left_bank_0_reg);\n left_bank_1_reg = vrev32q_u16(left_bank_1_reg);\n left_bank_2_reg = vrev32q_u16(left_bank_2_reg);\n vtrn1_s8x2_in_place(&left_bank_0_reg, &right_bank_0_reg);\n vtrn1_s8x2_in_place(&left_bank_1_reg, &right_bank_1_reg);\n vtrn1_s8x2_in_place(&left_bank_2_reg, &right_bank_2_reg);\n }\n\n if (output_width > 1) {\n acc0 = adjusted_bias_data;\n\n acc0 = vdotq_s32(acc0, filter_reg_0_a, left_bank_0_reg);\n acc0 = vdotq_s32(acc0, filter_reg_1_a, left_bank_1_reg);\n acc0 = vdotq_s32(acc0, filter_reg_2_a, left_bank_2_reg);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc0));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8 = vqmovun_s16(acc_s16_0_1);\n acc_u8 = vmax_u8(acc_u8, output_activation_min_vec);\n acc_u8 = vmin_u8(acc_u8, output_activation_max_vec);\n\n vst1_lane_u8x4(output_data_base + depth, acc_u8, 0);\n\n left_bank_0_reg = right_bank_0_reg;\n left_bank_1_reg = right_bank_1_reg;\n left_bank_2_reg = right_bank_2_reg;\n }\n }\n bias_data += bias_increment;\n }\n }\n }\n } // NOLINT(readability/fn_size) Manually unrolled.\n\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n KernelMacroBlockIntrinsics(scratch_block_data, filter_workspace, bias_data,\n output_block_data, function_params);\n }\n};\n\ntemplate <>\nstruct KernelMacroBlock<\n DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n /*stride=*/1> {\n static inline void KernelMacroBlockIntrinsics(\n const int8* scratch_block_data, const int8* filter_workspace,\n const int32* bias_data, uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n TFLITE_DCHECK_EQ(function_params->stride, 1);\n const int workspace_height_stride =\n function_params->workspace_height_stride;\n const int output_width_micro_repeats =\n function_params->output_width_micro_repeats;\n const int depth_micro_repeats = function_params->depth_micro_repeats;\n const int output_depth = function_params->output_depth;\n\n const int output_width_overall_micro_repeats =\n function_params->output_width_overall_micro_repeats;\n const int block_height = function_params->outbound_block_height;\n const int residual_width = function_params->output_residual_width;\n const int output_height_stride = function_params->output_height_stride;\n const int bias_increment = function_params->bias_increment;\n\n TFLITE_DCHECK(depth_micro_repeats > 0);\n\n TFLITE_DCHECK_EQ(bias_increment, 4);\n\n const int32 output_activation_min =\n function_params->quantized_activation_min;\n const int32 output_activation_max =\n function_params->quantized_activation_max;\n const int32 output_multiplier = function_params->output_multiplier;\n const int32 output_shift = function_params->output_shift;\n const int32 output_offset = function_params->output_offset;\n TFLITE_DCHECK_GE(output_activation_min, 0);\n TFLITE_DCHECK_LT(output_activation_min, 256);\n TFLITE_DCHECK_GE(output_activation_max, 0);\n TFLITE_DCHECK_LT(output_activation_max, 256);\n TFLITE_DCHECK_GE(output_offset, -32878);\n TFLITE_DCHECK_LT(output_offset, 32768);\n\n const int16x8_t output_offset_vec =\n vdupq_n_s16(static_cast<int16>(output_offset));\n const uint8x16_t output_activation_min_vec =\n vdupq_n_u8(static_cast<uint8>(output_activation_min));\n const uint8x16_t output_activation_max_vec =\n vdupq_n_u8(static_cast<uint8>(output_activation_max));\n\n uint8* output_data_depthwise = output_block_data;\n for (int j_depth = 0; j_depth < depth_micro_repeats; ++j_depth) {\n // Simulate NEON-register transposition of subset of filter.\n int8x16_t filter_reg_0_a;\n int8x16_t filter_reg_0_b;\n int8x16_t filter_reg_1_a;\n int8x16_t filter_reg_1_b;\n int8x16_t filter_reg_2_a;\n int8x16_t filter_reg_2_b;\n int8x16_t filter_reg_0_a_shifted;\n int8x16_t filter_reg_1_a_shifted;\n int8x16_t filter_reg_2_a_shifted;\n\n filter_reg_0_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_0_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_1_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_1_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_2_a = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n filter_reg_2_b = vld1q_s8(filter_workspace);\n filter_workspace += 16;\n\n filter_reg_0_a_shifted = vshlq_n_u32(filter_reg_0_a, 8);\n filter_reg_1_a_shifted = vshlq_n_u32(filter_reg_1_a, 8);\n filter_reg_2_a_shifted = vshlq_n_u32(filter_reg_2_a, 8);\n\n if (block_height == 4) {\n for (int s = 0; s < 2; ++s) {\n // Work through one slice, by row, at a time.\n uint8* output_data_base = output_data_depthwise + 4 * s;\n\n const int8* next_input_data = scratch_block_data;\n uint8* output_data = output_data_base;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n bias_data += bias_increment;\n\n int8x16_t input_bank_a_reg; // left 0, right 0, left 1, right 1.\n int8x16_t input_bank_b_reg; // left 2, right 2, left 3, right 3.\n int8x16_t input_bank_c_reg; // left 4, right 4, left 5, right 5.\n\n // Load first sub-micro block of data into operational banks.\n input_bank_a_reg = vld1q_dup_s32(reinterpret_cast<const int32*>(\n next_input_data)); // Load lane 0, avoiding\n // uninitialized variable.\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + workspace_height_stride),\n input_bank_a_reg, 2);\n input_bank_b_reg = vld1q_dup_s32(reinterpret_cast<const int32*>(\n next_input_data +\n 2 * workspace_height_stride)); // Load lane 0, avoiding\n // uninitialized variable.\n input_bank_b_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + 3 * workspace_height_stride),\n input_bank_b_reg, 2);\n input_bank_c_reg = vld1q_dup_s32(reinterpret_cast<const int32*>(\n next_input_data +\n 4 * workspace_height_stride)); // Load lane 0, avoiding\n // uninitialized variable.\n input_bank_c_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + 5 * workspace_height_stride),\n input_bank_c_reg, 2);\n\n int32x4_t acc0;\n int32x4_t acc1;\n int32x4_t acc2;\n int32x4_t acc3;\n\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a, input_bank_b_reg, 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a, input_bank_b_reg, 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a, input_bank_b_reg, 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a, input_bank_b_reg, 2);\n\n for (int i_width = 0; i_width < output_width_micro_repeats;\n ++i_width) {\n next_input_data += 4;\n\n // Iterate over input width shifts within 4x4 blocks.\n {\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_0_a, input_bank_a_reg,\n 0);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_1_a, input_bank_a_reg,\n 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_0_a, input_bank_a_reg,\n 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_2_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_1_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_2_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_1_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_2_a, input_bank_c_reg,\n 2);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n output_data += output_depth;\n }\n // Load next sub-micro block of data.\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(next_input_data),\n input_bank_a_reg, 1);\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + workspace_height_stride),\n input_bank_a_reg, 3);\n input_bank_b_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 2 * workspace_height_stride),\n input_bank_b_reg, 1);\n input_bank_b_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 3 * workspace_height_stride),\n input_bank_b_reg, 3);\n input_bank_c_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 4 * workspace_height_stride),\n input_bank_c_reg, 1);\n input_bank_c_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 5 * workspace_height_stride),\n input_bank_c_reg, 3);\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_0_a_shifted,\n input_bank_a_reg, 0);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_1_a_shifted,\n input_bank_a_reg, 2);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a_shifted,\n input_bank_b_reg, 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_0_a_shifted,\n input_bank_a_reg, 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a_shifted,\n input_bank_b_reg, 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_2_a_shifted,\n input_bank_b_reg, 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a_shifted,\n input_bank_b_reg, 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_1_a_shifted,\n input_bank_b_reg, 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_2_a_shifted,\n input_bank_c_reg, 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a_shifted,\n input_bank_b_reg, 2);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_1_a_shifted,\n input_bank_c_reg, 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_2_a_shifted,\n input_bank_c_reg, 2);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n input_bank_a_reg = vshrq_n_u64(input_bank_a_reg, 16);\n input_bank_b_reg = vshrq_n_u64(input_bank_b_reg, 16);\n input_bank_c_reg = vshrq_n_u64(input_bank_c_reg, 16);\n\n output_data += output_depth;\n }\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_0_a, input_bank_a_reg,\n 0);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_1_a, input_bank_a_reg,\n 2);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a, input_bank_b_reg,\n 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_0_a, input_bank_a_reg,\n 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a, input_bank_b_reg,\n 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_2_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a, input_bank_b_reg,\n 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_1_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_2_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a, input_bank_b_reg,\n 2);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_1_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_2_a, input_bank_c_reg,\n 2);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n output_data += output_depth;\n }\n\n {\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_0_a_shifted,\n input_bank_a_reg, 0);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_1_a_shifted,\n input_bank_a_reg, 2);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a_shifted,\n input_bank_b_reg, 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_0_a_shifted,\n input_bank_a_reg, 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a_shifted,\n input_bank_b_reg, 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_2_a_shifted,\n input_bank_b_reg, 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a_shifted,\n input_bank_b_reg, 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_1_a_shifted,\n input_bank_b_reg, 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_2_a_shifted,\n input_bank_c_reg, 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a_shifted,\n input_bank_b_reg, 2);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_1_a_shifted,\n input_bank_c_reg, 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_2_a_shifted,\n input_bank_c_reg, 2);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n input_bank_a_reg = vshrq_n_u64(input_bank_a_reg, 16);\n input_bank_b_reg = vshrq_n_u64(input_bank_b_reg, 16);\n input_bank_c_reg = vshrq_n_u64(input_bank_c_reg, 16);\n\n output_data += output_depth;\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a, input_bank_b_reg,\n 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a, input_bank_b_reg,\n 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a, input_bank_b_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a, input_bank_b_reg,\n 2);\n }\n }\n\n if (residual_width > 0) {\n next_input_data += 4;\n const int output_width = residual_width;\n\n // Load next sub-micro block of data.\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(next_input_data),\n input_bank_a_reg, 1);\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + workspace_height_stride),\n input_bank_a_reg, 3);\n input_bank_b_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 2 * workspace_height_stride),\n input_bank_b_reg, 1);\n input_bank_b_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 3 * workspace_height_stride),\n input_bank_b_reg, 3);\n input_bank_c_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 4 * workspace_height_stride),\n input_bank_c_reg, 1);\n input_bank_c_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 5 * workspace_height_stride),\n input_bank_c_reg, 3);\n\n // Iterate over input width shifts within 4x4 blocks.\n for (int x = 0; x < output_width; ++x) {\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_0_a, input_bank_a_reg,\n 0);\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_1_a, input_bank_a_reg,\n 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_0_a, input_bank_a_reg,\n 2);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_2_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_1_a, input_bank_b_reg,\n 2);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_2_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_1_a, input_bank_c_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_2_a, input_bank_c_reg,\n 2);\n\n // Fixed-point multiplication.\n acc0 = vqrdmulhq_n_s32(acc0, output_multiplier);\n acc0 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc0, -output_shift);\n acc1 = vqrdmulhq_n_s32(acc1, output_multiplier);\n acc1 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc1, -output_shift);\n acc2 = vqrdmulhq_n_s32(acc2, output_multiplier);\n acc2 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc2, -output_shift);\n acc3 = vqrdmulhq_n_s32(acc3, output_multiplier);\n acc3 = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc3, -output_shift);\n // Add the output offset.\n int16x8_t acc_s16_0_1 =\n vcombine_s16(vqmovn_s32(acc0), vqmovn_s32(acc1));\n int16x8_t acc_s16_2_3 =\n vcombine_s16(vqmovn_s32(acc2), vqmovn_s32(acc3));\n acc_s16_0_1 = vqaddq_s16(acc_s16_0_1, output_offset_vec);\n acc_s16_2_3 = vqaddq_s16(acc_s16_2_3, output_offset_vec);\n // Apply the activation function.\n uint8x16_t acc_u8_all = vcombine_u8(vqmovun_s16(acc_s16_0_1),\n vqmovun_s16(acc_s16_2_3));\n acc_u8_all = vmaxq_u8(acc_u8_all, output_activation_min_vec);\n acc_u8_all = vminq_u8(acc_u8_all, output_activation_max_vec);\n\n vst1q_lane_u8x4(output_data, acc_u8_all, 0);\n vst1q_lane_u8x4(output_data + output_height_stride, acc_u8_all,\n 1);\n vst1q_lane_u8x4(output_data + 2 * output_height_stride,\n acc_u8_all, 2);\n vst1q_lane_u8x4(output_data + 3 * output_height_stride,\n acc_u8_all, 3);\n\n input_bank_a_reg = vshrq_n_u64(input_bank_a_reg, 8);\n input_bank_b_reg = vshrq_n_u64(input_bank_b_reg, 8);\n input_bank_c_reg = vshrq_n_u64(input_bank_c_reg, 8);\n\n output_data += output_depth;\n\n acc0 = adjusted_bias_data;\n acc1 = adjusted_bias_data;\n acc2 = adjusted_bias_data;\n acc3 = adjusted_bias_data;\n\n acc0 = vdotq_four_lane_s32(acc0, filter_reg_2_a, input_bank_b_reg,\n 0);\n acc1 = vdotq_four_lane_s32(acc1, filter_reg_1_a, input_bank_b_reg,\n 0);\n acc2 = vdotq_four_lane_s32(acc2, filter_reg_0_a, input_bank_b_reg,\n 0);\n acc3 = vdotq_four_lane_s32(acc3, filter_reg_0_a, input_bank_b_reg,\n 2);\n }\n }\n // scratch_block_data += 4 * workspace_height_stride;\n output_data_base += 4 * output_height_stride;\n\n // Move to next sub-block: advance to second set of filters, to new\n // bias.\n filter_reg_0_a = filter_reg_0_b;\n filter_reg_1_a = filter_reg_1_b;\n filter_reg_2_a = filter_reg_2_b;\n filter_reg_0_a_shifted = vshlq_n_u32(filter_reg_0_a, 8);\n filter_reg_1_a_shifted = vshlq_n_u32(filter_reg_1_a, 8);\n filter_reg_2_a_shifted = vshlq_n_u32(filter_reg_2_a, 8);\n }\n } else {\n // Block height < 4.\n for (int s = 0; s < 2; ++s) {\n // Work through one slice, by row, at a time.\n uint8* output_data_base = output_data_depthwise + 4 * s;\n\n const int32x4_t adjusted_bias_data = vld1q_s32(bias_data);\n TFLITE_DCHECK_EQ(bias_increment, 4);\n bias_data += bias_increment;\n\n for (int k_height = 0; k_height < block_height; ++k_height) {\n const int8* next_input_data =\n scratch_block_data + k_height * workspace_height_stride;\n uint8* output_data = output_data_base;\n\n int8x16_t input_bank_a_reg; // left 0, right 0, left 1, right 1.\n int8x16_t input_bank_b_reg; // left 2, right 2, left 3, right 3.\n\n // Load first sub-micro block of data into operational banks.\n input_bank_a_reg = vld1q_dup_s32(reinterpret_cast<const int32*>(\n next_input_data)); // Load lane 0, avoiding uninitialized\n // variable.\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + workspace_height_stride),\n input_bank_a_reg, 2);\n input_bank_b_reg = vld1q_dup_s32(reinterpret_cast<const int32*>(\n next_input_data +\n 2 * workspace_height_stride)); // Load lane 0, avoiding\n // uninitialized variable.\n\n for (int i_width = 0; i_width < output_width_overall_micro_repeats;\n ++i_width) {\n next_input_data += 4;\n const int output_width =\n i_width == output_width_micro_repeats ? residual_width : 4;\n\n // Load next sub-micro block of data.\n input_bank_a_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data),\n input_bank_a_reg, 1);\n input_bank_a_reg =\n vld1q_lane_s32(reinterpret_cast<const int32*>(\n next_input_data + workspace_height_stride),\n input_bank_a_reg, 3);\n input_bank_b_reg = vld1q_lane_s32(\n reinterpret_cast<const int32*>(next_input_data +\n 2 * workspace_height_stride),\n input_bank_b_reg, 1);\n // Iterate over input width shifts within 4x4 blocks.\n for (int x = 0; x < output_width; ++x) {\n int32x4_t acc = adjusted_bias_data;\n acc = vdotq_four_lane_s32(acc, filter_reg_0_a, input_bank_a_reg,\n 0);\n acc = vdotq_four_lane_s32(acc, filter_reg_1_a, input_bank_a_reg,\n 2);\n acc = vdotq_four_lane_s32(acc, filter_reg_2_a, input_bank_b_reg,\n 0);\n\n // Fixed-point multiplication.\n acc = vqrdmulhq_n_s32(acc, output_multiplier);\n acc = DivideByPOT<DepthwiseConvOutputRounding::kUpward>::Run(\n acc, -output_shift);\n // Add the output offset.\n // Note that we need to fill the top half with vcombine, but can\n // drop the instruction in ASM code.\n int16x8_t acc_s16_0_0 =\n vcombine_s16(vqmovn_s32(acc), vqmovn_s32(acc));\n acc_s16_0_0 = vqaddq_s16(acc_s16_0_0, output_offset_vec);\n // Apply the activation function.\n uint8x8_t acc_u8_0_0 = vqmovun_s16(acc_s16_0_0);\n acc_u8_0_0 =\n vmax_u8(acc_u8_0_0, vget_low_u8(output_activation_min_vec));\n acc_u8_0_0 =\n vmin_u8(acc_u8_0_0, vget_low_u8(output_activation_max_vec));\n\n // if (x==1) {\n vst1_lane_u8x4(output_data, acc_u8_0_0, 0);\n // }\n\n input_bank_a_reg = vshrq_n_u64(input_bank_a_reg, 8);\n input_bank_b_reg = vshrq_n_u64(input_bank_b_reg, 8);\n\n output_data += output_depth;\n }\n }\n output_data_base += output_height_stride;\n }\n\n // Move to next sub-block: advance to second set of filters.\n filter_reg_0_a = filter_reg_0_b;\n filter_reg_1_a = filter_reg_1_b;\n filter_reg_2_a = filter_reg_2_b;\n }\n }\n output_data_depthwise += 8;\n }\n } // NOLINT(readability/fn_size) Manually unrolled.\n\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n KernelMacroBlockIntrinsics(scratch_block_data, filter_workspace, bias_data,\n output_block_data, function_params);\n }\n};\n\ntemplate <>\nstruct KernelMacroBlock<\n DepthwiseConvImplementation::kUseIntrinsics3x3DotProduct,\n DepthwiseConvDepthMultiplication::kUnitInputDepth,\n /*stride=*/2> {\n static inline void Run(const int8* scratch_block_data,\n const int8* filter_workspace, const int32* bias_data,\n uint8* output_block_data,\n const DepthwiseConvDotProdParams* function_params) {\n TFLITE_CHECK(false); // TODO(b/127805639): Not yet implemented.\n }\n};\n\n#undef vst1_lane_u8x4\n#undef vst1q_lane_u8x4\n#undef vld1q_lane_s8x8\n\n#endif\n\n} // namespace depthwise_conv\n} // namespace optimized_ops\n} // namespace tflite\n\n#endif // TENSORFLOW_LITE_KERNELS_INTERNAL_OPTIMIZED_DEPTHWISECONV_UINT8_TRANSITIONAL_H_\n"
},
{
"alpha_fraction": 0.6962913274765015,
"alphanum_fraction": 0.7036418318748474,
"avg_line_length": 41.75714111328125,
"blob_id": "974f164284cd3862f1920c5f40ad51f67c740c7c",
"content_id": "1adf9d8e2ad333e0782cd07f348ac603ff04aeae",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2993,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 70,
"path": "/tensorflow/python/keras/layers/dense_attention.py",
"repo_name": "overtheaurora/tensorflow",
"src_encoding": "UTF-8",
"text": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Attention layers that can be used in sequence DNN/CNN models.\n\nThis file follows the terminology of https://arxiv.org/abs/1706.03762 Figure 2.\nAttention is formed by three tensors: Query, Key and Value.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.engine.base_layer import Layer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import nn\n\n\nclass BaseDenseAttention(Layer):\n \"\"\"Base Attention class for Dense networks.\n\n This class is suitable for Dense or CNN networks, and not for RNN networks.\n\n Implementations of attention mechanisms should inherit from this class, and\n reuse the `apply_attention_scores()` method.\n \"\"\"\n\n def apply_attention_scores(self, scores, value, value_mask=None):\n \"\"\"Applies attention scores to the given value tensor.\n\n To use this method in your attention layer, follow the steps:\n\n * Use `query` tensor of shape `[batch_size, Tq]` and `key` tensor of shape\n `[batch_size, Tv]` to calculate the attention `scores`.\n * Pass `scores` and `value` tensors to this method. The method applies\n `value_mask`, calculates `attention_distribution = softmax(scores)`, then\n returns `matmul(attention_distribution, value).\n * Apply `query_mask` and return the result.\n\n Args:\n scores: Scores float tensor of shape `[batch_size, Tq, Tv]`.\n value: Value tensor of shape `[batch_size, Tv, dim]`.\n value_mask: A boolean mask `Tensor` of shape `[batch_size, Tv]`.\n If given, will apply the mask such that values at positions where\n `mask==False` do not contribute to the result.\n\n Returns:\n Tensor of shape `[batch_size, Tq, dim]`.\n \"\"\"\n if value_mask is not None:\n # Mask of shape [batch_size, 1, Tv] that is True in padding position.\n padding_mask = array_ops.expand_dims(\n math_ops.logical_not(value_mask), axis=1)\n # Bias so padding positions do not contribute to attention distribution.\n scores -= 1.e9 * math_ops.cast(padding_mask, dtype=K.floatx())\n attention_distribution = nn.softmax(scores)\n return math_ops.matmul(attention_distribution, value)\n"
},
{
"alpha_fraction": 0.5388724207878113,
"alphanum_fraction": 0.61622154712677,
"avg_line_length": 40.434425354003906,
"blob_id": "772840bbe005a74faaec0503be74f53821917a7c",
"content_id": "0d7ebf4e225dce612e4220b5199e45c3c44e73db",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5055,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 122,
"path": "/tensorflow/python/keras/layers/dense_attention_test.py",
"repo_name": "overtheaurora/tensorflow",
"src_encoding": "UTF-8",
"text": "# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests dense attention layers.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\n\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.keras.layers import dense_attention\nfrom tensorflow.python.platform import test\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass BaseDenseAttentionTest(test.TestCase):\n\n def test_one_dim_with_mask(self):\n # Scores tensor of shape [1, 1, 1]\n scores = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 1, 1]\n v = np.array([[[1.6]]], dtype=np.float32)\n # Value mask tensor of shape [1, 1]\n v_mask = np.array([[True]], dtype=np.bool_)\n actual = dense_attention.BaseDenseAttention().apply_attention_scores(\n scores=scores, value=v, value_mask=v_mask)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = softmax(scores)[0, 0] * 1.6 = 1.6\n expected = np.array([[[1.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_one_dim_no_mask(self):\n # Scores tensor of shape [1, 1, 1]\n scores = np.array([[[1.1]]], dtype=np.float32)\n # Value tensor of shape [1, 1, 1]\n v = np.array([[[1.6]]], dtype=np.float32)\n actual = dense_attention.BaseDenseAttention().apply_attention_scores(\n scores=scores, value=v)\n\n # Expected tensor of shape [1, 1, 1].\n # expected000 = softmax(scores)[0, 0] * 1.6 = 1.6\n expected = np.array([[[1.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_with_mask(self):\n # Scores tensor of shape [1, 1, 3]\n scores = np.array([[[1., 0., 1.]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n # Value mask tensor of shape [1, 3]\n v_mask = np.array([[True, True, False]], dtype=np.bool_)\n actual = dense_attention.BaseDenseAttention().apply_attention_scores(\n scores=scores, value=v, value_mask=v_mask)\n\n # Expected attention distribution = softmax(scores) with zeros in\n # positions where v_mask == False.\n # => attention_distribution000 = exp(1)/(exp(1) + exp(0)) = 0.73105857863\n # attention_distribution001 = exp(0)/(exp(1) + exp(0)) = 0.26894142137\n # attention_distribution002 = 0\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.73105857863 * 1.6 + 0.26894142137 * 0.7 - 0 * 0.8\n # = 1.35795272077\n expected = np.array([[[1.35795272077]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_multi_dim_no_mask(self):\n # Scores tensor of shape [1, 1, 3]\n scores = np.array([[[1., 0., 1.]]], dtype=np.float32)\n # Value tensor of shape [1, 3, 1]\n v = np.array([[[1.6], [0.7], [-0.8]]], dtype=np.float32)\n actual = dense_attention.BaseDenseAttention().apply_attention_scores(\n scores=scores, value=v)\n\n # Expected attention distribution = softmax(scores).\n # => attention_distribution000 = exp(1)/(exp(1) + exp(0) + exp(1))\n # = 0.42231879825\n # attention_distribution001 = exp(0)/(exp(1) + exp(0) + exp(1))\n # = 0.15536240349\n # attention_distribution002 = exp(1)/(exp(1) + exp(0) + exp(1))\n # = 0.42231879825\n #\n # Expected tensor of shape [1, 1, 1].\n # expected000 = 0.42231879825 * 1.6 + 0.15536240349 * 0.7\n # - 0.42231879825 * 0.8\n # = 0.44660872104\n expected = np.array([[[0.44660872104]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n def test_one_dim_batch_size_two(self):\n # Scores tensor of shape [2, 1, 1]\n scores = np.array([[[1.1]], [[2.1]]], dtype=np.float32)\n # Value tensor of shape [2, 1, 1]\n v = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n # Value mask tensor of shape [2, 1]\n v_mask = np.array([[True], [True]], dtype=np.bool_)\n actual = dense_attention.BaseDenseAttention().apply_attention_scores(\n scores=scores, value=v, value_mask=v_mask)\n\n # Expected tensor of shape [2, 1, 1].\n # expected000 = softmax(scores)[0, 0] * 1.6 = 1.6\n # expected100 = softmax(scores)[1, 0] * 2.6 = 2.6\n expected = np.array([[[1.6]], [[2.6]]], dtype=np.float32)\n self.assertAllClose(expected, actual)\n\n\nif __name__ == '__main__':\n test.main()\n"
}
] | 3 |
sch0lars/HackThisSiteProgramming2
|
https://github.com/sch0lars/HackThisSiteProgramming2
|
f72559447380fefdf3948c04f123b8997fddefb6
|
1d573f3c8b451ae6ed7250b75735b603a5b4ccc5
|
979462e6e633d1ea20fbbe7ca40cf44aa819c396
|
refs/heads/master
| 2023-09-01T14:48:40.130882 | 2020-10-11T03:33:08 | 2023-08-06T00:59:25 | 303,034,512 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.3629290759563446,
"alphanum_fraction": 0.37116703391075134,
"avg_line_length": 24.68235206604004,
"blob_id": "7a801c083d4de5288dd61482bee2951631a23cf8",
"content_id": "36454dd84c495a2db4ce5cd87962d3add078ba26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2185,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 85,
"path": "/HackThisSiteProgramming2.py",
"repo_name": "sch0lars/HackThisSiteProgramming2",
"src_encoding": "UTF-8",
"text": "# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # \n# #\n# Solution to Programming Mission 2 on Hack This Site. #\n# #\n# Author: Tyler Hooks #\n# #\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n\nfrom PIL import Image\nfrom io import BytesIO\nimport requests\n\nmorse = {\n\n '.-':'a',\n '-...':'b',\n '-.-.':'c',\n '-..-':'d',\n '.':'e',\n '..-.':'f',\n '--.':'g',\n '....':'h',\n '..':'i',\n '.---':'j',\n '-.-':'k',\n '.-..':'l',\n '--':'m',\n '-.':'n',\n '---':'o',\n '.--.':'p',\n '--.-':'q',\n '.-.':'r',\n '...':'s',\n '-':'t',\n '..-':'u',\n '...-':'v',\n '.--':'w',\n '-..-':'x',\n '-.--':'y',\n '--..':'z',\n\n '.----':'1',\n '..---':'2',\n '...--':'3',\n '....-':'4',\n '.....':'5',\n '-....':'6',\n '--...':'7',\n '---..':'8',\n '----.':'9',\n '-----':'0'\n\n }\n\nurl = 'https://www.hackthissite.org/missions/prog/2/'\nreferer = 'https://www.hackthissite.org/missions/programming/'\n# Change \"YourCookieValue\" to your own cookie value.\ncookies = {'PHPSESSID':'YourCookieValue'}\n\n# Start a session. \nsession = requests.Session()\nsession.headers.update({'referer':referer})\nsite = session.post(url, cookies = cookies)\n\n# Retrieve the image and convert differences in pixel values to ASCII characters. \nimg = session.get('https://www.hackthissite.org/missions/prog/2/PNG/', cookies = cookies)\nimage = Image.open(BytesIO(img.content))\nmessage = \"\"\nanswer = \"\"\nindex = 0\ncurrent = 0\nfor d in image.getdata():\n if d != 0:\n message += chr(index - current)\n current = index\n index += 1\n\n# Convert the morse code.\nfor m in message.split():\n answer += morse[m]\n \nurl = 'https://www.hackthissite.org/missions/prog/2/'\npayload = {'solution':answer}\nsite = session.post(url, cookies = cookies, data = payload)\n\n\n"
}
] | 1 |
michaelwalshe/Alpha-Particle-in-ICF
|
https://github.com/michaelwalshe/Alpha-Particle-in-ICF
|
bbd1c7e457e6841a9ada5036e5e61c0e2417cd7b
|
df39ce6d1c7de1829b3f33ca1d469411cb712429
|
95343516150a85634eb49cc6ec103a72c55d323a
|
refs/heads/master
| 2023-08-12T03:14:57.400760 | 2021-10-12T13:41:54 | 2021-10-12T13:41:54 | 249,468,741 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.39228394627571106,
"alphanum_fraction": 0.4691357910633087,
"avg_line_length": 30.727272033691406,
"blob_id": "343544f587b51ae81ee418f3cc03a33621ee296d",
"content_id": "c3e29a9e91659683e4492c8657f9b1d72a08f5a0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3240,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 99,
"path": "/T_matrix_edie_cgs.py",
"repo_name": "michaelwalshe/Alpha-Particle-in-ICF",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jan 24 00:10:22 2019\r\nCalculate the stopping power of a plasma using T-matrix model from Edie PhD thesis\r\n\r\nUNITS ARE IN CGS, CONSTANTS ARE DIFFERENT\r\n@author: Michael\r\n\"\"\"\r\n\r\nimport math as m\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Gives you the coefficient dependent on degeneracy param x (based on gamma and charge) and which coefficient i you want\r\ndef coef(i, x):\r\n if i == 1:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 2:\r\n a = m.exp(2.561 * x - 1.15)\r\n elif i == 3:\r\n a = m.exp(3.141 * x - 2.41)\r\n elif i == 4 and x > 0.548:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 4 and (x < 0.548 or x > -2.649):\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 4 and x < -2.649:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 5 and x > -3.13:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 5 and (x < 0.548 or x < -3.13):\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 6:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 7 and x > 1.83:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 7 and x < 1.83:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 8:\r\n a = m.exp(1.78 * x - 1.01)\r\n elif i == 9:\r\n a = m.exp(1.78 * x - 1.01)\r\n return a\r\n\r\n\r\n# Calculates dE/dx for energy of alpha particle E\r\ndef dE(E):\r\n T = 10 ** 7 # temp in K\r\n n_e = 10 ** 25 # density of electrons (&ions*2) in cm^-3\r\n m_alpha = 6.644e-24 # mass of alpha in kg\r\n m_e = 9.1e-28 # mass of e- in g\r\n Z_b = 2 # charge of alpha\r\n e = 4.8e-10 # charge of e-\r\n k = 1.38e-16 # boltzmann\r\n hbar = 1.055e-27 # planck\r\n a_B = 5.29e-9 # assumed bohr radius but not sure\r\n Gamma = e ** 2 * (\r\n m.pow(((4 * m.pi * n_e) / 3), 1 / 3) / (k * T)\r\n ) # Gamma_ee coupling param from edie\r\n v_th = m.sqrt((k * T) / m_e) # thermal velocity of electrons\r\n omega = m.sqrt((4 * m.pi * n_e * e ** 2) / m_e) # electron plasma frequency\r\n c1 = (2 * m_e * v_th ** 2) / (hbar * omega)\r\n c2 = (3 * a_B * (k * T) ** 3) / (Z_b ** 2 * e ** 2 * hbar ** 2 * omega ** 2)\r\n vel = m.sqrt(2 * E / m_alpha) # velocity of alpha particles\r\n x = m.log(Z_b * m.pow(Gamma, 1.5)) # x_0 argument\r\n vbar = vel / v_th\r\n dEdxtop = (\r\n coef(1, x) * vbar\r\n + coef(2, x) * vbar ** 2\r\n + coef(3, x) * vbar ** 4 * m.log(c1 * vbar ** 2 + 1)\r\n )\r\n dEdxbot = (\r\n 1\r\n + coef(5, x) * vbar\r\n + coef(6, x) * vbar ** 2\r\n + coef(7, x) * vbar ** 3\r\n + coef(8, x) * vbar ** 4\r\n + coef(9, x) * vbar ** 5\r\n + coef(4, x) * c2 * vbar ** 7\r\n )\r\n dEdx = (dEdxtop / dEdxbot) * (\r\n (3 * (k * T) ** 2) / (e ** 2)\r\n ) # not sure I need the second bit\r\n return dEdx\r\n\r\n\r\nif __name__ == \"__main__\":\r\n T_c = 10 ** 7\r\n E_MeV = np.linspace(0.01, 6.0, 100)\r\n E_erg = E_MeV * 10 ** 6 * 1.6e-19 * 10 ** -7\r\n T_mat_dEdx = np.zeros_like(E_MeV)\r\n for i in range(100):\r\n T_mat_dEdx[i] = dE(E_erg[i]) / 1.6e-8\r\n print(E_MeV)\r\n print(T_mat_dEdx)\r\n plt.plot(E_MeV, T_mat_dEdx, label=\"T-matrix\")\r\n plt.xlabel(\"E[MeV]\")\r\n plt.ylabel(\"-dE/dx [MeV / micrometer]\")\r\n plt.savefig(\"t_matrix.png\")\r\n plt.show()\r\n"
},
{
"alpha_fraction": 0.739130437374115,
"alphanum_fraction": 0.739130437374115,
"avg_line_length": 22,
"blob_id": "147f95a079c35fa19cf60c544c2befb554cd5441",
"content_id": "d3960d20eb18e8916ef58351ea560bb6172ec3f5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 23,
"license_type": "permissive",
"max_line_length": 22,
"num_lines": 1,
"path": "/README.md",
"repo_name": "michaelwalshe/Alpha-Particle-in-ICF",
"src_encoding": "UTF-8",
"text": "# Bits of project code\n"
},
{
"alpha_fraction": 0.4116247594356537,
"alphanum_fraction": 0.48368456959724426,
"avg_line_length": 26.843137741088867,
"blob_id": "15a94bb42c20a5a69f2622ed08b2bdea1fa5db80",
"content_id": "8f30b271bfb4e67b02cfca40156b17c672f439ef",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2942,
"license_type": "permissive",
"max_line_length": 115,
"num_lines": 102,
"path": "/thomas_fermi_edie.py",
"repo_name": "michaelwalshe/Alpha-Particle-in-ICF",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 23 22:39:13 2019\r\nCalculate the stopping power of a plasma using Thomas-Fermi model from Edie PhD thesis\r\n\r\n\r\n@author: Michael\r\n\"\"\"\r\n\r\nimport math as m\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Calculates the chemical potential for a certain temperature (using Ichimaru approx. from stat. physics of plasma)\r\ndef fermi_int(T):\r\n n_e = 10 ** 25 # dens of e- in cm^-3\r\n hbar = 1.054e-27 # planck constant in cgs\r\n m_e = 9.1e-31 # mass of e- in g\r\n E_F = ((hbar ** 2) / (2 * m_e)) * m.pow((3 * m.pi ** 2 * n_e), 2 / 3)\r\n theta = T / E_F\r\n I_half = (2 / 3) * m.pow(theta, -1.5)\r\n A = 0.25954\r\n B = 0.072\r\n b = 0.858\r\n const = (A * m.pow(theta, -(b + 1)) + B * m.pow(theta, -0.5 * (b + 1))) / (\r\n 1 + A * m.pow(theta, -b)\r\n )\r\n mu = T * (1.5 * m.log(theta) + 4 * m.log(4 / (3 * m.sqrt(m.pi))) + const)\r\n return (mu, I_half)\r\n\r\n\r\n# This calculates the arg. x_0 for our DT plasma with alpha particle beam\r\n# needs energy of beam epsilon_b, temp of plasma\r\ndef x_0(eps_b, T_c):\r\n m_b = 6.644e-24 # mass of alpha particle in g\r\n m_c = 4.15e-24 # avg mass of D & T in g\r\n k = 1.38e-16 # boltzmann in cgs\r\n fermi = fermi_int(T_c)\r\n eta = fermi[0] / (k * T_c)\r\n I = fermi[1]\r\n a1 = m.sqrt((m_c * eps_b) / (m_b * k * T_c))\r\n a2 = m.sqrt(m.pi) / (2 * I * (1 + m.exp(-eta)))\r\n a3 = m.pow(a2, 1 / 3)\r\n x = a1 * a3\r\n print(fermi)\r\n return x\r\n\r\n\r\n# Heaviside step fct for x (0 unless x positive)\r\ndef erf(x):\r\n if x < 0:\r\n return 0\r\n else:\r\n return 1\r\n\r\n\r\n##Calculates Pade approximation for coulomb logarithm\r\ndef pade(eps_b, T_c):\r\n m_e = 9.1e-28\r\n k = 1.38e-16\r\n v_e = m.sqrt((k * T_c) / m_e)\r\n n_e = 10 ** 25\r\n e = 4.8e-10\r\n hbar = 1.055e-27\r\n omega = m.sqrt((4 * m.pi * n_e * e ** 2) / m_e) # electron plasma frequency\r\n x = x_0(eps_b, T_c)\r\n b1 = (2 * m_e * v_e ** 2) / (hbar * omega)\r\n b2 = (0.321 + 0.259 * x ** 2 + 0.0707 * x ** 4 + 0.05 * x ** 6) / (\r\n 1 + 0.13 * x ** 2 + 0.05 * x ** 4\r\n )\r\n return b1 * b2\r\n\r\n\r\n# calc dE/dx\r\ndef dE(eps_b, T_c):\r\n Z_b = 2\r\n e = 4.8e-10\r\n m_b = 6.644e-24\r\n m_c = 4.15e-24\r\n v_b = m.sqrt((2 * eps_b) / m_b)\r\n x = x_0(eps_b, T_c)\r\n c1 = (4 * m.pi * Z_b ** 2 * e ** 4) / (m_c * v_b ** 2)\r\n c2 = m.log(pade(eps_b, T_c)) * (\r\n erf(x) - (1 + m_c / m_b) * ((2 / m.sqrt(m.pi)) * x * m.exp(-(x ** 2)))\r\n )\r\n print(c1)\r\n return -c1 * c2\r\n\r\n\r\nif __name__ == \"__main__\":\r\n T_c = 10 ** 7 # temp in K\r\n E_MeV = np.linspace(0.01, 4.0, 50)\r\n E_erg = E_MeV * 10 ** 6 * 1.6e-19 * 10 ** -7\r\n dEdx = np.zeros_like(E_MeV)\r\n for i in range(50):\r\n dEdx[i] = -1 * dE(E_erg[i], T_c) / 1.6e-8\r\n print(dEdx)\r\n plt.plot(E_MeV, dEdx)\r\n plt.xlabel(\"E[MeV]\")\r\n plt.ylabel(\"-dE/dx [MeV / micrometer]\")\r\n plt.savefig(\"thomas_fermi.png\")\r\n plt.show()\r\n"
}
] | 3 |
BrutishGuy/BDAPAssignment3
|
https://github.com/BrutishGuy/BDAPAssignment3
|
5a36f78c825f36ae23c740febea4f195d34fe984
|
eab25cc6f88f376d6b1a83e468791d95f0890c0d
|
f71ccbb24d2f781f9aeeabce980ace8e30e6b971
|
refs/heads/master
| 2023-07-05T05:24:55.290561 | 2021-08-20T00:24:56 | 2021-08-20T00:24:56 | 257,444,791 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5914285778999329,
"alphanum_fraction": 0.5971428751945496,
"avg_line_length": 20.18181800842285,
"blob_id": "da8fc5a3281591b0d58c13d633e01d6f2fad7ed3",
"content_id": "41a403ac309cb8394c837cc1cc15c486aadbb650",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 700,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 33,
"path": "/code/src/Precision.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Written by Victor Gueorguiev, 2020\n */\n\n\n/**\n * This class calculates the precision\n */\npublic class Precision implements EvaluationMetric {\n\n /**\n * Calculates the precision given the values of the contingency table\n *\n * @param TP Number of true positives\n * @param FP Number of false positives\n * @param TN Number of true negatives\n * @param FN Number of false negatives\n * @return evaluation evaluate\n */\n @Override\n public double evaluate(int TP, int FP, int TN, int FN) {\n return ((double) TP)/(TP + FP);\n }\n\n /**\n *\n * @return name of the evaluator\n */\n @Override\n public String name() {\n return \"precision\";\n }\n}\n\n"
},
{
"alpha_fraction": 0.6281113028526306,
"alphanum_fraction": 0.6339678168296814,
"avg_line_length": 22.55172348022461,
"blob_id": "124b42826c4b493f97cb87136f4f090d973bc582",
"content_id": "c50b5237fc38ecc065b518be419268ebdf64951e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 685,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 29,
"path": "/code/src/EvaluationMetric.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Copyright (c) DTAI - KU Leuven – All rights reserved.\n * Proprietary, do not copy or distribute without permission.\n * Written by Jessa Bekker and Pieter Robberechts, 2020\n */\n\n\n/**\n * This interface represents an evaluation metric\n */\npublic interface EvaluationMetric {\n\n /**\n * Evaluate given the values of the contingency table\n *\n * @param TP Number of true positives\n * @param FP Number of false positives\n * @param TN Number of true negatives\n * @param FN Number of false negatives\n * @return evaluation evaluate\n */\n double evaluate(int TP, int FP, int TN, int FN);\n\n /**\n *\n * @return name of the evaluator\n */\n String name();\n}\n"
},
{
"alpha_fraction": 0.5764994025230408,
"alphanum_fraction": 0.588739275932312,
"avg_line_length": 22.314285278320312,
"blob_id": "3a296985540402b2e727280e51bf22c9033622e3",
"content_id": "c7adcc9024f4d78d0cff6ce0d5805d64cad86ab6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 817,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 35,
"path": "/code/src/F1Score.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Written by Victor Gueorguiev, 2020\n */\n\n\n/**\n * This class calculates the F1 score\n */\npublic class F1Score implements EvaluationMetric {\n\n /**\n * Calculates the F1 score given the values of the contingency table\n *\n * @param TP Number of true positives\n * @param FP Number of false positives\n * @param TN Number of true negatives\n * @param FN Number of false negatives\n * @return evaluation evaluate\n */\n @Override\n public double evaluate(int TP, int FP, int TN, int FN) {\n double precision = ((double) TP)/(TP + FP);\n double recall = ((double) TP)/(TP+FN);\n return 2.0 * (precision * recall)/(precision + recall);\n }\n\n /**\n *\n * @return name of the evaluator\n */\n @Override\n public String name() {\n return \"f1score\";\n }\n}\n\n"
},
{
"alpha_fraction": 0.5881502628326416,
"alphanum_fraction": 0.5939306616783142,
"avg_line_length": 19.939393997192383,
"blob_id": "1619e0f3c3cc1135710da13d7903bd50c99daf76",
"content_id": "17564c3145506a0e8e164729268681b0afa42c27",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 692,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 33,
"path": "/code/src/Recall.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Written by Victor Gueorguiev, 2020\n */\n\n\n/**\n * This class calculates the recall score\n */\npublic class Recall implements EvaluationMetric {\n\n /**\n * Calculates the recall given the values of the contingency table\n *\n * @param TP Number of true positives\n * @param FP Number of false positives\n * @param TN Number of true negatives\n * @param FN Number of false negatives\n * @return evaluation evaluate\n */\n @Override\n public double evaluate(int TP, int FP, int TN, int FN) {\n return ((double) TP)/(TP+FN);\n }\n\n /**\n *\n * @return name of the evaluator\n */\n @Override\n public String name() {\n return \"recall\";\n }\n}\n\n"
},
{
"alpha_fraction": 0.4522058963775635,
"alphanum_fraction": 0.46599265933036804,
"avg_line_length": 16.015625,
"blob_id": "8d9e22a9b48d2553dcbb29639ded329e17039cb7",
"content_id": "4981d386a5eff07cb78da8e04388ffbf6134ae1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1088,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 64,
"path": "/code/src/HelperFunctions.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "import java.util.Arrays;\n\npublic class HelperFunctions {\n\t\n\t\n /**\n * Calculates the positive remainder of a divided by b.\n * @param a\n * @param b\n * @return\n */\n public static int posMod(int a, int b) {\n\n int result = Math.floorMod(a, b);\n\n if (result < 0)\n result += b;\n\n return result;\n\n\n }\n\t\n /**\n * Calculates ln(a+b), given ln(a) and ln(b)\n * @param lna\n * @param lnb\n * @return\n */\n public static double logSum(double lna, double lnb) {\n \t\n \tif (lna >= lnb)\n \t\treturn lna + Math.log(1 + Math.exp(lnb - lna));\n \telse\n \t\treturn lnb + Math.log(1 + Math.exp(lna - lnb));\n\n \t\n }\n \n \n /**\n * Calculates the median of unsorted array a\n * @param a\n * @return\n */\n public static double getMedian(double[] a) {\n \t\n \tArrays.sort(a);\n \tint n = a.length;\n \t\n \tif (n % 2 == 0) {\n \t\tdouble m1 = a[n/2];\n \t\tdouble m2 = a[n/2+1];\n \t\treturn (m1 + m2) / 2;\n \t} else {\n \t\treturn a[(n+1)/2];\n \t}\n \t\t\n \t\n \t\t\n \t\n }\n\n}"
},
{
"alpha_fraction": 0.5896005630493164,
"alphanum_fraction": 0.6000597476959229,
"avg_line_length": 34.982078552246094,
"blob_id": "ca53d0f26666fd7db890c03a081cbef6a224cb32",
"content_id": "cfb4685d175b727532dc738a60be8106fc5a1dfa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 10041,
"license_type": "no_license",
"max_line_length": 192,
"num_lines": 279,
"path": "/code/src/PerceptronL2RegFeatureHashing.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Copyright (c) DTAI - KU Leuven – All rights reserved.\n * Proprietary, do not copy or distribute without permission.\n * Written by Jessa Bekker and Pieter Robberechts, 2020\n */\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.HashSet;\nimport java.util.Set;\n\n\n/**\n * This class is a stub for a perceptron with count-min sketch\n */\npublic class PerceptronL2RegFeatureHashing extends OnlineTextClassifier{\n\n private int logNbOfBuckets;\n private int nbOfBuckets;\n private double learningRate;\n private double bias;\n private double[] weights; //weights[i]: The weight for n-grams that hash to value i\n private double sum_error;\n private int seed;\n /* FILL IN HERE */\n\n /**\n * Initialize the perceptron classifier\n *\n * THIS CONSTRUCTOR IS REQUIRED, DO NOT CHANGE THE HEADER\n * You can write additional constructors if you wish, but make sure this one works\n *\n * This classifier uses simple feature hashing: The features of this classifier are the hash values that n-grams\n * hash to.\n *\n * @param logNbOfBuckets The hash functions hash to the range [0,2^NbOfBuckets-1]\n * @param learningRate The size of the updates of the weights\n */\n public PerceptronL2RegFeatureHashing(int logNbOfBuckets, double learningRate){\n this.logNbOfBuckets=logNbOfBuckets;\n this.learningRate = learningRate;\n this.nbOfBuckets=((int) Math.pow(2, logNbOfBuckets));\n this.sum_error = 0;\n bias = 0;\n this.seed = (int) Math.random() * 1000;\n weights = new double[this.nbOfBuckets];\n // here we initialize the weights to random values between 0 and 1\n for (int i = 0; i < this.nbOfBuckets; i++) {\n weights[i] = 0;//Math.random();\n }\n }\n\n /**\n * Initialize the perceptron classifier\n *\n * THIS CONSTRUCTOR IS REQUIRED, DO NOT CHANGE THE HEADER\n * You can write additional constructors if you wish, but make sure this one works\n *\n * This classifier uses simple feature hashing: The features of this classifier are the hash values that n-grams\n * hash to.\n *\n * @param logNbOfBuckets The hash functions hash to the range [0,2^NbOfBuckets-1]\n * @param learningRate The size of the updates of the weights\n */\n public PerceptronL2RegFeatureHashing(int logNbOfBuckets, double learningRate, double threshold){\n this.logNbOfBuckets=logNbOfBuckets;\n this.learningRate = learningRate;\n this.nbOfBuckets=((int) Math.pow(2, logNbOfBuckets));\n this.sum_error = 0;\n this.threshold = threshold;\n bias = 0;\n this.seed = (int) Math.random() * 1000;\n \n weights = new double[this.nbOfBuckets];\n // here we initialize the weights to random values between 0 and 1\n for (int i = 0; i < this.nbOfBuckets; i++) {\n weights[i] = 0;//Math.random();\n }\n }\n\n /**\n * Calculate the hash value for string str\n *\n * THIS METHOD IS REQUIRED\n *\n * The hash function hashes to the range [0,2^NbOfBuckets-1]\n *\n * @param str The string to calculate the hash function for\n * @return the hash value of the h'th hash function for string str\n */\n public int hash(String str){\n \t\n \tint v = HelperFunctions.posMod(MurmurHash.hash32(str, seed), nbOfBuckets);\n return v;\n \n }\n\n\n /**\n * This method will update the parameters of your model using the incoming mail.\n *\n * THIS METHOD IS REQUIRED\n *\n * @param labeledText is an incoming e-mail with a spam/ham label\n */\n @Override\n public void update(LabeledText labeledText){\n super.update(labeledText);\n \n int feature_label = labeledText.label;\n int gradient_direction;\n if (feature_label == 0) {\n gradient_direction = -1;\n feature_label = -1;\n } else {\n gradient_direction = 1;\n }\n \n int hashValue;\n\n double[] feature_vector = new double[this.nbOfBuckets];\n Set<String> feature_ngrams = labeledText.text.ngrams;\n\n for (int i = 0; i < this.nbOfBuckets; i++) {\n feature_vector[i] = 0;\n }\n \n for (String ngram: feature_ngrams) {\n hashValue = hash(ngram);\n feature_vector[hashValue] += 1;\n }\n \n double weighted_sum = 0;\n double probabilityOfSpam = 0;\n for (int feature_i = 0; feature_i < this.nbOfBuckets; feature_i ++) {\n weighted_sum += feature_vector[feature_i] * this.weights[feature_i];\n }\n weighted_sum += bias;\n \n int prediction;\n if (this.threshold != 0.0) {\n probabilityOfSpam = sigmoid_activation(weighted_sum);\n prediction = super.classify(probabilityOfSpam);\n } else {\n prediction = super.classify(weighted_sum);\n }\n //System.out.println(Double.toString(weighted_sum));\n //double probabilityOfSpam = sigmoid_activation(weighted_sum);\n \n if (prediction == 0) {\n prediction = -1;\n }\n \n double error = feature_label - prediction;\n \n this.sum_error += Math.pow(error, 2);\n double lambda = 0.01;\n int m = 1;\n // updating the weights, with an L2 penalty\n\tbias = bias + this.learningRate * error;\n double L2_regularization_penalty = 0;\n\tfor (int weight_i = 0; weight_i < this.nbOfBuckets; weight_i++) {\n L2_regularization_penalty += Math.pow(weights[weight_i], 2);\n } \n L2_regularization_penalty *= lambda / (2 * m);\n \n\tfor (int feature_i = 0; feature_i < this.nbOfBuckets; feature_i++) {\n if (this.threshold != 0.0) {\n weights[feature_i] = weights[feature_i] + this.learningRate * error * sigmoid_activation_derivative(weighted_sum) * feature_vector[feature_i];\n } else {\n weights[feature_i] = weights[feature_i] + this.learningRate * error * feature_vector[feature_i];\n }\n }\n \t\t\t\t \n }\n\n public static double sigmoid_activation(double x) {\n return (1/( 1 + Math.pow(Math.E,(-1*x))));\n }\n \n public static double sigmoid_activation_derivative(double x) {\n return (Math.pow(Math.E,(-1*x)))/Math.pow((1 + Math.pow(Math.E,(-1*x))), 2);\n }\n \n public static double linear_activation(double x) {\n return x;\n }\n \n /**\n * Uses the current model to make a prediction about the incoming e-mail belonging to class \"1\" (spam)\n * If the prediction is positive, then the e-mail is classified as spam.\n *\n * This method gives the output of the perceptron, before it is passed through the threshold function.\n *\n * THIS METHOD IS REQUIRED\n *\n * @param text is an parsed incoming e-mail\n * @return the prediction\n */\n @Override\n public double makePrediction(ParsedText text) {\n double pr = 0;\n int hashValue;\n\n double[] feature_vector = new double[this.nbOfBuckets];\n Set<String> feature_ngrams = text.ngrams;\n \n for (String ngram: feature_ngrams) {\n hashValue = hash(ngram);\n feature_vector[hashValue] += 1;\n }\n \n double weighted_sum = 0;\n for (int feature_i = 0; feature_i < this.nbOfBuckets; feature_i ++) {\n weighted_sum += feature_vector[feature_i] * this.weights[feature_i];\n }\n weighted_sum += bias;\n\n if (this.threshold != 0) {\n pr = sigmoid_activation(weighted_sum);\n } else {\n pr = weighted_sum;\n }\n return pr;\n }\n\n\n /**\n * This runs your code.\n */\n public static void main(String[] args) throws IOException {\n if (args.length < 7) {\n System.err.println(\"Usage: java PerceptronFeatureHashing <indexPath> <stopWordsPath> <logNbOfBuckets> <learningRate> <outPath> <reportingPeriod> <maxN> [-writeOutAllPredictions]\");\n throw new Error(\"Expected 7 or 8 arguments, got \" + args.length + \".\");\n }\n try {\n // parse input\n String indexPath = args[0];\n String stopWordsPath = args[1];\n int logNbOfBuckets = Integer.parseInt(args[2]);\n double learningRate = Double.parseDouble(args[3]);\n String out = args[4];\n int reportingPeriod = Integer.parseInt(args[5]);\n int n = Integer.parseInt(args[6]);\n boolean writeOutAllPredictions = args.length>7 && args[7].equals(\"-writeOutAllPredictions\");\n\n // initialize e-mail stream\n MailStream stream = new MailStream(indexPath, new EmlParser(stopWordsPath,n));\n\n // initialize learner\n PerceptronFeatureHashing perceptron = new PerceptronFeatureHashing(logNbOfBuckets, learningRate);\n\n // generate output for the learning curve\n EvaluationMetric[] evaluationMetrics = new EvaluationMetric[5]; //ADD AT LEAST TWO MORE EVALUATION METRICS\n evaluationMetrics[0] = new Accuracy();\n evaluationMetrics[1] = new Recall();\n evaluationMetrics[2] = new Precision();\n evaluationMetrics[3] = new F1Score();\n evaluationMetrics[4] = new BalancedAccuracy();\n perceptron.makeLearningCurve(stream, evaluationMetrics, out+\".pfh\", reportingPeriod, writeOutAllPredictions);\n\n } catch (FileNotFoundException e) {\n System.err.println(e.toString());\n }\n }\n\n /*public void applyWeightConstraint(double weightConstraint) {\n double squared_length = 0;\n for(int i=0; i < inputDimension; ++i){\n squared_length += getWeight(i) * getWeight(i);\n }\n if(squared_length > weightConstraint){\n double ratio = Math.sqrt(weightConstraint / squared_length);\n for(int i=0; i < inputDimension; ++i) {\n setWeight(i, getWeight(i) * ratio);\n }\n }\n }*/\n\n}\n"
},
{
"alpha_fraction": 0.5101796388626099,
"alphanum_fraction": 0.5179640650749207,
"avg_line_length": 29.907407760620117,
"blob_id": "ed56a31db48fa91613ba9a11fec32f2b05bb7073",
"content_id": "284b9f61cf279c1eeea354c4cd8d4dfbe3d6ecfd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1670,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 54,
"path": "/code/metric_plotter.py",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n@author: VictorGueorguiev\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport glob\n\ndef main():\n data_path = '..\\\\.\\\\output\\\\OUT\\\\PLOT\\\\'\n models = {'pfh': 'Perceptron FH',\n 'pcms': 'Perceptron PCMS',\n 'nbfh': 'Naive Bayes FH',\n 'nbcms': 'Naive Bayes NBCMS',\n 'adpfh': 'Enchanced Perceptron FH'}\n PLOT_COLORS = ['C'+str(i) for i in range(1, 20)]\n\n metric_names = ['acc', 'recall', 'precision', 'balancedaccuracy'] # possible are acc, f1score, recall, precision, balancedaccuracy \n plot_metric_names = ['Accuracy', 'Recall', 'Precision', 'Balanced Accuracy']\n fig, axs = plt.subplots(2, 2)\n axs = axs.flatten()\n i = 0\n for metric_name in metric_names:\n ax = axs[i]\n plot_color = 0\n for file_name in glob.glob(data_path + '*.' + metric_name):\n model_name = file_name.split(data_path)[1].split('.')[1]\n model_name = models[model_name]\n plot_df = pd.read_csv(file_name, sep = '\\t')\n plot_df.columns = ['training_samples', 'metric_name']\n \n ax.plot(plot_df.training_samples, \n plot_df.metric_name, \n color = PLOT_COLORS[plot_color],\n #marker = 'o',\n linestyle = '-',\n label = model_name)\n plot_color += 1\n ax.set_xlabel('No. Training Samples')\n ax.set_ylabel(plot_metric_names[i])\n ax.legend(loc=\"lower right\")\n i += 1\n plt.legend()\n plt.show()\n\n \n\n \n \n \nif __name__ == \"__main__\":\n main()\n\n"
},
{
"alpha_fraction": 0.5832988619804382,
"alphanum_fraction": 0.5939569473266602,
"avg_line_length": 34.14181900024414,
"blob_id": "e9a67641701c68223532d1888901746dfcf8ce2f",
"content_id": "6a5c8d65bab9ae0832328e385e2a06fe229579b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 9666,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 275,
"path": "/code/src/NaiveBayesCountMinSketch.java",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "/**\n * Copyright (c) DTAI - KU Leuven – All rights reserved.\n * Proprietary, do not copy or distribute without permission.\n * Written by Jessa Bekker and Pieter Robberechts, 2020\n */\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.Set;\nimport java.util.Arrays;\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * This class is a stub for naive Bayes with count-min sketch\n */\npublic class NaiveBayesCountMinSketch extends OnlineTextClassifier{\n\n private int nbOfHashes;\n private int logNbOfBuckets;\n private int[][] hashAB; //hashAB[h][0] and hashAB[h][1] are the resp. constants 'a' and 'b' used in universal hashing for the h'th hash function. \n\n private int[][][] counts; // counts[c][h][i]: The count of n-grams in e-mails of class c (spam: c=1)\n // that hash to value i for the h'th hash function.\n private int[] classCounts; //classCounts[c] the count of e-mails of class c (spam: c=1)\n private int[] ngramCounts; //ngramCounts[c] the count of ngrams of class c (spam: c=1)\n private int nbOfBuckets;\n private int prime;\n private int seed;\n \n /* FILL IN HERE */\n\n /**\n * Initialize the naive Bayes classifier\n *\n * THIS CONSTRUCTOR IS REQUIRED, DO NOT CHANGE THE HEADER\n * You can write additional constructors if you wish, but make sure this one works\n *\n * This classifier uses the count-min sketch to estimate the conditional counts of the n-grams\n *\n * @param nbOfHashes The number of hash functions in the count-min sketch\n * @param logNbOfBuckets The hash functions hash to the range [0,2^NbOfBuckets-1]\n * @param threshold The threshold for classifying something as positive (spam). Classify as spam if Pr(Spam|n-grams)>threshold)\n */\n public NaiveBayesCountMinSketch(int nbOfHashes, int logNbOfBuckets, double threshold){\n this.nbOfHashes = nbOfHashes;\n this.logNbOfBuckets=logNbOfBuckets;\n this.threshold = threshold;\n this.prime = Primes.findLeastPrimeNumber(this.nbOfBuckets);\n \tthis.seed = (int) Math.random() * 1000;\n \n this.nbOfBuckets =((int) Math.pow(2, logNbOfBuckets));\n\n this.counts = new int[2][this.nbOfHashes][this.nbOfBuckets];\n this.classCounts = new int[2];\n \n // Init hashAB\n \thashAB = new int[this.nbOfHashes][2];\n \tRandom rand = new Random();\n \tfor (int i = 0; i < this.nbOfHashes; i++) {\n \t\thashAB[i][0] = rand.nextInt(this.prime - 1) + 1; // a != 0\n \t\thashAB[i][1] = rand.nextInt(this.prime);\n \t}\n \t\n \t// Init counts\n \tcounts = new int[2][nbOfHashes][nbOfBuckets];\n \tfor (int c = 0; c < 2; c++)\n \t\tfor (int h = 0; h < nbOfHashes; h++)\n \t\t\tfor (int i = 0; i < nbOfBuckets; i++)\n \t\t\t\tcounts[c][h][i] = 1;\n \n // Init ngramCounts\n \tngramCounts = new int[2];\n \tngramCounts[0] = nbOfBuckets;\n \tngramCounts[1] = nbOfBuckets;\n \t\n \t// Init classCounts\n \tclassCounts = new int[2];\n \tclassCounts[0] = 1;\n \tclassCounts[1] = 1;\n }\n\n /**\n * Calculate the hash value of the h'th hash function for string str\n *\n * THIS METHOD IS REQUIRED\n *\n * The hash function hashes to the range [0,2^NbOfBuckets-1]\n * This method should work for h in the range [0, nbOfHashes-1]\n *\n * @param str The string to calculate the hash function for\n * @param h The number of the hash function to use.\n * @return the hash value of the h'th hash function for string str\n */\n private int hash(String str, int h){\n int v;\n\n if (h < 0 || h >= nbOfBuckets){\n \tv = -1; // will cause system exception OutOfBounds\n \tSystem.out.println(\"Failure in NB CMS hash(): h out of range\");\n } else {\n \t\n \tint x = MurmurHash.hash32(str, seed);\n \tint a = hashAB[h][0];\n \tint b = hashAB[h][1];\n \t\n \tint y = HelperFunctions.posMod(a*x + b, prime);\n \tv = HelperFunctions.posMod(y, nbOfBuckets);\n \t\n }\n \t\n\n return v;\n }\n /**\n * This method will update the parameters of your model using the incoming mail.\n *\n * THIS METHOD IS REQUIRED\n *\n * @param labeledText is an incoming e-mail with a spam/ham label\n */\n @Override\n public void update(LabeledText labeledText){\n super.update(labeledText);\n\n int feature_label = labeledText.label;\n \n // update classCounts\n classCounts[feature_label]++;\n \n // update ngramCounts\n ngramCounts[feature_label] += labeledText.text.ngrams.size();\n \n // update counts\n for (String ngram : labeledText.text.ngrams)\n \tfor (int h = 0; h < nbOfHashes; h++)\n \t\tcounts[feature_label][h][hash(ngram,h)]++;\n \n }\n\n\n /**\n * Uses the current model to make a prediction about the incoming e-mail belonging to class \"1\" (spam)\n * The prediction is the probability for the e-mail to be spam.\n * If the probability is larger than the threshold, then the e-mail is classified as spam.\n *\n * THIS METHOD IS REQUIRED\n *\n * @param text is an parsed incoming e-mail\n * @return the prediction\n */\n @Override\n public double makePrediction(ParsedText text) {\n double pr = 0.0;\n \n List<String> ngramList = new ArrayList<String>(text.ngrams);\n\n // minCount[c][ngram] is the minimum count over all hash functions given class c and ngram\n int[][] minCount = new int[2][ngramList.size()];\n for (int i = 0; i < ngramList.size(); i++) {\n \t\n \tString ngram = ngramList.get(i);\n \tint[] min = getMinCount(ngram);\n \tminCount[0][i] = min[0];\n \tminCount[1][i] = min[1];\n \t\n }\n \n // from this point, similar to Feature Hashing\n double logJPDSpam = logJointProb(minCount[1],1);\n double logJPDHam = logJointProb(minCount[0],0);\n \n double logPr = logJPDSpam - HelperFunctions.logSum(logJPDSpam,logJPDHam);\n \n // Convert logPr to pr\n pr = Math.exp(logPr);\n \n // Testing\n if (pr < 0 || pr > 1)\n \tSystem.out.println(\"FAILURE IN NB-CMS makePrediction(): pr = \" + pr);\n \n \n \n return pr;\n }\n\n /**\n * Calculates the minimum count of ngram for both spam and ham.\n * @param ngram\n * @return An array with 2 elements, one minimum count for each class (ham and spam).\n */\n private int[] getMinCount(String ngram) {\n \tint[] min = new int[2];\n \tmin[0] = ngramCounts[0];\n \tmin[1] = ngramCounts[1];\n \t\n \tfor (int h = 0; h < nbOfHashes; h++) {\n \t\tint hashValue = hash(ngram,h);\n \t\tint countHam = counts[0][h][hashValue];\n \t\tint countSpam = counts[1][h][hashValue];\n \t\t\n \t\tif (min[0] > countHam)\n \t\t\tmin[0] = countHam;\n \t\t\n \t\tif (min[1] > countSpam)\n \t\t\tmin[1] = countSpam;\n \t\t\n \t}\n\n \treturn min;\n }\n \n /**\n * Calculates the log of the joint prob. distribution P(Text, Class = c)\n * @param text\n * @param c\n * @return\n */\n public double logJointProb(int[] minCount, int c) {\n double result = 0;\n \n // ln(Pr[Text = given set of n-grams | S = c])\n for (int count : minCount) {\n // Note that probability P[ngram|c] = minCounts[ngram] / ngramCounts[c]\n \tresult += Math.log((double) count);\n }\n result -= minCount.length * Math.log((double) ngramCounts[c]);\n \n // ln(Pr[S = c])\n result += Math.log(classCounts[c]) - HelperFunctions.logSum(Math.log(classCounts[0]), Math.log(classCounts[1]));\n \t\n \n return result;\n \t\n }\n /**\n * This runs your code.\n */\n public static void main(String[] args) throws IOException {\n if (args.length < 8) {\n System.err.println(\"Usage: java NaiveBayesCountMinSketch <indexPath> <stopWordsPath> <logNbOfBuckets> <nbOfHashes> <threshold> <outPath> <reportingPeriod> <maxN> [-writeOutAllPredictions]\");\n throw new Error(\"Expected 8 or 9 arguments, got \" + args.length + \".\");\n }\n try {\n // parse input\n String indexPath = args[0];\n String stopWordsPath = args[1];\n int logNbOfBuckets = Integer.parseInt(args[2]);\n int nbOfHashes = Integer.parseInt(args[3]);\n double threshold = Double.parseDouble(args[4]);\n String out = args[5];\n int reportingPeriod = Integer.parseInt(args[6]);\n int n = Integer.parseInt(args[7]);\n boolean writeOutAllPredictions = args.length>8 && args[8].equals(\"-writeOutAllPredictions\");\n\n // initialize e-mail stream\n MailStream stream = new MailStream(indexPath, new EmlParser(stopWordsPath,n));\n\n // initialize learner\n NaiveBayesCountMinSketch nb = new NaiveBayesCountMinSketch(nbOfHashes ,logNbOfBuckets, threshold);\n\n // generate output for the learning curve\n EvaluationMetric[] evaluationMetrics = new EvaluationMetric[5]; //ADD AT LEAST TWO MORE EVALUATION METRICS\n evaluationMetrics[0] = new Accuracy();\n evaluationMetrics[1] = new Recall();\n evaluationMetrics[2] = new Precision();\n evaluationMetrics[3] = new F1Score();\n evaluationMetrics[4] = new BalancedAccuracy();\n nb.makeLearningCurve(stream, evaluationMetrics, out+\".nbcms\", reportingPeriod, writeOutAllPredictions);\n\n } catch (FileNotFoundException e) {\n System.err.println(e.toString());\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6931408047676086,
"alphanum_fraction": 0.6985559463500977,
"avg_line_length": 36.559322357177734,
"blob_id": "257f7b153d3b43723c7ba0de1d342034fedff432",
"content_id": "b41f8c6671df77b98a62c48772d01b4cb00dfab0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 4432,
"license_type": "no_license",
"max_line_length": 180,
"num_lines": 118,
"path": "/code/Makefile",
"repo_name": "BrutishGuy/BDAPAssignment3",
"src_encoding": "UTF-8",
"text": "##\n## Makefile\n##\n## Pieter Robberechts\n## Nov 2018\n## \n\n\n# Experiment parameters ######################################################\n\nSMALL_DATA=../data/dataSubset/index_small\nSMALL_PERIOD=100\nSMALL_OUT=small\n\nDATA=/cw/bdap/retake1/Data/index\nPERIOD=1000\nOUT=out\n\nSTOPWORDS=./stop-word-list_stanford.txt\n\nMAX_N=2\nLOG_NB_BUCKETS=20\nNB_HASHES=10\nTHRESHOLD=0.5\nLEARNING_RATE=0.0001\n# Compilation ###############################################################\n\n## Locate directories\nclass_d=bin\nlib_d=lib\nsource_d=src\n\n# Compilation stuff\nJAVAC=javac\nJFLAGS=-g -d $(class_d) -sourcepath $(source_d) -Xlint:all\n\nclasspath:=$(class_d):$(lib_d)/javax.mail.jar\n# If there's already a CLASSPATH, put it on the front\nifneq ($(CLASSPATH),)\n classpath:= $(CLASSPATH):$(classpath)\nendif\n# Re-export the CLASSPATH.\nexport CLASSPATH:=$(classpath)\n\n.SUFFIXES: .java .class\n.PHONY: clean all\n\n$(class_d)/%.class: $(source_d)/%.java\n\t@echo \"JAVAC $<\"\n\t@$(JAVAC) $(JFLAGS) $<\n\nPROG= \\\n\t\t\tNaiveBayesFeatureHashing.class \\\n\t\t\tNaiveBayesCountMinSketch.class \\\n\t\t\tPerceptronFeatureHashing.class \\\n\t\t\tPerceptronCountMinSketch.class \\\n\t\t\tAdjustedPerceptronFeatureHashing.class\nLIST=$(addprefix $(class_d)/, $(PROG))\n\t\nall: $(class_d) $(LIST) \n\n$(class_d):\n\tmkdir $(class_d)\n\nclean:\n\trm -rf $(class_d)/*\n\n# Experiments ################################################################\n\nnbfh_small: $(class_d)/NaiveBayesFeatureHashing.class\n\t@echo \"Testing naive Bayes with feature hashing on a subset of the data\"\n\trm -f $(SMALL_OUT).nbfh.*\n\ttime java NaiveBayesFeatureHashing $(SMALL_DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(THRESHOLD) $(SMALL_OUT) $(SMALL_PERIOD) $(MAX_N) -writeOutAllPredictions\n\nnbfh: $(class_d)/NaiveBayesFeatureHashing.class\n\t@echo \"Testing naive Bayes with feature hashing on the complete data\"\n\trm -f $(OUT).nbfh.*\n\ttime java NaiveBayesFeatureHashing $(DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(THRESHOLD) $(OUT) $(PERIOD) $(MAX_N)\n\nnbcms_small: $(class_d)/NaiveBayesCountMinSketch.class\n\t@echo \"Testing naive Bayes with count-min sketch on a subset of the data\"\n\trm -f $(SMALL_OUT).nbcms.*\n\ttime java NaiveBayesCountMinSketch $(SMALL_DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(NB_HASHES) $(THRESHOLD) $(SMALL_OUT) $(SMALL_PERIOD) $(MAX_N) -writeOutAllPredictions\n\nnbcms: $(class_d)/NaiveBayesCountMinSketch.class\n\t@echo \"Testing naive Bayes with count-min sketch on the complete data\"\n\trm -f $(OUT).nbcms.*\n\ttime java NaiveBayesCountMinSketch $(DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(NB_HASHES) $(THRESHOLD) $(OUT) $(PERIOD) $(MAX_N)\n\npfh_small: $(class_d)/PerceptronFeatureHashing.class\n\t@echo \"Testing perceptron classification with feature hashing on a subset of the data\"\n\trm -f $(SMALL_OUT).pfh.*\n\ttime java PerceptronFeatureHashing $(SMALL_DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(LEARNING_RATE) $(SMALL_OUT) $(SMALL_PERIOD) $(MAX_N) -writeOutAllPredictions\n\npfh: $(class_d)/PerceptronFeatureHashing.class\n\t@echo \"Testing perceptron classification with feature hashing on the complete data\"\n\trm -f $(OUT).pfh.*\n\ttime java PerceptronFeatureHashing $(DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(LEARNING_RATE) $(OUT) $(PERIOD) $(MAX_N)\n\npcms_small: $(class_d)/PerceptronCountMinSketch.class\n\t@echo \"Testing perceptron classification with count-min sketch on a subset of the data\"\n\trm -f $(SMALL_OUT).pcms.*\n\ttime java PerceptronCountMinSketch $(SMALL_DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(NB_HASHES) $(LEARNING_RATE) $(SMALL_OUT) $(SMALL_PERIOD) $(MAX_N) -writeOutAllPredictions\n\npcms: $(class_d)/PerceptronCountMinSketch.class\n\t@echo \"Testing perceptron classification with count-min sketch on the complete data\"\n\trm -f $(OUT).pcms.*\n\ttime java PerceptronCountMinSketch $(DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(NB_HASHES) $(LEARNING_RATE) $(OUT) $(PERIOD) $(MAX_N)\n\nadpfh_small: $(class_d)/AdjustedPerceptronFeatureHashing.class\n\t@echo \"Testing enchanched perceptron classification with feature hashing on a subset of the data\"\n\trm -f $(SMALL_OUT).adpfh.*\n\ttime java AdjustedPerceptronFeatureHashing $(SMALL_DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(THRESHOLD) $(LEARNING_RATE) $(SMALL_OUT) $(SMALL_PERIOD) $(MAX_N) -writeOutAllPredictions\n\nadpfh: $(class_d)/AdjustedPerceptronFeatureHashing.class\n\t@echo \"Testing perceptron classification with count-min sketch on the complete data\"\n\trm -f $(OUT).adpfh.*\n\ttime java AdjustedPerceptronFeatureHashing $(DATA) $(STOPWORDS) $(LOG_NB_BUCKETS) $(THRESHOLD) $(LEARNING_RATE) $(OUT) $(PERIOD) $(MAX_N)\n"
}
] | 9 |
ztlevi/pytest-dap-mode-test
|
https://github.com/ztlevi/pytest-dap-mode-test
|
6cc2e9265b526519eb5e9c43a4155aa62be63ea8
|
a273b3610ef32619fdd601c8a3f6d0cc70208be1
|
29a4512378f34f8d6acff65b811a61f5cbeb9187
|
refs/heads/master
| 2020-09-03T00:10:21.854561 | 2019-11-17T09:32:50 | 2019-11-17T09:32:50 | 219,337,899 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6815510988235474,
"alphanum_fraction": 0.6991774439811707,
"avg_line_length": 18.79069709777832,
"blob_id": "28bb687412f992332c1d8020b04669acbdd3e23e",
"content_id": "3374f502b20292e1c980c15312c0437b28b2d3ff",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 851,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 43,
"path": "/README.md",
"repo_name": "ztlevi/pytest-dap-mode-test",
"src_encoding": "UTF-8",
"text": "# Dap mode pytest test project\n\nMake sure you have pytest installed. Python3 is used in this project, so you can install pytest via `python3 -m pip install pytest`\n\n## Emacs config\n\nEmacs's config is under `{root}/config.el`.\n\nYou might need to set `dap-python-executable to python3`\n\n## Reproduce\n\n### python run\n\n- In emacs\n\n 1. toggle dap breakpoint on `main.py` line 4.\n 2. dap-debug -> My app\n\n Working but the compilation buffer (server log) will disappear.\n\n- In vscode\n\n 1. toggle breakpoint on `main.py` line 4.\n 2. Select `python main` in the debug panel and run.\n\n Working.\n\n### pytest run\n\n- In emacs\n\n 1. toggle dap breakpoint on `test/test_app.py` line 7\n 2. dap-debug -> My app\n\n Not working\n\n- In vscode\n\n 1. toggle breakpoint on `test/test_app.py` line 7\n 2. Select `pytest test_app` in the debug panel and run.\n\n Working\n"
},
{
"alpha_fraction": 0.4852941036224365,
"alphanum_fraction": 0.5588235259056091,
"avg_line_length": 12.600000381469727,
"blob_id": "1930a2b25fc39c714368d746f935dc901ce423eb",
"content_id": "c73d7dcdc7db1ccf17f965181b243a778fc93c3f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 68,
"license_type": "permissive",
"max_line_length": 22,
"num_lines": 5,
"path": "/main.py",
"repo_name": "ztlevi/pytest-dap-mode-test",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n\nfor i in range(100):\n a = 1\n print(i)\n"
}
] | 2 |
xmunoz/beaconinsidechallenge
|
https://github.com/xmunoz/beaconinsidechallenge
|
9376d26e5a5930c2e8954a97083f112d1073b1cb
|
3956c4438edbd06ee0abacd540382927cd241167
|
7d839720cb004a2cf01e8a4518d510322e39b5e3
|
refs/heads/master
| 2021-06-26T12:19:32.027962 | 2016-12-03T12:55:54 | 2016-12-03T12:55:54 | 37,209,936 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7508090734481812,
"alphanum_fraction": 0.754045307636261,
"avg_line_length": 24.75,
"blob_id": "21b1710b57ad1e8df9155dc394c22e0a5708d676",
"content_id": "ee12d2f22d023639200f5108a62b06516ff57d9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 309,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 12,
"path": "/caesar.wsgi",
"repo_name": "xmunoz/beaconinsidechallenge",
"src_encoding": "UTF-8",
"text": "import os\nimport sys\n\nAPP_HOME = \"/home/cristina/public/xmunoz/main/web/caesar\"\n\nactivate_this = os.path.join(APP_HOME, \"venv_caesar/bin/activate_this.py\")\nexecfile(activate_this, dict(__file__=activate_this))\n\nsys.path.insert(0, APP_HOME)\nos.chdir(APP_HOME)\n\nfrom crypto_app.routes import app as application\n"
},
{
"alpha_fraction": 0.7451274394989014,
"alphanum_fraction": 0.7481259107589722,
"avg_line_length": 50.30769348144531,
"blob_id": "ab1cbf1b82cd6123055ef5ad53c19871be4f3bda",
"content_id": "3e7a56789128d3d253b04f597af1f737578706f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 667,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 13,
"path": "/README.md",
"repo_name": "xmunoz/beaconinsidechallenge",
"src_encoding": "UTF-8",
"text": "## [caesar](https://www.xmunoz.com/encryption)\nEncrypt and decrypt a string using a [Caesar Cipher](https://en.wikipedia.org/wiki/Caesar_cipher)!\n\n## CLI Usage\n\nThe Caesar Cipher tool can also be used as a command line tool, with a configurable shift value. Currently the shift is hard-coded to 3. Usage:\n\n python crypto_app/caesar.py encrypt 'foo bar!' # outputs CLL YXO!\n python crypto_app/caesar.py decrypt 'cll yxo!' # outputs FOO BAR!\n\n## Web Usage\nThe web interface is a simple flask app with 3 endpoints: the home page, /encrypt and /decrypt.\n\n"
}
] | 2 |
webis-de/acl20-efficient-argument-quality-annotation
|
https://github.com/webis-de/acl20-efficient-argument-quality-annotation
|
4a8e0d64a101892a4a1e92af9e79d00b5fe5fbe8
|
2e93b5850eb22e76f7ed1a02d8148fc225f600fa
|
8e1b7ec7ae7a8979c90bb21b8666d4936e55a88d
|
refs/heads/master
| 2022-06-19T22:01:04.945347 | 2020-05-01T10:20:09 | 2020-05-01T10:20:09 | 257,583,164 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5148704648017883,
"alphanum_fraction": 0.518551230430603,
"avg_line_length": 86.07691955566406,
"blob_id": "988219b92ae3968fa9efc0463798822cef9af08d",
"content_id": "89edb3507bc08d86128e6a158a73bc4a47a1090d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6792,
"license_type": "no_license",
"max_line_length": 429,
"num_lines": 78,
"path": "/Readme.md",
"repo_name": "webis-de/acl20-efficient-argument-quality-annotation",
"src_encoding": "UTF-8",
"text": "# Paper: Efficient Pairwise Annotation of Argument Quality\n\nThis is the data and code for the paper Efficient Pairwise Annotation of Argument Quality.\n\nLukas Gienapp, Benno Stein, Matthias Hagen and Martin Potthast\n\n @InProceedings{gienapp:2020,\n author = {Gienapp, Lukas and Stein, Benno and Hagen, Matthias and Potthast, Martin},\n booktitle = {The 58th annual meeting of the Association for Computational Linguistics (ACL) },\n month = jul,\n publisher = {ACL},\n site = {Seattle, USA},\n title = {{Efficient Pairwise Annotation of Argument Quality}},\n year = 2020\n }\n-----------------------------------------------\n## Webis-ArgQuality-20 Corpus\nThe Webis-ArgQuality-20 corpus consists of two sets of data: a processed version, where for each annotated argument, a scalar value for each argument quality dimension is derived; and the raw annotation data, providing the individual paired comparison labels. The structure of both datasets is described below. \n\n### [Processed Data](./Webis-ArgQuality-20-Full)\nThe dataset is split into three different tables. Each key represents a column name, with details about the contained data in the explanation field. Primary keys are marked in **bold**. If a combined key is used, all entries that the combined key is composed of are marked. Foreign keys that can be used to reference other tables are marked in *italics*.\n###### Argument Dataset\n| Key | Explanation |\n|---------------------|---------------------------------------------------------------------------------------------------|\n| ***Topic ID*** | Unique identifier for the topic context the item was judged in |\n| **Argument ID** | Unique identifier for the item in regards to the discussion it is part of |\n| **Discussion ID** | Unique identifier of the discussion the item is part of |\n| Is Argument? | Boolean value, indicating wether the item is an argument, or not |\n| Stance | Denotes the stance of the item, can be Pro, Con or Not specified |\n| Relevance | Relevance score, z-normalised \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t |\n| Logical Quality | Logical quality score, z-normalised \t\t\t\t\t\t\t\t\t\t\t\t\t\t |\n| Rhetorical Quality | Rhetorical quality score, z-normalised \t\t\t\t\t\t\t\t\t\t\t\t\t\t |\n| Dialectical Quality | Dialectical quality score, z-normalised \t\t\t\t\t\t\t\t\t\t\t\t\t |\n| Combined Quality \t | Combined quality score, z-normalised \t\t\t\t\t\t\t\t\t\t\t\t\t \t |\n| Premise | Text of the items' premise |\n| Text Length | Word Count of the premise |\n\n###### Ranking Dataset\n| Key | Explanation |\n|-------------------|-------------------------------------------------------------------------------|\n| ***Topic ID*** | Unique identifier for the topic context |\n| **Model** | Name of the model the ranking this entry stems from was obtained with |\n| **Rank** | The rank of the argument in the respective engines ranking |\n| *Argument ID* | Unique identifier for the argument in regards to the discussion it is part of |\n| *Discussion ID* | Unique identifier of the discussion the argument is part of |\n\n###### Topic Dataset\n| Key | Explanation |\n|---------------------------|-------------------------------------------------------------------|\n| ***Topic ID*** | Unique identifier for the topic |\n| Category | Thematical category the topic belongs to |\n| Long Query | Long query, used as input for the retrieval models |\n| Short Query | Shortened form of the query \t\t\t\t\t\t|\n\n### [Raw Data](./Webis-ArgQuality-20-Raw)\nIndividual comparisons for argument quality are given in a dedicated table each. Relevance annotations are included as well. Each key represents a column name, with details about the contained data in the explanation field. Primary keys are marked in **bold**. If a combined key is used, all entries that the combined key is composed of are marked. Foreign keys that can be used to reference other tables are marked in *italics*.\n\n###### Quality Annotations\n\n| Key | Explanation |\n|---------------------------|-----------------------------------------------------------------------|\n| ***Argument ID A*** | Unique identifier for argument A in regards to the discussion it is part of |\n| ***Discussion ID A*** | Unique identifier of the discussion argument A is part of |\n| ***Argument ID B*** | Unique identifier for argument B in regards to the discussion it is part of |\n| ***Discussion ID B*** | Unique identifier of the discussion argument B is part of |\n| Comparison | Denotes the direction of the comparison; can be \"A\" if argument A is better, \"B\" if argument B is better, of \"Tie\", if both arguments are equal. |\n\n###### Relevance Annotations\n| Key | Explanation |\n|---------------------------|-----------------------------------------------------------------------|\n| ***Task ID*** | ID of the annotation task this annotation was part of. |\n| ***Argument ID*** | Unique identifier for the argument in regards to the discussion it is part of |\n| ***Discussion ID*** | Unique identifier of the discussion the argument is part of |\n| Relevance | Denotes the relevance of this argument with regards to the topic on a scale of 0 (low) to 4 (high). -2 is used to mark irrelevant text. |\n| Is Argument? | Boolean value, indicating wether the item is an argument, or not |\n\n### [Model Implementation](./Webis-ArgQuality-20-Model)\nA Python implementation is included. See code comments for additional implementation details. Also, an example describing the usage of the model is given, and can be applied to the `Webis-ArgQuality-20-Raw`data to derive the processed version.\n"
},
{
"alpha_fraction": 0.5648482441902161,
"alphanum_fraction": 0.5722776651382446,
"avg_line_length": 36.38888931274414,
"blob_id": "e48238b816c12ae547b51c7964bf07747a140ef5",
"content_id": "9701cadc1abf66b8a46f6bae66364bb9960fc066",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4711,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 126,
"path": "/Webis-ArgQuality-20-Model/bradleyterry.py",
"repo_name": "webis-de/acl20-efficient-argument-quality-annotation",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom scipy.optimize import minimize\n\nclass BradleyTerry:\n def __init__(self, comparisons, parsefunc = None):\n \"\"\"\n Constructor\n :param comparisons: list of comparisons\n :param parsefunc: optionally pass a custom parsign function to cope with different data formats\n \"\"\"\n parsefunc = parsefunc if parsefunc is not None else self.__parsefunc__\n self.items, self.comparisons, self.merits = parsefunc(comparisons)\n\n @staticmethod\n def __parsefunc__(comparisons) -> tuple:\n \"\"\"\n Function to parse supplied comparison data to the format needed by the model\n :param comparisons: comparison data\n :return\n \"\"\"\n items = list(set([x[0] for x in comparisons]+[x[1] for x in comparisons]))\n \n # Mapping\n items_parsed = {x: i for i, x in enumerate(items)}\n\n # Mapped comparisons\n comparisons_parsed = []\n for arg1_id, arg2_id, tie in comparisons:\n comparisons_parsed.append([\n items_parsed[arg1_id],\n items_parsed[arg2_id],\n tie\n ])\n\n # Initialize zero-vector for merits\n merits = np.zeros(len(items))\n\n return (items_parsed, comparisons_parsed, merits)\n\n @staticmethod\n def __pfunc__(i: float, j: float, t: float) -> float:\n \"\"\"\n Function to compute pairwise comparison probabilities of non-ties\n :param i: merit of the winning item\n :param j: merit of the loosing item\n :param s: annotation quality score\n :param t: difference threshold\n :return: propability of item i beating item j\n \"\"\"\n p = np.exp(i) / (np.exp(i) + np.exp(j) * np.exp(t))\n return np.log10(p)\n\n @staticmethod\n def __tfunc__(i: float, j: float, t: float) -> float:\n \"\"\"\n Function to compute pairwise comparison probabilities of ties\n :param i: merit of the winning item\n :param j: merit of the loosing item\n :param t: difference threshold\n :return: propability of item i beating item j\n \"\"\"\n f1 = np.exp(i) * np.exp(j) * (np.square(np.exp(t)) - 1)\n f2 = (np.exp(i) + np.exp(j) * np.exp(t)) * (np.exp(i) * np.exp(t) + np.exp(j))\n p = f1 / f2\n return np.log10(p)\n\n def __rfunc__(self, i: float, l: float) -> float:\n \"\"\"\n Function to compute regularized probability\n :param i: item merit\n :param l: regularization factor\n :return: value of __pfunc__ for matches with dummy item weighted by l\n \"\"\"\n return l * (self.__pfunc__(i, 1, 0) + self.__pfunc__(1, i, 0))\n\n def __log_likelihood__(self, merits: np.ndarray) -> float:\n \"\"\"\n Log-Likelihood Function\n :param merits: merit vector\n :return: log-likelihood value\n \"\"\"\n k: float = 0 # Maximization sum\n\n # Summing Edge Probabilities\n for arg1, arg2, tie in self.comparisons: \n if tie:\n k += self.__tfunc__(merits[arg1], merits[arg2], self.threshold)\n else:\n k += self.__pfunc__(merits[arg1], merits[arg2], self.threshold)\n\n # Regularization\n for x in range(len(self.items)): \n k += self.__rfunc__(merits[x], self.regularization)\n\n return -1 * k\n\n def fit(self, regularization: float = 0, threshold: float = 0) -> None:\n \"\"\"\n Optimize the model for merits\n :param regularization: regularization parameter\n :param threshold: difference threshold\n \"\"\"\n self.merits = np.ones(len(self.items))\n self.threshold = threshold\n self.regularization = regularization\n \n res = minimize(self.__log_likelihood__, self.merits, method='BFGS', options={\"maxiter\": 100})\n self.merits = res.x\n\n def get_merits(self, normalize=False) -> list:\n \"\"\"\n Returns the merits mapped to items\n :param normalize: if true, returns normalized merit vector to 0-1 range instead of original scores\n :return: dict in the form of {argument_id: merit} sorted by merits\n :exception: Exception if model was not fitted\n \"\"\"\n if not self.merits.any():\n raise Exception('Model has to be fitted first!')\n else:\n d = {argument_id: self.merits[index] for argument_id, index in self.items.items()}\n if normalize:\n mi = min(d.values())\n ma = max(d.values())\n normalize = lambda mi, ma, v: (v-mi)/(ma-mi)\n d.update({k: normalize(mi,ma,v) for k, v in d.items()})\n return sorted(d.items(), key=lambda kv: kv[1])\n"
},
{
"alpha_fraction": 0.5178571343421936,
"alphanum_fraction": 0.6289682388305664,
"avg_line_length": 33.75862121582031,
"blob_id": "2804cb43ab84b49302b7b3afa96cfc3519061551",
"content_id": "df205444be07aafb038629553b37a044655d5866",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1008,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 29,
"path": "/Webis-ArgQuality-20-Model/example.py",
"repo_name": "webis-de/acl20-efficient-argument-quality-annotation",
"src_encoding": "UTF-8",
"text": "from bradleyterry import BradleyTerry\n\n# Comparisons are given in the form of (ID_A, ID_B, Tie)\n# The order of IDs denotes the direction of the comparison. If Tie is True, the order is ignored.\n# The input format can be customized by supplying a custom parsing function to the model\ncomparisons = [\n ('A','B',False),\n ('A','C',False),\n ('A','D',False),\n ('B','C',True),\n ('B','D',False),\n ('C','B',False),\n ('C','D',False),\n ('D','A',False),\n ]\n\n# Initialize the model with given comparisons\nbt = BradleyTerry(comparisons)\n\n# Fit the model using supplied hyperparameters\nbt.fit(regularization = 0.3, threshold = 0.01)\n\n# Get the calculated merits\nprint(bt.get_merits())\n#>>> [('D', 0.32692689118596696), ('B', 0.7570454645168428), ('C', 1.2429546060392827), ('A', 1.673073287350478)]\n\n# Merits can be normalized to the 0-1 range\nprint(bt.get_merits(normalize=True))\n#>>> [('D', 0.0), ('B', 0.3195185203522548), ('C', 0.680481543344691), ('A', 1.0)]\n"
}
] | 3 |
nikitarredline/stepic_course
|
https://github.com/nikitarredline/stepic_course
|
c5a389a1a9f2ccc26c3e5675c1748cc4fb75cf28
|
a0be0453ca9828a2b6a4bd3ebc98761b0a627e85
|
db5ea791a60743dd9b508ae391203d950b9960e6
|
refs/heads/master
| 2021-06-16T18:57:45.122795 | 2019-07-24T17:42:51 | 2019-07-24T17:42:51 | 198,680,057 | 0 | 0 | null | 2019-07-24T17:22:03 | 2019-07-24T17:42:53 | 2021-04-20T18:18:19 |
Python
|
[
{
"alpha_fraction": 0.701886773109436,
"alphanum_fraction": 0.704150915145874,
"avg_line_length": 43.75862121582031,
"blob_id": "627f83f36339cfdf20964623ecfae05451908b54",
"content_id": "fd2d00b02efc462508d521722f4796f93aeabf6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1325,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 29,
"path": "/pages/locators.py",
"repo_name": "nikitarredline/stepic_course",
"src_encoding": "UTF-8",
"text": "from selenium.webdriver.common.by import By\r\n\r\nclass BasePageLocators(object):\r\n\tLOGIN_LINK = (By.CSS_SELECTOR, \"#login_link\")\r\n\tLOGIN_LINK_INVALID = (By.CSS_SELECTOR, \"#login_link_inc\")\r\n\tCART_LINK = (By.CSS_SELECTOR, \".btn-group .btn-default:nth-child(1)\")\r\n\tUSER_ICON = (By.CSS_SELECTOR, \".icon-user\")\r\n\r\nclass MainPageLocators(object):\r\n\tLOGIN_LINK = (By.CSS_SELECTOR, \"#login_link\")\r\n\r\nclass LoginPageLocators(object):\r\n\tLOGIN_FORM = (By.CSS_SELECTOR, \"#login_form\")\r\n\tREGISTER_FORM = (By.CSS_SELECTOR, \"#register_form\")\r\n\tREGISTER_EMAIL = (By.CSS_SELECTOR, \"#id_registration-email\")\r\n\tREGISTER_PASSWORD = (By.CSS_SELECTOR, \"#id_registration-password1\")\r\n\tREGISTER_CONFIRM_PASSWORD = (By.CSS_SELECTOR, \"#id_registration-password2\")\r\n\tREGISTER_SUBMIT = (By.CSS_SELECTOR, \"[name='registration_submit']\")\r\n\r\nclass ProductPageLocators(object):\r\n\tADD_TO_CART_LINK = (By.CSS_SELECTOR, \".btn-add-to-basket\")\r\n\tPAGE_PRODUCT_NAME = (By.CSS_SELECTOR, \".product_main h1\")\r\n\tPAGE_PRODUCT_PRICE = (By.CSS_SELECTOR, \".product_main .price_color\")\r\n\tCART_PRODUCT_NAME = (By.CSS_SELECTOR, \"#messages div:nth-child(1) div strong\")\r\n\tCART_PRODUCT_PRICE = (By.CSS_SELECTOR, \".alert-info .alertinner strong\")\r\n\r\nclass CartPageLocators(object):\r\n\tITEMS_LINK = (By.CSS_SELECTOR, \".basket-items\")\r\n\tEMPTY_CART_TEXT = (By.CSS_SELECTOR, \"#content_inner p\")"
},
{
"alpha_fraction": 0.4830188751220703,
"alphanum_fraction": 0.6679245233535767,
"avg_line_length": 15.800000190734863,
"blob_id": "a94f75e43011d0f8ee93fb137186b419a15ec6c3",
"content_id": "53e2ba0a66d9ed942ab7da2bc91c15011bdfba41",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 15,
"path": "/requirements.txt",
"repo_name": "nikitarredline/stepic_course",
"src_encoding": "UTF-8",
"text": "atomicwrites==1.3.0\r\nattrs==19.1.0\r\ncolorama==0.4.1\r\nimportlib-metadata==0.18\r\nmore-itertools==7.1.0\r\npackaging==19.0\r\npluggy==0.12.0\r\npy==1.8.0\r\npyparsing==2.4.0\r\npytest==3.10.1\r\npytest-rerunfailures==3.1\r\nselenium==3.13.0\r\nsix==1.12.0\r\nwcwidth==0.1.7\r\nzipp==0.5.1"
},
{
"alpha_fraction": 0.6968854069709778,
"alphanum_fraction": 0.6968854069709778,
"avg_line_length": 44.10256576538086,
"blob_id": "43b9bcbecdf3aea977c6f2c2f189bc3ef744fc34",
"content_id": "1cf6d81730a4523cacf68b9db59a6b1af6c2029a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1798,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 39,
"path": "/pages/product_page.py",
"repo_name": "nikitarredline/stepic_course",
"src_encoding": "UTF-8",
"text": "from .base_page import BasePage\r\nfrom .locators import ProductPageLocators\r\n\r\n\r\nclass ProductPage(BasePage):\r\n def add_product_to_cart(self):\r\n cart_link = self.browser.find_element(*ProductPageLocators.ADD_TO_CART_LINK)\r\n cart_link.click()\r\n\r\n def should_be_product_page(self):\r\n self.should_be_product_url()\r\n self.should_be_add_to_cart_button()\r\n self.should_not_be_success_message()\r\n\r\n def should_be_product_url(self):\r\n assert '?promo=' in self.browser.current_url, \"Not product url\"\r\n\r\n def should_be_add_to_cart_button(self):\r\n assert self.is_element_present(*ProductPageLocators.ADD_TO_CART_LINK), \"No cart button\"\r\n\r\n def should_not_be_success_message(self):\r\n assert self.is_not_element_present(\r\n *ProductPageLocators.CART_PRODUCT_NAME), \"Success message is presented, but should not be\"\r\n\r\n def should_be_success_message(self):\r\n assert self.is_element_present(*ProductPageLocators.CART_PRODUCT_NAME), \"No success message\"\r\n\r\n def should_be_valid_cart_name(self):\r\n product_name = self.browser.find_element(*ProductPageLocators.PAGE_PRODUCT_NAME)\r\n cart_product_name = self.browser.find_element(*ProductPageLocators.CART_PRODUCT_NAME)\r\n assert product_name.text == cart_product_name.text, \"Invalid product name\"\r\n\r\n def should_be_valid_cart_price(self):\r\n product_price = self.browser.find_element(*ProductPageLocators.PAGE_PRODUCT_PRICE)\r\n cart_product_price = self.browser.find_element(*ProductPageLocators.CART_PRODUCT_PRICE)\r\n assert product_price.text == cart_product_price.text, \"Invalid product price\"\r\n\r\n def should_be_disappeared(self):\r\n assert self.is_disappeared(*ProductPageLocators.CART_PRODUCT_NAME), \"Not disappeared\"\r\n"
},
{
"alpha_fraction": 0.7112069129943848,
"alphanum_fraction": 0.7112069129943848,
"avg_line_length": 40.3636360168457,
"blob_id": "a8578b39caf3af42aa93bf6b6ec43646091eac05",
"content_id": "ae7e46435aec05efb4bf96c57bbf3bce13abd83d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 464,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 11,
"path": "/pages/cart_page.py",
"repo_name": "nikitarredline/stepic_course",
"src_encoding": "UTF-8",
"text": "from .base_page import BasePage\r\nfrom .locators import CartPageLocators\r\n\r\n\r\nclass CartPage(BasePage):\r\n def should_not_be_items_in_cart(self):\r\n assert self.is_not_element_present(*CartPageLocators.ITEMS_LINK), \"Cart is not empty\"\r\n\r\n def should_be_empty_cart_text(self):\r\n cart_text = self.browser.find_element(*CartPageLocators.EMPTY_CART_TEXT)\r\n assert cart_text.text == 'Your basket is empty. Continue shopping', \"Cart is not empty\""
},
{
"alpha_fraction": 0.6549844145774841,
"alphanum_fraction": 0.656931459903717,
"avg_line_length": 30.94871711730957,
"blob_id": "d7af798e0d8c1dd73bd6ce153d1a4d94d0b7d03c",
"content_id": "144306307b71ca1e52163e1e65b498fc5e106233",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2568,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 78,
"path": "/test_product_page.py",
"repo_name": "nikitarredline/stepic_course",
"src_encoding": "UTF-8",
"text": "from .pages.product_page import ProductPage\r\nfrom .pages.login_page import LoginPage\r\nfrom .pages.cart_page import CartPage\r\nimport pytest\r\nimport time\r\n\r\nproduct_link = 'http://selenium1py.pythonanywhere.com/catalogue/the-shellcoders-handbook_209/'\r\n\r\n\r\ndef test_guest_should_see_login_link_on_product_page(browser):\r\n link = product_link\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.should_be_login_link()\r\n\r\n\r\[email protected]_review\r\ndef test_guest_can_go_to_login_page_from_product_page(browser):\r\n link = product_link\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.go_to_login_page()\r\n\r\n\r\[email protected]_review\r\ndef test_guest_cant_see_product_in_cart_opened_from_product_page(browser):\r\n link = product_link\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.go_to_cart_page()\r\n cart_page = CartPage(browser, browser.current_url)\r\n cart_page.should_not_be_items_in_cart()\r\n cart_page.should_be_empty_cart_text()\r\n\r\n\r\[email protected]_review\r\ndef test_guest_can_add_product_to_cart(browser):\r\n link = product_link + '?promo=newYear'\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.should_be_product_page()\r\n page.add_product_to_cart()\r\n page.solve_quiz_and_get_code()\r\n page.should_be_success_message()\r\n page.should_be_valid_cart_name()\r\n page.should_be_valid_cart_price()\r\n\r\n\r\[email protected]\r\nclass TestUserAddToCartFromProductPage(object):\r\n @pytest.fixture(scope=\"function\", autouse=True)\r\n def setup(self, browser):\r\n link = \"https://selenium1py.pythonanywhere.com/accounts/login/\"\r\n self.browser = browser\r\n email = str(time.time()) + \"@fakemail.org\"\r\n login_page = LoginPage(browser, link)\r\n login_page.open()\r\n login_page.should_be_login_page()\r\n login_page.register_new_user(email, email)\r\n login_page.should_be_authorized_user()\r\n\r\n @pytest.mark.need_review\r\n def test_user_can_add_product_to_cart(self, browser):\r\n link = product_link + '?promo=newYear'\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.should_be_product_page()\r\n page.add_product_to_cart()\r\n page.solve_quiz_and_get_code()\r\n page.should_be_success_message()\r\n page.should_be_valid_cart_name()\r\n page.should_be_valid_cart_price()\r\n\r\n def test_user_cant_see_success_message(self, browser):\r\n link = product_link\r\n page = ProductPage(browser, link)\r\n page.open()\r\n page.should_not_be_success_message()"
}
] | 5 |
kavyasree-bvs/Resource-Allocation
|
https://github.com/kavyasree-bvs/Resource-Allocation
|
e7a005d4ec6bc02524a5d2183e718556fafc39b7
|
76701c686ae4cf18fb018d32ae5c3c36e75d9ec3
|
951e3b55dc77164ce4b1a12f1b39ebee9881309f
|
refs/heads/master
| 2020-03-17T06:01:15.097657 | 2018-05-14T09:38:51 | 2018-05-14T09:38:51 | 133,338,304 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.8347107172012329,
"alphanum_fraction": 0.8347107172012329,
"avg_line_length": 59.5,
"blob_id": "df91828d94ae91da9896f32c13cb846ae8c68f05",
"content_id": "5a2f449a951a05b2b458290caa8d5708951ec7ae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 121,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 2,
"path": "/README.md",
"repo_name": "kavyasree-bvs/Resource-Allocation",
"src_encoding": "UTF-8",
"text": "# Resource-Allocation\nImplemented a Command Line Interface to handle resource allocation of racks, server storage space.\n"
},
{
"alpha_fraction": 0.684335470199585,
"alphanum_fraction": 0.6906244158744812,
"avg_line_length": 27.07927894592285,
"blob_id": "107ebe7cae349acfd1c94402ff8266b88f4c9097",
"content_id": "50fd62f388e99c85c9e54cc06206a3cf9143e5e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15583,
"license_type": "no_license",
"max_line_length": 257,
"num_lines": 555,
"path": "/main.py",
"repo_name": "kavyasree-bvs/Resource-Allocation",
"src_encoding": "UTF-8",
"text": "import os.path\nas_str = \"aggiestack\"\nshow_str = \"show\"\nconfig_str = \"config\"\nserver_str = \"server\"\nadmin_str = \"admin\"\n\nclass machine:\n\tdef __init__(self, name, rackName, ip, mem, numDisks, numCores):\n\t#def __init__(self, name, ip, mem, numDisks, numCores):\n\t\tself.name = name\n\t\tself.rackName = rackName\n\t\tself.ip = ip\n\t\tself.mem = mem #in GB\n\t\tself.numDisks = numDisks\n\t\tself.numCores = numCores\n\t\tself.availableMem = 0\n\t\tself.availableDisks = 0\n\t\tself.availableCores = 0\n\tdef initAvailableParams(self):\n\t\tself.availableCores = self.numCores\n\t\tself.availableDisks = self.numDisks\n\t\tself.availableMem = self.mem\n\tdef allocateSpace(self, mem, numDisks, numCores):\n\t\tself.availableCores -= numCores\n\t\tself.availableDisks -= numDisks\n\t\tself.availableMem -= mem\n\tdef deallocateSpace(self, mem, numDisks, numCores):\n\t\tself.availableCores += numCores\n\t\tself.availableDisks += numDisks\n\t\tself.availableMem += mem\n\nclass rack:\n\tdef __init__(self, name, storagecap):\n\t\tself.name =name\n\t\tself.storageCapacity = storagecap\n\nclass image:\n\tdef __init__(self, imageName, imageSize, imagePath):\n\t#def __init__(self, imageName, imagePath):\n\t\tself.imageName = imageName\n\t\tself.imageSize = imageSize #in MB\n\t\tself.imagePath = imagePath\n\nclass flavor:\n\tdef __init__(self, flavorName, RAM, noOfDisks, noOfVcpus):\n\t\t#amount of RAM in GB, the number of disks, the number of vcpus. \n\t\tself.flavorName = flavorName\n\t\tself.RAM = RAM #in GB\n\t\tself.noOfDisks = noOfDisks\n\t\tself.noOfVcpus = noOfVcpus\n\nclass instance:\n\tdef __init__(self, instanceName, imageName, flavorName):\n\t\tself.instanceName = instanceName\n\t\tself.imageName = imageName\n\t\tself.flavorName = flavorName\n\t\tself.serverHosting = \"none\"\n\t\tself.rack = \"none\"\n\tdef updateServer(self, server):\n\t\tself.serverHosting = server\n\tdef updateRack(self, rack):\n\t\tself.rack = rack\n\nracks = []\nmachines = []\nimages = []\nflavors = []\ninstances = []\n\ndef ReadConfigFile(configFileName):\n\twith open(configFileName) as f:\n\t\tcontent = f.readlines()\n\tcontent = [x.strip() for x in content] \n\n\tcurr_index = 0\n\tnoOfRacks = int(content[curr_index])\n\t\n\tcurr_index +=1\n\tfor n in range(noOfRacks):\n\t\tif(len(content[curr_index+n].split()) != 2):\n\t\t\tprint 'ERROR: Incorrect format. Should be in <rack name> <storage capacity>'\n\t\t\treturn False\n\t\t(name, val) = content[curr_index+n].split()\n\t\trh = rack(name,int(val))\n\t\tracks.append(rh)\n\t\n\tcurr_index +=noOfRacks\n\tnoOfMachines = int(content[curr_index])\n\tcurr_index +=1\n\t\n\tfor n in range(noOfMachines):\n\t\tif(len(content[curr_index+n].split()) != 6):\n\t\t\tprint 'ERROR: Incorrect format. Should be in <name> <rack name> <ip> <mem> <num-disks> <num-cores>'\n\t\t\treturn False\n\t\t(name, rackName, ip, mem, numDisks, numCores) = content[curr_index+n].split()\n\t\tmh = machine(name, rackName, ip, int(mem), int(numDisks), int(numCores))\n\t\tmh.initAvailableParams()\n\t\tmachines.append(mh)\n\treturn True\n\ndef ShowHardware():\n\t#do error check for len = 0\n\t#and return fail\n\tprint 'no of racks = ', len(racks)\n\tfor i in range(len(racks)):\n\t\tprint racks[i].name, racks[i].storageCapacity\n\t''''''\n\tprint 'no of machines = ', len(machines)\n\tfor i in range(len(machines)):\n\t\tprint machines[i].name, machines[i].rackName, machines[i].ip, machines[i].mem, machines[i].numDisks, machines[i].numCores\n\treturn True\n\ndef ShowCurrentlyAvailableHardware():\n\tif(len(machines)==0):\n\t\tprint 'No machines to show'\n\t\treturn True\n\tprint 'no of currently available machines = ', len(machines)\n\tfor i in range(len(machines)):\n\t\tprint machines[i].name, machines[i].availableMem, machines[i].availableDisks, machines[i].availableCores\n\treturn True\n\ndef ReadImageFile(configFileName):\n\twith open(configFileName) as f:\n\t\tcontent = f.readlines()\n\tcontent = [x.strip() for x in content] \n\n\tcurr_index = 0\n\tnoOfImages = int(content[0])\n\t\n\tcurr_index +=1\n\tfor n in range(noOfImages):\n\t\tif(len(content[curr_index+n].split()) != 3):\n\t\t\tprint 'ERROR: Incorrect format. Should be in <image name> <size> <path>'\n\t\t\treturn False\n\n\t\t(name, size, path) = content[curr_index+n].split()\n\t\tim = image(name,int(size),path)\n\t\timages.append(im)\n\treturn True\n\ndef ShowImages():\n\tprint 'no of images = ', len(images)\n\tfor i in range(len(images)):\n\t\tprint images[i].imageName, images[i].imageSize, images[i].imagePath\n\ndef ReadFlavorFile(configFileName):\n\twith open(configFileName) as f:\n\t\tcontent = f.readlines()\n\t# you may also want to remove whitespace characters like `\\n` at the end of each line\n\tcontent = [x.strip() for x in content] \n\t#print content\n\n\tcurr_index = 0\n\tnoOfFlavors = int(content[0])\n\t#print noOfFlavors\n\t\n\tcurr_index +=1\n\tfor n in range(noOfFlavors):\n\t\tif(len(content[curr_index+n].split()) != 4):\n\t\t\tprint 'ERROR: Incorrect format. Should be in <flavor name> <size> <disks> <vcpus>'\n\t\t\treturn False\n\t\t(name, size, disks, vcpus) = content[curr_index+n].split()\n\t\tfl = flavor(name,int(size),int(disks), int(vcpus))\n\t\tflavors.append(fl)\n\treturn True\n\ndef ShowFlavors():\n\tprint 'no of flavors = ', len(flavors)\n\tfor i in range(len(flavors)):\n\t\tprint flavors[i].flavorName, flavors[i].RAM, flavors[i].noOfDisks, flavors[i].noOfVcpus\n\ndef FindMachineIndex(machineName):\n\tfor i in range(len(machines)):\n\t\tcurr = machines[i]\n\t\tif(curr.name == machineName):\n\t\t\treturn i\n\treturn -1\n\ndef FindFlavorIndex(flavorType):\n\tfor i in range(len(flavors)):\n\t\tcurr = flavors[i]\n\t\tif(curr.flavorName == flavorType):\n\t\t\treturn i\n\treturn -1\n\ndef FindInstanceIndex(name):\n\n\tfor i in range(len(instances)):\n\t\tcurr = instances[i]\n\t\tif(curr.instanceName == name):\n\t\t\treturn i\n\treturn -1\n\ndef FindRackIndex(name):\n\tfor i in range(len(racks)):\n\t\tcurr = racks[i]\n\t\tif(curr.name == name):\n\t\t\treturn i\n\treturn -1\n\ndef IsSpaceAvail(a,b):\n\tif(a>=b):\n\t\treturn True\n\treturn False\n\ndef CanHost(machineName, flavorType):\n\tmachineIndex = FindMachineIndex(machineName)\n\tif(machineIndex == -1):\n\t\tprint 'ERROR: no machine of given name found'\n\t\treturn\n\tflavorIndex = FindFlavorIndex(flavorType)\n\tif(flavorIndex == -1):\n\t\tprint 'ERROR: no flavor of given name found'\n\t\treturn\n\t#print machineIndex, flavorIndex\n\n\tif(IsSpaceAvail(machines[machineIndex].availableMem, flavors[flavorIndex].RAM) and IsSpaceAvail(machines[machineIndex].availableDisks, flavors[flavorIndex].noOfDisks) and IsSpaceAvail(machines[machineIndex].availableCores, flavors[flavorIndex].noOfVcpus)):\n\t\treturn True\n\treturn False\n\ndef CreateInstance(instancename, imageToBeBootedFrom, flavorname):\n\tif(len(machines)==0):\n\t\tprint 'ERROR: no physical servers to host on'\n\t\treturn False\n\tfor i in range(len(machines)):\n\t\tcurrMach = machines[i].name\n\t\tret = CanHost(currMach, flavorname)\n\t\tif(ret):\n\t\t\tflavorIndex = FindFlavorIndex(flavorname)\n\t\t\tif(flavorIndex == -1):\n\t\t\t\tprint 'ERROR: no flavor of given name found'\n\t\t\t\treturn\n\t\t\tcurrflav = flavors[flavorIndex]\n\t\t\tmachines[i].allocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t\t\tins = instance(instancename, imageToBeBootedFrom, flavorname)\n\t\t\tins.updateServer(currMach)\n\t\t\tins.updateRack(machines[i].rackName)\n\t\t\tinstances.append(ins)\n\n\t\t\treturn True\n\tprint 'ERROR: no free servers'\n\treturn False\n\ndef ListInstances():\n\tif(len(instances)==0):\n\t\tprint 'ERROR: no instances to list'\n\t\treturn False\n\tprint len(instances)\n\tfor i in range(len(instances)):\n\t\tprint instances[i].instanceName, instances[i].imageName, instances[i].flavorName\n\treturn True\n\ndef ShowServersOfInstances():\n\tif(len(instances)==0):\n\t\tprint 'no instances to show'\n\t\treturn True\n\tprint 'no of instances = ', len(instances)\n\tfor i in range(len(instances)):\n\t\tprint instances[i].instanceName, instances[i].serverHosting\n\treturn True\n\ndef DeleteInstance(name):\n\tindex = FindInstanceIndex(name)\n\tif(index == -1):\n\t\tprint 'ERROR: no instance of given name found'\n\t\treturn False\n\t#print 'index is: ', index\n\t#deallocate the resources and delete the instance\n\tins = instances[index]\n\tflaname = ins.flavorName\n\tserver = ins.serverHosting\n\tindex = FindMachineIndex(server)\n\tif(index == -1):\n\t\tprint 'ERROR: no such server is found'\n\t\treturn False\n\tflaindex = FindFlavorIndex(flaname)\n\tif(flaindex == -1):\n\t\tprint 'ERROR: no flavor of given name found'\n\t\treturn False\n\tcurrflav = flavors[flaindex]\n\tmachines[index].deallocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t#del instances[index]\n\t\n\tif(len(instances) == 1):\n\t\tinstances.pop()\n\telse:\n\t\tinstances.pop(index)\n\treturn True\n\ndef EvacuateRack(evacname):\n\t#remove the instances from the current servers on the sick rack\n\t#delete the servers\n\t#reallocate the instance to another server on a healthy rack\n\t# should the rack be deleted as well\n\tif(len(racks)==0):\n\t\tprint 'ERROR: no racks to evacuate'\n\t\treturn True\n\tindex = FindRackIndex(evacname)\n\tif(index==-1):\n\t\tprint 'ERROR: no rack of given name found'\n\t\treturn False\n\tmigratedList = []\n\tfor i in range(len(instances)):\n\t\tins = instances[i]\n\t\tif(ins.rack == evacname):\n\t\t\t#print 'ins on rack to be evacuated is: ', ins.instanceName\n\t\t\tmigratedList.append(i)\n\t\t\t#remove from existing server\n\t\t\tflaname = ins.flavorName\n\t\t\tserverindex = FindMachineIndex(ins.serverHosting)\n\t\t\tflaindex = FindFlavorIndex(flaname)\n\t\t\tcurrflav = flavors[flaindex]\n\t\t\tmachines[serverindex].deallocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t\telse:\n\t\t\tcontinue\n\n\t#delete the machines\n\tmachlist = []\n\tfor i in range(0,len(machines)):\n\t\tcurrMach = machines[i].name\n\t\tif(machines[i].rackName == evacname):\n\t\t\tmachlist.append(i)\n\n\tfor i in range(0,len(machlist)):\n\t\ttempindex = len(machlist) - i - 1\n\t\tif(len(machines) == 1):\n\t\t\tmachines.pop()\n\t\telse:\n\t\t\tmachines.pop(machlist[tempindex])\n\n\t#reallocate\n\tfor j in range(len(migratedList)):\n\t\tins = instances[j]\n\t\tflaname = ins.flavorName\n\t\tfor i in range(len(machines)):\n\t\t\tcurrMach = machines[i].name\n\t\t\tret = CanHost(currMach, flaname)\n\t\t\tif(ret):\n\t\t\t\tflavorIndex = FindFlavorIndex(flaname)\n\t\t\t\tif(flavorIndex == -1):\n\t\t\t\t\tprint 'ERROR: no flavor of given name found'\n\t\t\t\t\treturn False\n\t\t\t\tcurrflav = flavors[flavorIndex]\n\t\t\t\tmachines[i].allocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t\t\t\tins.updateServer(currMach)\n\t\t\t\tins.updateRack(machines[i].rackName)\n\t\t\t\tbreak\n\t\t\tif(i == len(machines)-1):\n\t\t\t\t\tprint 'No free space in any machine to allocate'\n\treturn True\n\n\ndef RemoveMachine(remMachName):\n\tindex = FindMachineIndex(remMachName)\n\tif(index==-1):\n\t\tprint 'ERROR: no machine of given name found'\n\t\treturn False\n\tmigratedList = []\n\tfor i in range(len(instances)):\n\t\tins = instances[i]\n\t\tif(ins.serverHosting == remMachName):\n\t\t\tmigratedList.append(i)\n\t\t\t#remove from existing server\n\t\t\tflaname = ins.flavorName\n\t\t\tserverindex = FindMachineIndex(ins.serverHosting)\n\t\t\tflaindex = FindFlavorIndex(flaname)\n\t\t\tcurrflav = flavors[flaindex]\n\t\t\tmachines[serverindex].deallocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t\telse:\n\t\t\tcontinue\n\t#delete the machine\n\tif(len(machines) == 1):\n\t\tmachines.pop()\n\telse:\n\t\tmachines.pop(index)\n\t#reallocate\n\tfor j in range(len(migratedList)):\n\t\tins = instances[j]\n\t\tflaname = ins.flavorName\n\t\tfor i in range(len(machines)):\n\t\t\tcurrMach = machines[i].name\n\t\t\tret = CanHost(currMach, flaname)\n\t\t\tif(ret):\n\t\t\t\tflavorIndex = FindFlavorIndex(flaname)\n\t\t\t\tif(flavorIndex == -1):\n\t\t\t\t\tprint 'ERROR: no flavor of given name found'\n\t\t\t\t\treturn\n\t\t\t\tcurrflav = flavors[flavorIndex]\n\t\t\t\tmachines[i].allocateSpace(currflav.RAM, currflav.noOfDisks, currflav.noOfVcpus)\n\t\t\t\tins.updateServer(currMach)\n\t\t\t\tins.updateRack(machines[i].rackName)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tif(i == len(machines)-1):\n\t\t\t\t\tprint 'No free space in any machine to allocate'\n\treturn True\n\ndef AddMachine(mem, disk, vcpus, ip, rack, machineName):\n\t#adding a new machine\n\tmh = machine(machineName, rack, ip, int(mem), int(disk), int(vcpus))\n\tmh.initAvailableParams()\n\tmachines.append(mh)\n\treturn True\n\n\t\nimport datetime\n\ntime = 'Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now())\nprint time\n#print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))\n\n\nlog = open('aggiestack-log.txt', 'a')\nlog.write('\\n%s\\n'%time)\n#log.write()\n#write time stamp and start logging\ndef logOutput(ret):\n\tif(ret):\n\t\tlog.write('%s\\n'%SUC_STR)\n\telse:\n\t\tlog.write('%s\\n'%FAIL_STR)\n\nSUC_STR = \"SUCCESS\"\t\nFAIL_STR = \"FAILURE\"\n\n\nwhile True:\n\ttry:\n\t\tcmd =raw_input()\n\t\tlog.write('%s\\n'%cmd)\n\t\tcmd_parts = cmd.split()\n\t\tif(len(cmd_parts)==0):\n\t\t\tcontinue\n\n\t\tif(cmd_parts[0] != as_str):\n\t\t\tprint \"ERROR: Incorrect format. cmd should begin with\", as_str\n\t\t\tlog.write('%s\\n'%FAIL_STR)\n\t\t\tcontinue\n\t\t\n\t\tif(cmd_parts[1] == show_str):\n\t\t\t#do error check for len = 0\n\t\t\t#and return fail\n\t\t\tif(cmd_parts[2]==\"hardware\"):\n\t\t\t\tret = ShowHardware()\n\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"images\"):\n\t\t\t\tShowImages()\n\t\t\t\tlogOutput(True)\n\t\t\telif(cmd_parts[2]==\"flavors\"):\n\t\t\t\tShowFlavors()\n\t\t\t\tlogOutput(True)\n\t\t\telif(cmd_parts[2]==\"all\"):\n\t\t\t\tShowHardware()\n\t\t\t\tShowImages()\n\t\t\t\tShowFlavors()\n\t\t\t\tlogOutput(True)\n\t\t\telse:\n\t\t\t\tprint \"ERROR: Invalid parameters. Can show hardware/images/flavor/all\"\n\t\t\t\tlogOutput(False)\n\t\t\n\t\telif(cmd_parts[1]==config_str):\n\t\t\tif(cmd_parts[2]== \"--hardware\"):\n\t\t\t\tfname = cmd_parts[3]\n\t\t\t\tif(os.path.isfile(fname) == False):\n\t\t\t\t\tprint \"ERROR: File does not exist\"\n\t\t\t\t\tlogOutput(False)\n\t\t\t\telse:\n\t\t\t\t\tret = ReadConfigFile(fname)\n\t\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"--images\"):\n\t\t\t\tfname = cmd_parts[3]\n\t\t\t\tif(os.path.isfile(fname) == False):\n\t\t\t\t\tprint \"ERROR: File does not exist\"\n\t\t\t\t\tlogOutput(False)\n\t\t\t\telse:\n\t\t\t\t\tret = ReadImageFile(fname)\n\t\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"--flavors\"):\n\t\t\t\tfname = cmd_parts[3]\n\t\t\t\tif(os.path.isfile(fname) == False):\n\t\t\t\t\tprint \"ERROR: File does not exist\"\n\t\t\t\t\tlogOutput(False)\n\t\t\t\telse:\n\t\t\t\t\tret = ReadFlavorFile(fname)\n\t\t\t\t\tlogOutput(ret)\n\t\t\telse:\n\t\t\t\tprint 'ERROR: Invalid parameters. Can config only hardware/flavors/images'\n\t\t\t\tlogOutput(False)\n\n\t\telif(cmd_parts[1] == server_str):\n\t\t\t#print \"server case\"\n\t\t\tif(cmd_parts[2]==\"create\"):\n\t\t\t\tif(cmd_parts[3]==\"--image\" and cmd_parts[5]==\"--flavor\"):\n\t\t\t\t\timageToBeBootedFrom = cmd_parts[4]\n\t\t\t\t\tflavor_name = cmd_parts[6]\n\t\t\t\t\tinstance_name = cmd_parts[7]\n\t\t\t\t\tret = CreateInstance(instance_name, imageToBeBootedFrom, flavor_name)\n\t\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"list\"):\n\t\t\t\tret = ListInstances()\n\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"delete\"):\n\t\t\t\tret = DeleteInstance(cmd_parts[3])\n\t\t\t\tlogOutput(ret)\n\t\t\telse:\n\t\t\t\tprint \"Invalid command\"\n\t\t\t\tlogOutput(False)\n\n\t\telif(cmd_parts[1] == admin_str):\n\t\t\tif(cmd_parts[2]== \"show\"):\n\t\t\t\tif(cmd_parts[3]==\"hardware\"):\n\t\t\t\t\tret = ShowCurrentlyAvailableHardware()\n\t\t\t\t\tlogOutput(ret)\n\t\t\t\telif(cmd_parts[3]==\"instances\"):\n\t\t\t\t\tret = ShowServersOfInstances()\n\t\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"can_host\"):\n\t\t\t\tmachineName = cmd_parts[3]\n\t\t\t\tflavorType = cmd_parts[4]\n\t\t\t\tret = CanHost(machineName, flavorType)\n\t\t\t\tif(ret):\n\t\t\t\t\tprint \"yes\"\n\t\t\t\telse:\n\t\t\t\t\tprint \"no\"\n\t\t\telif(cmd_parts[2]==\"evacuate\"):\n\t\t\t\tret = EvacuateRack(cmd_parts[3])\n\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"remove\"):\n\t\t\t\tret = RemoveMachine(cmd_parts[3])\n\t\t\t\tlogOutput(ret)\n\t\t\telif(cmd_parts[2]==\"add\"):\n\t\t\t\t#check if enough arguments are there\n\t\t\t\tif(len(cmd_parts)!= 14):\n\t\t\t\t\tprint 'ERROR: few params to parse'\n\t\t\t\t\tlogOutput(False)\n\t\t\t\t\tcontinue\n\t\t\t\tif(cmd_parts[3]==\"-mem\" and cmd_parts[5]=='-disk' and cmd_parts[7]=='-vcpus' and cmd_parts[9]=='-ip' and cmd_parts[11]=='-rack'):\n\t\t\t\t\tAddMachine(cmd_parts[4], cmd_parts[6], cmd_parts[8], cmd_parts[10], cmd_parts[12], cmd_parts[13])\n\t\t\t\telse:\n\t\t\t\t\tprint 'incorrect format'\n\t\t\t\t\tlogOutput(False)\n\t\t\telse:\n\t\t\t\tprint \"Invalid command\"\n\t\t\t\tlogOutput(False)\n\n\t\telse:\n\t\t\tprint \"Invalid command\"\n\t\t\tlogOutput(False)\n\n\t\tcontinue\n\texcept KeyboardInterrupt:\n\t\tlog.close()\n\t\tprint \"Terminating CLI .. \"\n\t\tbreak"
}
] | 2 |
HashCodeAkTesisti/HashCodePizze
|
https://github.com/HashCodeAkTesisti/HashCodePizze
|
238ad6931826f17bad7e195521041f5204dc8ce5
|
f1f26e67df31c90a7c006649fc864039405dc533
|
04953ad398b68df2359f17d3319afd8d2b438374
|
refs/heads/master
| 2020-12-28T03:17:10.120466 | 2020-02-20T20:53:12 | 2020-02-20T20:53:12 | 238,163,566 | 2 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.41945064067840576,
"alphanum_fraction": 0.42984411120414734,
"avg_line_length": 29.613636016845703,
"blob_id": "6ff1737e3d13ca9ac331688ad8db16ad73e4d699",
"content_id": "ffe82930c1c0d93bb6fa2a0df0104fe425aa99e0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1347,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 44,
"path": "/vero/stev.py",
"repo_name": "HashCodeAkTesisti/HashCodePizze",
"src_encoding": "UTF-8",
"text": "import numpy as np\n\nfrom queue import Queue\nfrom tqdm import trange\n\n\ndef stev(B, L, D, S, DS, BD, BL):\n libraries = np.argsort(DS)\n lib_index = 0\n end_sign = -1\n scanned_books = {l: 0 for l in range(L)}\n all_scanned_b = np.zeros(B)\n signed_lib = []\n sol = {}\n\n for d in trange(D):\n if end_sign == -1:\n end_sign = d + DS[libraries[lib_index]]\n elif end_sign == d:\n end_sign = -1\n lib_index += 1\n signed_lib.append(libraries[lib_index - 1])\n sol[libraries[lib_index - 1]] = []\n for l in libraries[:lib_index]:\n que = Queue(maxsize=B)\n for b in list(BL[l])[scanned_books[l]:int(BD[l])]:\n que.put(b)\n aux = scanned_books[l] + BD[l]\n i = 0\n while not que.empty():\n if i == BD[l]:\n break\n b = que.get()\n a = 1\n if all_scanned_b[b] == 0:\n sol[l].append(b)\n all_scanned_b[b] = 1\n scanned_books[l] += 1\n else:\n # the book is already present, we take the next one to scan\n if aux < len(BL[l]):\n que.put(list(BL[l])[int(aux)])\n aux += 1\n return sol\n"
},
{
"alpha_fraction": 0.5154769420623779,
"alphanum_fraction": 0.5180037617683411,
"avg_line_length": 32.67021179199219,
"blob_id": "2f287955005ad5fc6d92739d0a38109e9691334a",
"content_id": "2df75032e57968ef7b670181bda611234b47f7e9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3166,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 94,
"path": "/vero/stecer.py",
"repo_name": "HashCodeAkTesisti/HashCodePizze",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom tqdm import tqdm\n\ndef stecer1(B, L, D, S, DS, BD, BL):\n pot_scores = compute_potential_library_scores(B, L, D, S, DS, BD, BL)\n sorted_libraries = np.argsort(-pot_scores)\n solution = {}\n day = 0\n scanned_books = set()\n sorted_books = list(np.argsort(-S))\n\n for library in tqdm(sorted_libraries):\n day += DS[library]\n if day >= D:\n # time up\n break\n\n solution[library] = []\n num_readable_books = int((D - day) * BD[library])\n\n best_books = [book for book in sorted_books if book in BL[library]]\n solution[library] = [book for book in\n best_books[:num_readable_books]\n if book not in scanned_books]\n scanned_books.update(solution[library])\n if len(solution[library]) == 0:\n del solution[library]\n day -= DS[library]\n\n return solution\n\n\ndef compute_potential_library_scores(B, L, D, S, DS, BD, BL):\n potential_scores = np.zeros(L)\n for library in range(L):\n potential_scores[library] = (np.sum(S[list(BL[library])]) * BD[library]\n * (D - DS[library]))\n return potential_scores\n\n\ndef compute_potential_library_scores_2(B, L, D, S, DS, BD, BL, day, scanned,\n sorted_books):\n potential_scores = np.zeros(L)\n for library in range(L):\n num_readable_books = int(np.floor((D - day) * BD[library]))\n best_books = [book for book in sorted_books if book in BL[library]]\n\n score = np.sum(S[[b for b in best_books[:num_readable_books]\n if b in BL[library] and b not in scanned]])\n potential_scores[library] = (score * BD[library] * (D - DS[library] - day))\n return potential_scores\n\n\n\ndef stecer2(B, L, D, S, DS, BD, BL):\n solution = {}\n day = 0\n scanned_books = set()\n sorted_books = tuple(np.argsort(-S))\n\n changed = True\n while changed and day <= D:\n changed = False\n pot_scores = compute_potential_library_scores_2(B, L, D, S, DS, BD, BL,\n day, scanned_books,\n sorted_books)\n sorted_libraries = np.argsort(-pot_scores)\n\n for library in sorted_libraries:\n if library in solution:\n continue\n if DS[library] + day > D:\n continue\n\n day += DS[library]\n\n solution[library] = []\n num_readable_books = int(np.floor((D - day) * BD[library]))\n\n best_books = [book for book in sorted_books if book in BL[library]]\n solution[library] = [book for book in\n best_books[:num_readable_books]\n if book not in scanned_books]\n scanned_books.update(solution[library])\n changed = True\n\n if len(solution[library]) == 0:\n del solution[library]\n day -= DS[library]\n changed = False\n else:\n break\n\n return solution\n\n"
},
{
"alpha_fraction": 0.4950298070907593,
"alphanum_fraction": 0.5058221817016602,
"avg_line_length": 27.860654830932617,
"blob_id": "a8fe012762ed889c807a01cdb6d9d84e0cc53a37",
"content_id": "d9ebb7578e50869b2e5f26f87befd1fbda97521c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3521,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 122,
"path": "/vero/main.py",
"repo_name": "HashCodeAkTesisti/HashCodePizze",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom stecer import stecer1, stecer2\nfrom stev import stev\n\ndef read_file(filename):\n \"\"\"\n B number of different books\n L number of libraries\n D number of available days\n S array of score given by books\n DS array length L: day to signup library j\n BD array length L: num books can be scanned in one day from library j\n BL dictionary of sets: set of books available in library key\n \"\"\"\n with open(filename, 'r') as infile:\n f = infile.readlines()\n\n # 1st line\n B, L, D = [int(x) for x in f[0].split(' ')]\n\n S = np.array([int(x) for x in f[1].split(' ')])\n\n # L section\n line = 2\n DS = np.zeros(L)\n BD = np.zeros(L)\n BL = {}\n for j in range(L):\n (n_books, DS[j], BD[j]) = [int(x) for x in f[line].split(' ')]\n line += 1\n BL[j] = set([int(x) for x in f[line].split(' ')])\n line += 1\n return B, L, D, S, DS, BD, BL\n\n\ndef write_file(solution, filename):\n nnz = sum([1 for l in solution if len(solution[l]) > 0])\n with open(filename, 'w') as outfile:\n outfile.write(\"{}\\n\".format(nnz))\n for library in solution:\n if len(solution[library]) == 0:\n continue\n outfile.write(\"{} {}\\n\".format(library, len(solution[library])))\n for book in solution[library]:\n outfile.write(\"{} \".format(book))\n outfile.write('\\n')\n\n\ndef scorer(solution, D, S, DS, BD):\n score = 0\n scanned_books = set()\n days = {}\n signup_day = 0\n for library in solution:\n signup_day += DS[library]\n days[library] = signup_day\n scanned = 0\n for book in solution[library]:\n if days[library] >= D:\n print('Books not scanned, out of time')\n break\n if book not in scanned_books:\n score += S[book]\n scanned_books.add(book)\n else:\n print('Scanning the same book')\n scanned += 1\n #print(scanned)\n if scanned == BD[library]:\n days[library] += 1\n scanned = 0\n return score\n\ndef check_constraint(solution):\n return True\n\ndef example(B, L, D, S, DS, BD, BL):\n solution = {}\n solution[1] = [5,2,3]\n solution[0] = [0,1,2,3,4]\n return solution\n\n\n\nif __name__ == '__main__':\n files = ['a_example',\n 'b_read_on',\n 'c_incunabula',\n 'd_tough_choices',\n 'e_so_many_books',\n 'f_libraries_of_the_world'\n ]\n algos = [#stecer2,\n stecer1,\n #stev\n ]\n tot_score = 0\n maximum = 0\n\n for f in files:\n B, L, D, S, DS, BD, BL = read_file(\"input/{}.txt\".format(f))\n\n scores = {}\n solutions = {}\n for alg in algos:\n solution = alg(B, L, D, S, DS, BD, BL)\n check_constraint(solution)\n scores[alg] = scorer(solution, D, S, DS, BD)\n solutions[alg] = solution\n maximum += sum(S)\n print(\"{:20s}{:30s}{}/{}\".format(f, alg.__name__, scores[alg],\n maximum))\n\n # search for best\n best_alg = sorted(scores.items(), key=lambda x: -x[1])[0][0]\n print(\"Using {}\\n\".format(best_alg.__name__))\n tot_score += scores[best_alg]\n solution = solutions[best_alg]\n write_file(solution, \"./output/{}.txt\".format(f))\n\n\n print(\"Final score is {}/{}\".format(tot_score, maximum))\n"
},
{
"alpha_fraction": 0.520026683807373,
"alphanum_fraction": 0.5277512669563293,
"avg_line_length": 30.7757568359375,
"blob_id": "f962562b2a0801559a3833f0c24fbebf64057393",
"content_id": "ab0039208f4ea57da5f2e6c5c83328fc05fb0ff0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10486,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 330,
"path": "/google_pizza.py",
"repo_name": "HashCodeAkTesisti/HashCodePizze",
"src_encoding": "UTF-8",
"text": "import random\nimport numpy as np\nfrom itertools import chain, combinations\n\ndef read_file(filename):\n \"\"\" Read submission file, return\n M: maximum number of slices\n N: number of tipes\n S: list of slice per type\n \"\"\"\n with open(filename, 'r') as infile:\n f = infile.readlines()\n\n m, n = [int(x) for x in f[0].split(' ')]\n s = [int(x) for x in f[1].split(' ')]\n return m, n, s\n\n\ndef writer(selected, filename):\n with open(filename, 'w') as outfile:\n outfile.write(\"{}\\n\".format(len(selected)))\n for sel in selected:\n outfile.write(\"{} \".format(sel))\n outfile.write(\"\\n\")\n\n\ndef scorer(wanted, selected, s):\n ordered_slices = 0\n seen = set()\n for pizza_type, pizza_slices in enumerate(s):\n if pizza_type in seen:\n raise Exception(\"Cannot order 2 times same pizza\")\n if pizza_type in selected:\n ordered_slices += pizza_slices\n seen.add(pizza_type)\n\n if ordered_slices > wanted:\n raise Exception(\"ERROR: too many slices ordered\")\n #print(\"ordered {} slices, we wanted {}\".format(ordered_slices, wanted))\n #print(\"optimality is {}\".format(100*ordered_slices/wanted))\n return ordered_slices\n\n\ndef stupid_solver(max_slices, s):\n \"\"\" Start from first element, add until exceed M\n return list of selected indices of s.\n \"\"\"\n selected = []\n tot_slices = 0\n for pizza_type, pizza_slices in enumerate(s):\n if pizza_slices + tot_slices <= max_slices:\n tot_slices += pizza_slices\n selected.append(pizza_type)\n return selected\n\n\ndef reverse_stupid_solver(max_slices, s):\n \"\"\" start from big pizzas\n \"\"\"\n selected = []\n tot_slices = 0\n for pizza_type, pizza_slices in enumerate(s[::-1]):\n if pizza_slices + tot_slices <= max_slices:\n tot_slices += pizza_slices\n selected.append(pizza_type)\n return selected\n\n\ndef randomized_stupid_solver(max_slices, s):\n \"\"\" Bad results\n \"\"\"\n rounds = 100\n selections = {}\n tot_slices = {}\n s_shuffle = s.copy()\n\n for rn in range(rounds):\n random.shuffle(s_shuffle)\n selections[rn] = []\n tot_slices[rn] = 0\n for pizza_type, pizza_slices in enumerate(s_shuffle):\n if pizza_slices + tot_slices[rn] <= max_slices:\n tot_slices[rn] += pizza_slices\n selections[rn].append(pizza_type)\n\n # now look for best shuffle\n best = sorted(tot_slices.items(), key=lambda x: -x[1])[0][0]\n return selections[best]\n\ndef refined_stupid_solver(max_slices, s):\n return refine_selection(stupid_solver(max_slices, s), max_slices, s)\n\n\ndef refine_selection(selection, max_slices, s):\n \"\"\" Try to improve selection by making space for non-included pizzas \"\"\"\n MAX_ITERS = 8 # refinement iterations\n SUBSET_L = 5 # max length of subsets for candidate removal\n slices = np.array(s)\n\n # try to improve untill there is space or we did not find a way to improve\n available_space = max_slices - sum(slices[selection])\n changed = True\n iters = 0\n while available_space > 0 and changed and iters < MAX_ITERS:\n iters += 1\n changed = False\n\n unordered_pizzas = set(range(len(s))) - set(selection)\n for pizza_type in unordered_pizzas:\n # TODO: any way to prune this?\n\n adding_slices = slices[pizza_type]\n if changed:\n break # we need to recompute unordered_pizzas\n\n # how much space do we need to create?\n remove_slices = adding_slices - available_space\n\n # we can simply insert this pizza\n if remove_slices <= 0:\n selection.append(pizza_type)\n changed = True\n available_space -= adding_slices\n continue\n\n # try to make space for this pizza by removig as less as possible\n current_slices = sum(slices[selection])\n removal_candidates = set(selection)\n\n # prune the removal set\n pruning = set()\n for candidate in removal_candidates:\n if (-slices[candidate] + adding_slices) <= 0:\n pruning.add(candidate)\n for prune in pruning:\n removal_candidates.remove(prune)\n\n bad_subsets = set()\n for candidate_removal_set in arrays_and_powerset(removal_candidates,\n SUBSET_L):\n skip = False\n for bad in bad_subsets:\n if all([b in candidate_removal_set for b in bad]):\n skip = True\n break\n if skip:\n continue\n\n candidate_slices = sum(slices[list(candidate_removal_set)])\n\n if candidate_slices < remove_slices:\n # not enough\n continue\n\n score_delta = -candidate_slices + adding_slices\n if score_delta <= 0:\n # not convenient\n bad_subsets.add(candidate_removal_set)\n continue\n\n # score delta is positive, make the change (even if it's not\n # the optimal change, checking all is too much\n for rem_pizza in candidate_removal_set:\n selection.remove(rem_pizza)\n available_space += slices[rem_pizza]\n selection.append(pizza_type)\n available_space -= adding_slices\n changed = True\n break\n\n # if we did not break then we did not found any candidate set with\n # positive delta, check another type of pizza\n\n return selection\n\ndef arrays_and_powerset(s, subset_l):\n return chain.from_iterable([subarrays(s), powerset(s, subset_l)])\n\n\ndef subarrays(s):\n l = tuple(s)\n for idx1 in range(len(l)):\n idx2 = idx1 + 1 # 1-length done in subsets\n while idx2 < len(l):\n yield l[idx1:idx2+1]\n idx2 += 1\n\n\ndef powerset(s, l=None):\n if l is not None:\n lengths = range(min(l, len(s)-1))\n else:\n lengths = range(len(s)-1)\n return chain.from_iterable(combinations(s, r+1) for r in lengths)\n\n\ndef bruteforce(max_slices, s):\n slices = np.array(s)\n best_num = 0\n best_order = []\n for subset in powerset(range(len(s))):\n ordering = list(subset)\n score = sum(slices[ordering])\n if score > max_slices:\n continue\n if score == max_slices:\n return ordering\n if score > best_num:\n best_num = score\n best_order = ordering\n return best_order\n\n\ndef knapsack(max_slices, s):\n W = max_slices # capacity of knapsack is number of pizza slices\n wt = s # a pizza weights the number of slices\n val = s # value == weight\n n = len(val)\n\n K_new = np.zeros(W+1, dtype=np.uint8)\n sel_new = np.zeros((W+1, len(val)), dtype=np.bool) # bool is still a byte\n # we need to reduce the first idx, but I don't think it's feasible\n\n # Build table K[][] in bottom up manner\n for i in range(n+1): # all items (iterations)\n K_old = K_new\n K_new = np.zeros(W+1, dtype=np.uint8)\n sel_old = sel_new\n sel_new = np.zeros((W+1, len(val)), dtype=np.bool)\n\n for w in range(W+1): # increase weigth\n if i == 0 or w == 0:\n continue\n\n elif wt[i-1] <= w: # we can pick this\n val_inc = val[i-1] + K_old[w-wt[i-1]]\n val_non_inc = K_old[w]\n if val_inc > val_non_inc: # should we pick it?\n K_new[w] = val_inc\n sel_new[w, :] = sel_old[w-wt[i-1], :]\n sel_new[w, i-1] = 1\n\n if K_new[w] == W: # early exit\n return np.where(sel_new[w])[0]\n\n else: # don't pick\n K_new[w] = val_inc\n sel_new[w, :] = sel_old[w, :]\n\n else: # not pickable\n K_new[w] = K_old[w]\n sel_new[w, :] = sel_old[w, :]\n\n return np.where(sel_new[W, :])[0]\n\ndef knapSack_onlyScore(max_slices, s):\n W = max_slices # capacity of knapsack is number of pizza slices\n wt = s # a pizza weights the number of slices\n val = s # value == weight\n n = len(val)\n\n K_new = np.zeros(W+1, dtype=np.uint8)\n\n # Build table K[][] in bottom up manner\n for i in range(n+1): # all items (iterations)\n K_old = K_new\n K_new = np.zeros(W+1, dtype=np.uint8)\n\n for w in range(W+1): # increase weigth\n if i == 0 or w == 0:\n continue\n\n elif wt[i-1] <= w: # we can pick this\n val_inc = val[i-1] + K_old[w-wt[i-1]]\n val_non_inc = K_old[w]\n if val_inc > val_non_inc: # should we pick it?\n K_new[w] = val_inc\n\n if K_new[w] == W: # early exit\n return K_new[w]\n\n else: # don't pick\n K_new[w] = val_inc\n\n else: # not pickable\n K_new[w] = K_old[w]\n\n return K_new[W]\n\n\n\n\nif __name__ == '__main__':\n files = [\n \"a_example\",\n \"b_small\",\n \"c_medium\",\n \"d_quite_big\",\n \"e_also_big\"]\n\n algos = [stupid_solver, reverse_stupid_solver, knapsack,\n refined_stupid_solver]\n tot_wanted = 0\n tot_score = 0\n\n for f in files:\n m, n, s = read_file(\"{}.in\".format(f))\n tot_wanted += m\n\n scores = {}\n selections = {}\n for alg in algos:\n if alg in[bruteforce, knapsack] and f in [\"d_quite_big\", \"e_also_big\"]:\n continue\n selected = alg(m, s)\n scores[alg] = scorer(m, selected, s)\n selections[alg] = selected\n print(\"{:20s}{:50s}{}/{}\".format(f, alg.__name__, scores[alg],\n m))\n\n # search for best\n best_alg = sorted(scores.items(), key=lambda x: -x[1])[0][0]\n print(\"Using {}\\n\".format(best_alg.__name__))\n tot_score += scores[best_alg]\n selected = selections[best_alg]\n writer(selected, \"{}.out\".format(f))\n\n\n print(\"Final score is {} over {}: {}%\".format(tot_score, tot_wanted,\n 100*tot_score/tot_wanted))\n"
}
] | 4 |
MichaelBittencourt/testgit
|
https://github.com/MichaelBittencourt/testgit
|
8b8891f96dc935bf271b3a4528e8ed2b8e072635
|
c25de1eafa33507847f3a76a95038d458fe51c7d
|
79c688b4db436d1d049cd7bf0e6fb288e62647f6
|
refs/heads/main
| 2023-08-27T19:52:19.864688 | 2021-10-21T19:13:15 | 2021-10-21T19:13:15 | 419,840,970 | 0 | 0 | null | 2021-10-21T18:48:38 | 2021-10-21T19:02:39 | 2021-10-21T19:07:21 |
Python
|
[
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 16,
"blob_id": "aa95a933d0fefe38f0ed040bd875eb8d9e035e4c",
"content_id": "653eed6e84b21d6b8520870d36aa9ea3e7363fe1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 51,
"license_type": "no_license",
"max_line_length": 17,
"num_lines": 3,
"path": "/test.py",
"repo_name": "MichaelBittencourt/testgit",
"src_encoding": "UTF-8",
"text": "print(\"Hello\")\nprint(\"feature1\")\nprint(\"feature2\")\n"
}
] | 1 |
AndreasZaschka/hipchat-timer-bot
|
https://github.com/AndreasZaschka/hipchat-timer-bot
|
8e77518b8b68251dad6bc7fe638bc6288efbb6e1
|
b864ce8b6770014b66b444fbbdb92c4961bb7ed2
|
fb3d6d4d5c51a809480647761a11df4686dad676
|
refs/heads/master
| 2021-01-20T22:11:36.674511 | 2016-06-28T20:55:33 | 2016-06-28T20:55:33 | 61,049,245 | 0 | 1 | null | 2016-06-13T15:50:55 | 2016-06-15T14:18:42 | 2016-06-28T20:55:33 |
Python
|
[
{
"alpha_fraction": 0.637535810470581,
"alphanum_fraction": 0.6454154849052429,
"avg_line_length": 18.375,
"blob_id": "054fecbe116a5cd866154a0cf345df0ffcba7957",
"content_id": "cde647360694c315b8d39bf6acec09c2b1556a78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1396,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 72,
"path": "/command.py",
"repo_name": "AndreasZaschka/hipchat-timer-bot",
"src_encoding": "UTF-8",
"text": "class HTBCommand(object):\n\n\tdef __init__(self, raw):\n\t\tself.raw = raw\n\t\tself.minutes = None\n\t\tself.command = None\n\t\tself.name = None\n\t\tself.parse(self.raw)\n\n\tdef parse(self, raw):\n\t\tif (len(raw) < 6):\n\t\t\tself.command = 'ERROR'\n\n\t\t# /timer\n\t\tif (len(raw) == 6):\n\t\t\tself.default()\n\n\t\t# /timer *\n\t\tif (len(raw) > 7):\n\t\t\tself.parseSuffix(raw[7:len(raw)])\n\n\n\tdef parseSuffix(self, rawSuffix):\n\n\t\t# /timer config <token>\n\t\tif (rawSuffix.find('config') > -1):\n\t\t\tself.parseConfig(rawSuffix[7:len(rawSuffix)])\n\t\t\treturn\n\n\t\t# /timer <minutes>\n\t\tif (unicode(rawSuffix).isnumeric()):\n\t\t\tself.default()\n\t\t\tself.parseOnlyMinutes(rawSuffix)\n\t\t\treturn\n\n\t\t# /timer <name>\n\t\tif(rawSuffix.isalpha()):\n\t\t\tself.default()\n\t\t\tself.parseOnlyName(rawSuffix)\n\t\t\treturn\n\n\t\tsplit = rawSuffix.split()\n\n\t\t# /timer <name> <minutes>\n\t\tif(len(split) == 2):\n\t\t\tself.default()\n\t\t\tself.parseOnlyMinutes(split[1])\n\t\t\tself.parseOnlyName(split[0])\n\t\t\n\n\tdef parseConfig(self, rawConfig):\n\t\tself.command = 'CONFIG'\n\t\tself.name = rawConfig\n\n\tdef parseOnlyMinutes(self, rawSuffix):\n\t\tif(rawSuffix.isdigit()):\n\t\t\ttry:\n\t \t\t\tself.minutes = int(rawSuffix)\n\t\t\texcept ValueError:\n\t\t\t\tself.minutes = None\n\n\t\tif(rawSuffix.isdigit() == False):\n\t\t\tself.minutes = None\n\n\tdef parseOnlyName(self, rawSuffix):\n\t\tif(rawSuffix.isalpha()):\n\t\t\tself.name = rawSuffix\n\n\tdef default(self):\n\t\tself.minutes = 60\n\t\tself.name = 'Sprint'\n\t\tself.command = 'NEW'\n\n"
},
{
"alpha_fraction": 0.6573241949081421,
"alphanum_fraction": 0.6668429374694824,
"avg_line_length": 21.5238094329834,
"blob_id": "a884789b67577122ab427969506d72b365ff6da8",
"content_id": "589e23266830e77d548d15857ab626b4eb6649b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1891,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 84,
"path": "/app.py",
"repo_name": "AndreasZaschka/hipchat-timer-bot",
"src_encoding": "UTF-8",
"text": "import os\nimport requests\nimport logging\nimport sys\nimport json\nimport time\n\nfrom threading import Timer\nfrom flask import Flask\nfrom flask import request\nfrom command import HTBCommand\n\napp = Flask(__name__)\n\nlog = logging.getLogger('TimerBot')\n\[email protected]('/test', methods=['GET', 'POST'])\ndef create_status():\n\treturn 'ok'\n\n\[email protected]('/timer', methods=['GET', 'POST'])\ndef create_timer():\n\n\trData = request.get_json(silent=True)\n\n\tmessage = rData['item']['message']['message']\n\n\troom_id = rData['item']['room']['id']\n\n\tcmd = HTBCommand(message)\n\n\tif (cmd.command == 'NEW'):\n\t\tstart_timer(room_id, cmd)\n\n\treturn 'created timer'\n\ndef notify_room(room_id, message):\n\n\ttoken = os.environ.get('TOKEN_' + str(room_id), None)\n\n\tif (token == None):\n\t\treturn\n\n\turl = 'https://bindoc.hipchat.com/v2/room/' + str(room_id) + '/notification?auth_token=' + token\n\n\theaders = {'Content-type': 'application/json'}\n\n\tpayload = {'color': 'green','message': message,'notify': True,'message_format': 'text'}\n\n\tr = requests.post(url, headers = headers, data = json.dumps(payload))\n\n\tif r.status_code >= 400:\n\t\tlog.error('request turns info %d', r.status_code)\n\t\tlog.error('payload= %s', json.dumps(payload))\n\t\tlog.error('url= %s', r.url)\n\t\tlog.error('content= %s', r.content)\n\ndef set_scheduler(cmd, room_id):\n\n\tmessage_str = '%s (%d min) abgelaufen' % (cmd.name, cmd.minutes)\n\n\tTimer(60 * cmd.minutes, notify_room, (room_id, message_str)).start()\n\ndef start_timer(room_id, cmd):\n\n\tif (cmd.minutes == None): return\n\n\tif (cmd.name == None): return\n\n\tmessage_str = '%s (%d min) gestartet ...' % (cmd.name, cmd.minutes)\n\n\tnotify_room(room_id, message_str)\n\n\tset_scheduler(cmd, room_id)\n\nif __name__ == '__main__':\n\n\tlogging.basicConfig(stream=sys.stdout, level=logging.ERROR)\n\n\t# Bind to PORT if defined, otherwise default to 5000.\n\tport = int(os.environ.get('PORT', 5000))\n\n\tapp.run(host='0.0.0.0', port=port)"
},
{
"alpha_fraction": 0.44594594836235046,
"alphanum_fraction": 0.6756756901741028,
"avg_line_length": 13.800000190734863,
"blob_id": "23e95f4c8919ef82e6a6a95ed60164276ca277ed",
"content_id": "e364e66ab57ccf010e6cac7a3fe54d96ee1d56b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 74,
"license_type": "no_license",
"max_line_length": 16,
"num_lines": 5,
"path": "/requirements.txt",
"repo_name": "AndreasZaschka/hipchat-timer-bot",
"src_encoding": "UTF-8",
"text": "Flask==0.10.1\nJinja2==2.6\nWerkzeug==0.8.3\nwsgiref==0.1.2\nrequests==2.10.0\n"
},
{
"alpha_fraction": 0.7318761348724365,
"alphanum_fraction": 0.744990885257721,
"avg_line_length": 29.511110305786133,
"blob_id": "11f945dcf7396815697d2f2fe9e3a55066a77e52",
"content_id": "3ae102c723984e1a6af1530002e16ee3cf1738b6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2745,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 90,
"path": "/commandTest.py",
"repo_name": "AndreasZaschka/hipchat-timer-bot",
"src_encoding": "UTF-8",
"text": "import unittest\n\nfrom command import HTBCommand\n\n# Here's HTBCommand \"unit tests\".\nclass HTBCommandTest(unittest.TestCase):\n\n\tdef testTooShort(self):\n\t\tinstance = HTBCommand('/time')\n\t\tself.assertEqual('ERROR', instance.command)\n\t\tself.assertEqual(None, instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef testDefault(self):\n\t\tinstance = HTBCommand('/timer')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Sprint', instance.name)\n\t\tself.assertEqual(60, instance.minutes)\n\n\tdef testConfig(self):\n\t\tinstance = HTBCommand('/timer config token')\n\t\tself.assertEqual('CONFIG', instance.command)\n\t\tself.assertEqual('token', instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef testOnlyMinutes(self):\n\t\tinstance = HTBCommand('/timer 60')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Sprint', instance.name)\n\t\tself.assertEqual(60, instance.minutes)\n\n\tdef testOnlyMinutes2(self):\n\t\tinstance = HTBCommand('/timer 6')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Sprint', instance.name)\n\t\tself.assertEqual(6, instance.minutes)\n\n\tdef testOnlyMinutes3(self):\n\t\tinstance = HTBCommand('/timer 100')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Sprint', instance.name)\n\t\tself.assertEqual(100, instance.minutes)\n\n\tdef testOnlyMinutes4(self):\n\t\tinstance = HTBCommand('/timer 0.001')\n\t\tself.assertEqual(None, instance.command)\n\t\tself.assertEqual(None, instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef testOnlyMinutes5(self):\n\t\tinstance = HTBCommand('/timer -1')\n\t\tself.assertEqual(None, instance.command)\n\t\tself.assertEqual(None, instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef testOnlyName(self):\n\t\tinstance = HTBCommand('/timer Test')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Test', instance.name)\n\t\tself.assertEqual(60, instance.minutes)\n\n\tdef testNameAndMinutes(self):\n\t\tinstance = HTBCommand('/timer Test 5')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Test', instance.name)\n\t\tself.assertEqual(5, instance.minutes)\n\n\tdef testNameAndMinutes1(self):\n\t\tinstance = HTBCommand('/timer Test -5')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Test', instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef testNameAndMinutes2(self):\n\t\tinstance = HTBCommand('/timer Test 0.001')\n\t\tself.assertEqual('NEW', instance.command)\n\t\tself.assertEqual('Test', instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\n\tdef test3Things(self):\n\t\tinstance = HTBCommand('/timer name token 6')\n\t\tself.assertEqual(None, instance.command)\n\t\tself.assertEqual(None, instance.name)\n\t\tself.assertEqual(None, instance.minutes)\n\ndef main():\n\tunittest.main()\n\nif __name__ == '__main__':\n\tmain()"
},
{
"alpha_fraction": 0.6733871102333069,
"alphanum_fraction": 0.6733871102333069,
"avg_line_length": 19.58333396911621,
"blob_id": "c3c84efa3cb80ef8895a7612eb93d0423f492324",
"content_id": "c02c1cb89cdd48d24efe828c7534ccb1f0fee0b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 248,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/Dockerfile",
"repo_name": "AndreasZaschka/hipchat-timer-bot",
"src_encoding": "UTF-8",
"text": "FROM ubuntu:latest\nMAINTAINER Markus Heider \"[email protected]\"\nRUN apt-get update -y && \\\n\t\t\tapt-get install -y \\\n\t\t\tbuild-essential \\\n\t\t\tpython-pip \\\n\t\t\tpython-dev\nCOPY . /app\nWORKDIR /app\nRUN pip install -r requirements.txt\nENTRYPOINT [\"python\"]\nCMD [\"app.py\"]\n\n"
}
] | 5 |
DEH1C/calculator
|
https://github.com/DEH1C/calculator
|
1d90c57bd624cc7f43e8b7d2bdc4f03ce0fbe389
|
5cec05c0b2d2c411d0cff8956a03f2a98e204bfc
|
fe4018b27f782a21c689ae9ec0d93cd05a9389d1
|
refs/heads/master
| 2020-07-02T18:47:00.403771 | 2019-08-10T12:32:09 | 2019-08-10T12:32:09 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7727272510528564,
"alphanum_fraction": 0.7727272510528564,
"avg_line_length": 21,
"blob_id": "0c321279dc2342774d729b8d74f4147f35b83456",
"content_id": "b10f0c4ad5239c662d22dc0d3e40b7eb2f21fac8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 2,
"path": "/README.md",
"repo_name": "DEH1C/calculator",
"src_encoding": "UTF-8",
"text": "# calculator\nCalculator on Python (eng/rus)\n"
},
{
"alpha_fraction": 0.5200729966163635,
"alphanum_fraction": 0.5334550142288208,
"avg_line_length": 32.551021575927734,
"blob_id": "5fba16244cefad7fbcbcf3b00de4ddaf0fdac193",
"content_id": "f2325fb05d36429f7f91e1f3176337cf8cfe86fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1743,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 49,
"path": "/start.py",
"repo_name": "DEH1C/calculator",
"src_encoding": "UTF-8",
"text": "import math\nimport time\n\n# Loading...\ntime.sleep(0.8)\nprint (\"\\n\" * 100 + \"Loading.\")\ntime.sleep(0.8)\nprint (\"\\n\" * 100 + \"Loading. .\")\ntime.sleep(0.8)\nprint (\"\\n\" * 100 + \"Loading. . .\")\ntime.sleep(0.8)\nprint (\"\\n\" * 100 + \" – Complete!\")\n\n# Language change\nlang = input(\" \\n Change your language [eng/rus]: \")\nif lang == \"rus\":\n # Russian version\n username = input(\"\\n Введите свой ник: \")\n tool = input(\"\\n \" + username + \", что хотите сделать? (+/-): \")\n first = float( input(\"\\n Первое число: \"))\n second = float( input(\"\\n Второе число: \"))\n if tool == \"+\":\n ans = first + second\n print(\"\\n Решение: \" + str(first) + \"+\" + str(second) + \"=\" + str(ans))\n elif tool == \"-\":\n ans = first - second\n print(\"\\n Решение: \" + str(first) + \"-\" + str(second) + \"=\" + str(ans))\n else:\n print(\"\\n Убедитесь, что ввели все правильно!\")\n exit(0)\nelif lang == \"eng\":\n # English version\n username = input(\" \\nEnter your nickname: \")\n tool = input(\"\\n\" + username + \", what do you want to do? (+/-): \")\n first = float( input(\"\\n First number: \"))\n second = float( input(\"\\n Second number: \"))\n if tool == \"+\":\n ans = first + second\n print(\"\\n Decision: \" + str(first) + \"+\" + str(second) + \"=\" + str(ans))\n elif tool == \"-\":\n ans = first - second\n print(\"\\n Decision: \" + str(first) + \"-\" + str(second) + \"=\" + str(ans))\n else:\n print(\"\\n Be sure to enter everything correctly!\")\n exit(0)\nelse:\n print (\" \\nSelect available language.\")\n \nprint(\"\\n Thx for choose this code!\\n My link in VK.com – vk.com/denniis\")\n"
}
] | 2 |
nashtash/servicelayer
|
https://github.com/nashtash/servicelayer
|
6db75c5b16ab71f05b57427d4638c9dd0ae5784c
|
1455bc305302ee184695af006477f9812ff39910
|
e6e7883106f86d8da4234b6632b6050da2911b12
|
refs/heads/master
| 2020-12-15T16:57:15.196191 | 2020-01-14T16:41:41 | 2020-01-14T16:41:41 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6939040422439575,
"alphanum_fraction": 0.7107652425765991,
"avg_line_length": 31.125,
"blob_id": "1492f1df4a968db7f21deade421c86109e897e4b",
"content_id": "91c4f46a085ae147fc93b0c0b3447a7bbd1df41f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 771,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 24,
"path": "/servicelayer/settings.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "import multiprocessing\nfrom servicelayer import env\n\n# Redis cache\nREDIS_URL = env.get('REDIS_URL')\nREDIS_SHORT = 84700\nREDIS_LONG = REDIS_SHORT * 200\nREDIS_EXPIRE = env.to_int('REDIS_EXPIRE', REDIS_SHORT * 7)\nREDIS_PREFIX = 'sla'\n\n# Worker\nWORKER_RETRY = env.to_int('WORKER_RETRY', 3)\nWORKER_THREADS = min(8, multiprocessing.cpu_count())\nWORKER_THREADS = env.to_int('WORKER_THREADS', WORKER_THREADS)\n\n# Amazon client credentials\nAWS_KEY_ID = env.get('AWS_ACCESS_KEY_ID')\nAWS_SECRET_KEY = env.get('AWS_SECRET_ACCESS_KEY')\nAWS_REGION = env.get('AWS_REGION', 'eu-west-1')\n\n# Storage type (either 's3', 'gs', or 'file', i.e. local file system):\nARCHIVE_TYPE = env.get('ARCHIVE_TYPE', 'file')\nARCHIVE_BUCKET = env.get('ARCHIVE_BUCKET')\nARCHIVE_PATH = env.get('ARCHIVE_PATH')\n"
},
{
"alpha_fraction": 0.5949506163597107,
"alphanum_fraction": 0.6031833291053772,
"avg_line_length": 33.377357482910156,
"blob_id": "8a0b8bbe78f6d956a7aa2a174e4ae1d69c175972",
"content_id": "45605a43d7339e4bb2ca23694e8045ee135f3282",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1822,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 53,
"path": "/servicelayer/rate_limit.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "import time\n\nfrom servicelayer.settings import REDIS_PREFIX as PREFIX\nfrom servicelayer.cache import make_key\n\n\nclass RateLimit(object):\n \"\"\"Limit the rate of stages on a given resource during a\n stated interval.\"\"\"\n\n def __init__(self, conn, resource, limit=100, interval=60, unit=1):\n self.conn = conn\n self.resource = resource\n self.limit = max(0.1, limit)\n self.interval = max(1, interval)\n self.unit = unit\n\n def _time(self):\n return int(time.time() / self.unit)\n\n def _keys(self):\n base = self._time()\n for slot in range(base, base + self.interval):\n yield make_key(PREFIX, 'rate', self.resource, slot)\n\n def update(self, amount=1):\n \"\"\"Set the cached counts for stats keeping.\"\"\"\n pipe = self.conn.pipeline()\n for key in self._keys():\n pipe.incr(key, amount=amount)\n pipe.expire(key, (self.interval * self.unit) + 2)\n values = pipe.execute()[::2]\n return (sum(values) / self.interval)\n\n def check(self):\n \"\"\"Check if the resource has exceeded the rate limit.\"\"\"\n key = make_key(PREFIX, 'rate', self.resource, self._time())\n count = int(self.conn.get(key) or 0)\n return count < self.limit\n\n def comply(self, amount=1):\n \"\"\"Update, then sleep for the time required to adhere to the\n rate limit.\"\"\"\n # FIXME: this is trying to be smart, which will probably\n # backfire. Rather than just halt when the rate is exceeded,\n # this is trying to average down calls to the appropriate\n # frequency.\n rate = self.update(amount=amount) / self.limit\n expected = self.interval / self.limit\n excess = rate - expected\n if excess > 0:\n time.sleep(excess)\n return rate\n"
},
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.7015384435653687,
"avg_line_length": 29.952381134033203,
"blob_id": "6931fbe3b64e5c617d97c3b0a7e2854fb08dabc2",
"content_id": "b2b1a359c79d6b678f1041290d0b54094643494f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 650,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 21,
"path": "/servicelayer/archive/__init__.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "from servicelayer import settings\nfrom servicelayer.archive.file import FileArchive\n\nARCHIVE_FILE = 'file'\nARCHIVE_S3 = 's3'\nARCHIVE_GS = 'gs'\n\n\ndef init_archive(archive_type=settings.ARCHIVE_TYPE,\n path=settings.ARCHIVE_PATH,\n bucket=settings.ARCHIVE_BUCKET):\n \"\"\"Instantiate an archive object.\"\"\"\n if archive_type == ARCHIVE_S3:\n from servicelayer.archive.s3 import S3Archive\n return S3Archive(bucket=bucket)\n\n if archive_type == ARCHIVE_GS:\n from servicelayer.archive.gs import GoogleStorageArchive\n return GoogleStorageArchive(bucket=bucket)\n\n return FileArchive(path=path)\n"
},
{
"alpha_fraction": 0.6259351372718811,
"alphanum_fraction": 0.6296758055686951,
"avg_line_length": 30.45098114013672,
"blob_id": "25d5aa58b8efb32cf4f9c713be8b41a152e5d32c",
"content_id": "5e78625b40e68706e4f90d9f7b0ee106705ce382",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1604,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 51,
"path": "/tests/archive/test_s3.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "from unittest import TestCase\n\nfrom moto import mock_s3\n\nfrom servicelayer.archive import init_archive\nfrom servicelayer.archive.util import checksum, ensure_path\n\n\nclass FileArchiveTest(TestCase):\n\n def setUp(self):\n self.mock = mock_s3()\n self.mock.start()\n self.archive = init_archive('s3', bucket='foo')\n self.file = ensure_path(__file__)\n\n def tearDown(self):\n self.mock.stop()\n\n def test_basic_archive(self):\n checksum_ = checksum(self.file)\n assert checksum_ is not None, checksum_\n out = self.archive.archive_file(self.file)\n assert checksum_ == out, (checksum_, out)\n out2 = self.archive.archive_file(self.file)\n assert out == out2, (out, out2)\n\n def test_basic_archive_with_checksum(self):\n checksum_ = 'banana'\n out = self.archive.archive_file(self.file, checksum_)\n assert checksum_ == out, (checksum_, out)\n\n def test_generate_url(self):\n out = self.archive.archive_file(self.file)\n url = self.archive.generate_url(out)\n # assert False, url\n assert url is not None, url\n\n def test_load_file(self):\n out = self.archive.archive_file(self.file)\n path = self.archive.load_file(out)\n assert path is not None, path\n assert path.is_file(), path\n\n def test_cleanup_file(self):\n out = self.archive.archive_file(self.file)\n self.archive.cleanup_file(out)\n path = self.archive.load_file(out)\n assert path.is_file(), path\n self.archive.cleanup_file(out)\n assert not path.exists(), path\n"
},
{
"alpha_fraction": 0.5786163806915283,
"alphanum_fraction": 0.593710720539093,
"avg_line_length": 25.5,
"blob_id": "e2c7578a60353dc4f265c423bb7f73b01aeb19a4",
"content_id": "1890e7b9accd73cac41c918e660cf4678cd710ce",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 795,
"license_type": "permissive",
"max_line_length": 56,
"num_lines": 30,
"path": "/servicelayer/archive/util.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "from hashlib import sha1\nfrom pathlib import Path\n\nBUF_SIZE = 1024 * 1024 * 16\n\n\ndef ensure_path(file_path):\n if file_path is None or isinstance(file_path, Path):\n return file_path\n return Path(file_path).resolve()\n\n\ndef ensure_posix_path(file_path):\n if isinstance(file_path, Path):\n file_path = file_path.as_posix()\n return file_path\n\n\ndef checksum(file_name):\n \"\"\"Generate a hash for a given file name.\"\"\"\n file_name = ensure_path(file_name)\n if file_name is not None and file_name.is_file():\n digest = sha1()\n with open(file_name, 'rb') as fh:\n while True:\n block = fh.read(BUF_SIZE)\n if not block:\n break\n digest.update(block)\n return str(digest.hexdigest())\n"
},
{
"alpha_fraction": 0.8130968809127808,
"alphanum_fraction": 0.8144611120223999,
"avg_line_length": 47.86666488647461,
"blob_id": "db60bfa9348cea879dfcd5c130495e164dc38a59",
"content_id": "193c530e33d9936ee0ec364b22edcf5c7f54ad41",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 733,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 15,
"path": "/README.md",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "# servicelayer\n\n[](https://travis-ci.org/alephdata/servicelayer)\n\nComponents of the aleph data toolkit needed to interact with networked services,\nsuch as a storage archive, cache, document conversion and named entity\nextraction. This package contains some common configuration components for\nall of these services using environment variables. It also contains the protocol\ndefinition files for the gRPC/protobuf interfaces used by aleph.\n\n## archive mechanism\n\nThis library provides a configurable method for file storage used by aleph and\nmemorious. It will store files based on their content hash (SHA1) and allows for\nlater retrieval of the content.\n"
},
{
"alpha_fraction": 0.607239842414856,
"alphanum_fraction": 0.6126697063446045,
"avg_line_length": 26.625,
"blob_id": "09176d9ed15cd53cb145729b765c952cd87c98d1",
"content_id": "fa005f5c5a17b209312a1347603061228256976c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1105,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 40,
"path": "/tests/test_worker.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "from unittest import TestCase\n\nfrom servicelayer.cache import get_fakeredis\nfrom servicelayer.jobs import Job, Stage, Task\nfrom servicelayer.worker import Worker\n\n\nclass CountingWorker(Worker):\n\n def boot(self):\n self.test_done = 0\n\n def handle(self, task):\n self.test_done += 1\n\n\nclass WorkerTest(TestCase):\n\n def test_run(self):\n conn = get_fakeredis()\n operation = 'lala'\n worker = CountingWorker(conn=conn, stages=[operation])\n worker.sync()\n assert worker.test_done == 0, worker.test_done\n job = Job.create(conn, 'test')\n stage = job.get_stage(operation)\n task = stage.queue({}, {})\n assert not job.is_done()\n assert worker.test_done == 0, worker.test_done\n worker.sync()\n assert worker.test_done == 1, worker.test_done\n assert job.is_done()\n worker.retry(task)\n assert not job.is_done()\n worker.sync()\n assert job.is_done()\n assert worker.test_done == 1, worker.test_done\n worker.shutdown()\n worker.retry(task)\n worker.process()\n"
},
{
"alpha_fraction": 0.7248322367668152,
"alphanum_fraction": 0.7516778707504272,
"avg_line_length": 20.285715103149414,
"blob_id": "10ef2e644e630f99e9dad647e92007a69b5f3b95",
"content_id": "befc32f958adede58a8811459ef83403d5ddefbd",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 149,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 7,
"path": "/servicelayer/__init__.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "import logging\n\n__version__ = '1.9.6'\n\n\nlogging.getLogger('boto3').setLevel(logging.WARNING)\nlogging.getLogger('botocore').setLevel(logging.WARNING)\n"
},
{
"alpha_fraction": 0.5853058695793152,
"alphanum_fraction": 0.5859206914901733,
"avg_line_length": 29.120370864868164,
"blob_id": "4c06361085614ef52971f5d8932f8980a9eb7a49",
"content_id": "3c7c886e8b355c03a2e1dc8281d76713fd0948bb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3253,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 108,
"path": "/servicelayer/worker.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "import signal\nimport logging\nfrom threading import Thread\nfrom abc import ABC, abstractmethod\n\nfrom servicelayer import settings\nfrom servicelayer.jobs import Stage\nfrom servicelayer.cache import get_redis\nfrom servicelayer.util import unpack_int\n\nlog = logging.getLogger(__name__)\n\n\nclass Worker(ABC):\n \"\"\"Workers of all microservices, unite!\"\"\"\n\n def __init__(self, conn=None, stages=None,\n num_threads=settings.WORKER_THREADS):\n self.conn = conn or get_redis()\n self.stages = stages\n self.num_threads = num_threads\n self._shutdown = False\n\n def shutdown(self, *args):\n log.warning(\"Shutting down worker.\")\n self._shutdown = True\n if not self.num_threads:\n raise SystemExit()\n\n def handle_safe(self, task):\n try:\n self.handle(task)\n except (SystemExit, KeyboardInterrupt, Exception):\n self.retry(task)\n raise\n finally:\n task.done()\n self.after_task(task)\n\n def init_internal(self):\n self._shutdown = False\n self.boot()\n\n def retry(self, task):\n retries = unpack_int(task.context.get('retries'))\n if retries < settings.WORKER_RETRY:\n log.warning(\"Queue failed task for re-try...\")\n task.context['retries'] = retries + 1\n task.stage.queue(task.payload, task.context)\n\n def process(self, interval=5):\n while True:\n if self._shutdown:\n return\n self.periodic()\n stages = self.get_stages()\n task = Stage.get_task(self.conn, stages, timeout=interval)\n if task is None:\n continue\n self.handle_safe(task)\n\n def sync(self):\n \"\"\"Process only the tasks already in the job queue, but do not\n go into an infinte loop waiting for new ones.\"\"\"\n self.init_internal()\n while True:\n stages = self.get_stages()\n task = Stage.get_task(self.conn, stages, timeout=None)\n if task is None:\n return\n self.handle_safe(task)\n\n def run(self):\n # Try to quit gracefully, e.g. after finishing the current task.\n signal.signal(signal.SIGINT, self.shutdown)\n signal.signal(signal.SIGTERM, self.shutdown)\n self.init_internal()\n if not self.num_threads:\n return self.process()\n log.info(\"Worker has %d threads.\", self.num_threads)\n threads = []\n for _ in range(self.num_threads):\n thread = Thread(target=self.process)\n thread.daemon = True\n thread.start()\n threads.append(thread)\n for thread in threads:\n thread.join()\n\n def get_stages(self):\n \"\"\"Easily allow the user to make the active stages dynamic.\"\"\"\n return self.stages\n\n def boot(self):\n \"\"\"Optional hook for the boot-up of the worker.\"\"\"\n pass\n\n def periodic(self):\n \"\"\"Optional hook for running a periodic task checker.\"\"\"\n pass\n\n def after_task(self, task):\n \"\"\"Optional hook excuted after handling a task\"\"\"\n pass\n\n @abstractmethod\n def handle(self, task):\n raise NotImplementedError\n"
},
{
"alpha_fraction": 0.4919246435165405,
"alphanum_fraction": 0.5201884508132935,
"avg_line_length": 26.518518447875977,
"blob_id": "8760bcc306119b806cac84810025bf1ad911becd",
"content_id": "e61cf7958588c13350ef864bf0b007639f5f97d9",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1486,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 54,
"path": "/setup.py",
"repo_name": "nashtash/servicelayer",
"src_encoding": "UTF-8",
"text": "from setuptools import setup, find_packages\n\n\nsetup(\n name='servicelayer',\n version='1.9.6',\n description=\"Basic remote service functions for alephdata components\",\n classifiers=[\n \"Development Status :: 3 - Alpha\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n keywords='storage files s3',\n author='Organized Crime and Corruption Reporting Project',\n author_email='[email protected]',\n url='http://github.com/alephdata/servicelayer',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples', 'test']),\n namespace_packages=[],\n include_package_data=True,\n zip_safe=True,\n install_requires=[\n 'banal >= 0.4.2',\n 'six >= 1.12.0',\n 'normality >= 1.0.0',\n 'redis == 3.3.11',\n 'fakeredis == 1.1.0',\n ],\n extras_require={\n 'amazon': [\n 'boto3 >= 1.9.71',\n ],\n 'google': [\n 'google-cloud-storage >= 1.10.0',\n ],\n 'dev': [\n 'twine',\n 'moto',\n 'boto3 >= 1.9.71',\n 'pytest >= 3.6',\n 'coverage',\n 'pytest-cov',\n ]\n },\n test_suite='tests',\n entry_points={\n 'servicelayer.test': [\n 'test = servicelayer.extensions:get_extensions',\n ]\n }\n)\n"
}
] | 10 |
ip2k/wunder-star
|
https://github.com/ip2k/wunder-star
|
e3316155ac40070a0f088f0d91a492683651e129
|
d266baf55566fbf60cef5acf9cde83318aa76c26
|
a0ba7fbe107869d0a7cf1d699b7ec6ce0cfcb1f2
|
refs/heads/master
| 2021-01-22T06:58:57.854121 | 2014-11-05T21:05:29 | 2014-11-05T21:05:29 | 26,238,350 | 2 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5438052415847778,
"alphanum_fraction": 0.547249972820282,
"avg_line_length": 34.98760223388672,
"blob_id": "7e81c5658d0329bf61b2397af7f4600d74fada7a",
"content_id": "21d49a0b5c9aa514fd50324e11b4e708c3d72515",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8709,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 242,
"path": "/lib/python2.7/site-packages/wunderpy/cli/main.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''Command line script for wunderpy.'''\n\n\nimport argparse\nfrom datetime import date, timedelta\n\nfrom wunderpy import Wunderlist\nfrom .storage import get_token, setup\nimport wunderpy.cli.colors as colors\nimport wunderpy.cli.six as six\n\n\nclass WunderlistCLI(object):\n '''Handles basic tasks performed by the CLI app.'''\n\n def __init__(self):\n self.wunderlist = None\n self.get_wunderlist()\n\n def get_wunderlist(self):\n try:\n token = get_token()\n except IOError: # first run\n setup()\n token = get_token()\n\n wunderlist = Wunderlist()\n wunderlist.set_token(token)\n wunderlist.update_lists()\n self.wunderlist = wunderlist\n\n def print_tasks(self, tasks, limit):\n '''\n :param tasks: A dict with key: TaskList, value: list of Tasks\n '''\n\n with colors.pretty_output(colors.BOLD, colors.UNDERSCORE) as out:\n for list_title, _tasks in six.iteritems(tasks):\n if len(_tasks) > 0:\n out.write(\"\\n\" + list_title)\n\n tasks_printed = 0\n for task in _tasks:\n if tasks_printed < limit:\n pretty_print_task(task)\n tasks_printed += 1\n\n def add(self, task_title, list_title):\n '''Add a task or create a list.\n If just --task is used, optionally with --list, add a task.\n If just --list is used, create an empty list.\n '''\n\n if task_title and list_title: # adding a task to a list\n self.wunderlist.add_task(task_title, list_title=list_title)\n elif list_title != \"inbox\": # creating a list\n self.wunderlist.add_list(list_title)\n\n def complete(self, task_title, list_title):\n '''Complete a task'''\n\n self.wunderlist.complete_task(task_title, list_title=list_title)\n\n def delete_task(self, task_title, list_title):\n '''Delete a task'''\n\n self.wunderlist.delete_task(task_title, list_title)\n\n def delete_list(self, list_title):\n '''Delete a list'''\n\n self.wunderlist.delete_list(list_title)\n\n def overview(self, limit, show_complete):\n '''Display a few tasks from each list.\n :param limit: Maximum number of tasks to display per list.\n :type limit: int\n :param show_complete: Disply completed tasks?\n :type show_complete: bool\n '''\n\n to_print = {}\n for task_list in self.wunderlist.lists:\n if show_complete:\n to_print[task_list.title] = task_list.tasks\n else:\n tasks = task_list.incomplete_tasks()\n to_print[task_list.title] = tasks\n\n self.print_tasks(to_print, limit)\n\n def today(self, limit, show_complete):\n '''Display tasks that are due or overdue today.\n :param limit: Maximum number of tasks to display per list.\n :type limit: int\n :param show_complete: Display completed tasks?\n :type show_complete: bool\n '''\n\n to_print = {}\n for task_list in self.wunderlist.lists:\n tasks = task_list.tasks_due_before(date.today() +\n timedelta(days=1))\n if show_complete:\n to_print[task_list.title] = tasks\n else:\n _tasks = [t for t in tasks if t.completed is not True]\n to_print[task_list.title] = _tasks\n\n self.print_tasks(to_print, limit)\n\n def week(self, limit, show_complete):\n '''Display tasks that are due or overdue this week.\n :param limit: Maximum number of tasks to display per list.\n :type limit: int\n :param show_complete: Display completed tasks?\n :type show_complete: bool\n '''\n\n to_print = {}\n for task_list in self.wunderlist.lists:\n tasks = task_list.tasks_due_before(date.today() +\n timedelta(days=6))\n if show_complete:\n to_print[task_list.title] = tasks\n else:\n _tasks = [t for t in tasks if t.completed is not True]\n to_print[task_list.title] = _tasks\n\n self.print_tasks(to_print, limit)\n\n def display(self, list_title, show_complete):\n '''Display all tasks in a list.\n :param list_title: Title of the list to display.\n :type list_title: str\n :param show_complete: Display completed tasks?\n :type show_complete: bool\n '''\n\n _list = self.wunderlist.list_with_title(list_title)\n to_print = {}\n\n if show_complete:\n to_print[_list.title] = _list.tasks\n else:\n _tasks = [t for t in _list.tasks if t.completed is not True]\n to_print[_list.title] = _tasks\n\n self.print_tasks(to_print, len(to_print[_list.title]))\n\n\ndef pretty_print_task(task):\n '''Take a Task object and format it like so:\n [ (check) ] title (star)\n '''\n\n if six.PY2:\n check_mark = u\"\\u2713\".encode(\"utf-8\")\n star = u\"\\u2605\".encode(\"utf-8\")\n elif six.PY3:\n check_mark = u\"\\u2713\"\n star = u\"\\u2605\"\n\n is_completed = check_mark # in other words, True\n if not task.completed:\n is_completed = \" \" # not completed, False\n\n use_star = star # True\n if not task.starred:\n use_star = \"\" # False\n\n if six.PY2:\n line = \"[{}] {} {}\".format(is_completed,\n task.title.encode(\"utf-8\"),\n use_star)\n elif six.PY3:\n line = \"[{}] {} {}\".format(is_completed,\n task.title,\n use_star)\n print(line)\n\n\ndef main():\n '''Entry point'''\n\n parser = argparse.ArgumentParser(description=\"A Wunderlist CLI client.\")\n\n parser.add_argument(\"-a\", \"--add\", dest=\"add\", action=\"store_true\",\n default=False, help=\"Add a task or list.\")\n parser.add_argument(\"-c\", \"--complete\", dest=\"complete\",\n action=\"store_true\", default=False,\n help=\"Complete a task.\")\n parser.add_argument(\"-d\", \"--delete\", dest=\"delete\", action=\"store_true\",\n default=False, help=\"Delete a task or list.\")\n parser.add_argument(\"-o\", \"--overview\", dest=\"overview\",\n action=\"store_true\", default=False,\n help=\"Display an overview of your Wunderlist.\")\n parser.add_argument(\"--week\", dest=\"week\", action=\"store_true\",\n default=False, help=\"Display all incomplete tasks\"\n \"that are overdue or due in the next week.\")\n parser.add_argument(\"--today\", dest=\"today\", action=\"store_true\",\n default=False, help=\"Display all incomplete tasks \"\n \"that are overdue or due today.\")\n parser.add_argument(\"--display\", dest=\"display\", action=\"store_true\",\n default=False, help=\"Display all items in a list \"\n \"specified with --list.\")\n parser.add_argument(\"--show-complete\", dest=\"show_complete\",\n action=\"store_true\", default=False,\n help=\"Display complete tasks, \"\n \"by default only incomplete are shown.\")\n parser.add_argument(\"-n\", \"--num\", dest=\"num_tasks\", type=int, default=5,\n help=\"Choose the number of tasks to display from \"\n \"each list. [default 5]\")\n parser.add_argument(\"-l\", \"--list\", dest=\"list\", default=\"inbox\",\n help=\"Used to specify a list, either for a task in a \"\n \"certain list, or for a command that only operates \"\n \"on lists. Default is inbox.\")\n parser.add_argument(\"-t\", \"--task\", dest=\"task\",\n help=\"Used to specify a task name.\")\n args = parser.parse_args()\n\n cli = WunderlistCLI()\n\n if args.add:\n cli.add(args.task, args.list)\n elif args.complete:\n cli.complete(args.task, args.list)\n elif args.delete:\n if args.task:\n cli.delete_task(args.task, args.list)\n else:\n cli.delete_list(args.list)\n elif args.today:\n cli.today(args.num_tasks, args.show_complete)\n elif args.week:\n cli.week(args.num_tasks, args.show_complete)\n elif args.overview:\n cli.overview(args.num_tasks, args.show_complete)\n elif args.display:\n cli.display(args.list, args.show_complete)\n else:\n cli.overview(args.num_tasks, args.show_complete)\n"
},
{
"alpha_fraction": 0.7888888716697693,
"alphanum_fraction": 0.7888888716697693,
"avg_line_length": 29,
"blob_id": "95660830a2229c542d701fdb0d55261b29207a46",
"content_id": "70c26e7f22ea897216fb5132105edc7ea64813ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 90,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 3,
"path": "/lib/python2.7/site-packages/wunderpy/wunderlist/__init__.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''Classes implementing a basic Wunderlist client.'''\n\nfrom .wunderlist import Wunderlist\n"
},
{
"alpha_fraction": 0.6129032373428345,
"alphanum_fraction": 0.6330121755599976,
"avg_line_length": 41.625,
"blob_id": "bbf7f2a955b029476a4aeea470a0153f619f8f3e",
"content_id": "a255d92e34fba9040978036ea82dd5ffb07c76fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2387,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 56,
"path": "/wunder-star.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "from datetime import datetime\nfrom wunderpy import Wunderlist\nfrom github import Github\nimport base64\nimport time\n\nWL_USER = 'your-wunderlist-login'\nWL_PASS = base64.b64decode('base64-of-your-wunderlist-password')\nWL_LIST_NAME = 'Github Starred' # name of list to add stars to. Must exist ahead of time.\nGH_TOKEN = 'see https://github.com/settings/tokens/new'\n\n# get wunderlist stuff\nprint \">>>>> WUNDER-STAR STARTED {} <<<<<\".format(time.asctime( time.localtime(time.time()) ))\nprint \"Getting list from Wunderlist...\"\nw = Wunderlist()\nw.login(WL_USER, WL_PASS)\nw.update_lists()\ntasks = w.tasks_for_list(WL_LIST_NAME)\n\n# get github stuff\nprint \"Getting stars from GitHub (this may take a bit)\"\ngh = Github(login_or_token=GH_TOKEN)\nme = gh.get_user()\nrepos = [repo for repo in me.get_starred()]\n\n# get what projects are already in Wunderlist by splitting on :\nprint \"Comparing stars to Wunderlist items...\"\ntask_title_list = [task.title.split(':')[0].encode('ISO-8859-1', 'ignore') for task in w.tasks_for_list(WL_LIST_NAME)]\nadded = 0\nskipped = 0\nnotes = 0\nerror = 0\nfor repo in repos:\n repo_name = repo.full_name.encode('ISO-8859-1', 'ignore')\n if repo_name in task_title_list:\n skipped +=1\n print \"{} already in Wunderlist. Skipping...\".format(repo_name)\n else:\n try:\n info = \"{}: {} // {}\".format(repo_name, repo.description.encode('ISO-8859-1', 'ignore'), repo.homepage.encode('ISO-8859-1', 'ignore'))\n w.add_task(title=info, list_title=WL_LIST_NAME, note=None, due_date=None, starred=False)\n added +=1\n except Exception as e:\n print \"Couldn\\'t add {} ... exception: {} ... will retry with description as a note....\".format(repo_name, e)\n\t try:\n info = \"{}: [too long; see notes] // {}\".format(repo_name, repo.homepage.encode('ISO-8859-1', 'ignore'))\n\t\tdesc = repo.description.encode('ISO-8859-1', 'ignore')\n w.add_task(title=info, list_title=WL_LIST_NAME, note=desc, due_date=None, starred=False)\n added += 1\n notes += 1\n except Exception as e:\n print \"Couldn\\'t add {} ... exception: {} ... retry didn't work...skipping...\".format(repo_name, e)\n error +=1\n pass\n\nprint \"Done. Added {} ({} with description in notes)// skipped {} // {} errors\".format(added, notes, skipped, error)\n"
},
{
"alpha_fraction": 0.7948718070983887,
"alphanum_fraction": 0.7948718070983887,
"avg_line_length": 22.399999618530273,
"blob_id": "68f448a68af1268cef6485f145cb07d0e7011413",
"content_id": "48b1265cc47c34e2a833a00ad6c7f30f3ece92d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 117,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 5,
"path": "/lib/python2.7/site-packages/wunderpy/api/__init__.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''Interface package for the Wunderlist API'''\n\n\nfrom wunderpy.api.client import APIClient\nimport wunderpy.api.calls\n"
},
{
"alpha_fraction": 0.5515275001525879,
"alphanum_fraction": 0.5523421764373779,
"avg_line_length": 27.882352828979492,
"blob_id": "1b91499c5e492d53c69749a89b911cf57b180ee7",
"content_id": "61d03ba6d6b79f4dc5228553e101fec9d0735efb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2455,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 85,
"path": "/lib/python2.7/site-packages/wunderpy/wunderlist/task_list.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''Implements the TaskList class.'''\n\n\nclass TaskList(dict):\n '''Object representing a single task list in Wunderlist.'''\n\n def __init__(self, info, tasks=None, *args):\n '''\n :param tasks: A list of Task objects this list contains.\n :type tasks: list\n :param info: Information dict about the list returned by the API.\n :type info: dict\n '''\n\n if tasks:\n self.tasks = tasks\n else:\n self.tasks = []\n self.info = info\n dict.__init__(self, args)\n\n def __getitem__(self, key):\n return dict.__getitem__(self.info, key)\n\n def __setitem__(self, key, value):\n dict.__setitem__(self.info, key, value)\n\n def __repr__(self):\n return \"<wunderpy.wunderlist.TaskList: {} {}>\".format(self.title,\n self.id)\n\n @property\n def title(self):\n '''The TaskList's title.'''\n return self.info.get(\"title\")\n\n @property\n def id(self):\n '''The TaskList's ID.'''\n\n return self.info.get(\"id\")\n\n def add_task(self, task):\n '''Add a Task to the list.'''\n self.tasks.append(task)\n\n def remove_task(self, task):\n '''Remove a Task from the TaskList.'''\n\n self.tasks.remove(task)\n\n def task_with_title(self, title):\n '''Return the most recently created Task with the given title.'''\n\n tasks = self.tasks_with_title(title)\n if len(tasks) >= 1:\n #return most recent task\n tasks = sorted(tasks, key=lambda t: t.created_at, reverse=True)\n return tasks[0]\n else:\n return None\n\n def tasks_with_title(self, title):\n '''Find all Tasks with the given title.\n :param title: Title to match Tasks with.\n :type title: str\n '''\n return [task for task in self.tasks if task.title == title]\n\n def tasks_due_before(self, date):\n '''Find all Tasks that are due before date.'''\n\n return [task for task in self.tasks\n if task.due_date and task.due_date < date]\n\n def tasks_due_on(self, date):\n '''Find all Tasks that are due on date.'''\n\n return [task for task in self.tasks\n if task.due_date and task.due_date == date]\n\n def incomplete_tasks(self):\n '''Return all incomplete tasks.'''\n\n return [task for task in self.tasks if task.completed is not True]\n"
},
{
"alpha_fraction": 0.7272727489471436,
"alphanum_fraction": 0.7272727489471436,
"avg_line_length": 43,
"blob_id": "4456638db8ce59484b82cf0b92d8a5041ae6b2f5",
"content_id": "07f386ac341641cefc0ade48b63512f75567a346",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 1,
"path": "/lib/python2.7/site-packages/wunderpy/cli/__init__.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''A command line utility for Wunderlist'''\n"
},
{
"alpha_fraction": 0.5539345741271973,
"alphanum_fraction": 0.5543766617774963,
"avg_line_length": 24.133333206176758,
"blob_id": "19ea9b224919ce8c3c9f564bb80a471ecf122a89",
"content_id": "a0a3df121cf4fc5c12f1b7916681ce57cbfc84bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2262,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 90,
"path": "/lib/python2.7/site-packages/wunderpy/wunderlist/task.py",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "'''Implements the Task class.'''\n\n\nimport dateutil.parser\n\n\nclass Task(dict):\n '''Object representing a single task in Wunderlist.'''\n\n def __init__(self, info, parent_list=None, subtasks=None, *args):\n '''\n :param info: The task information obtained from the API.\n :type info: dict\n :param parent_list: The TaskList this Task belongs to.\n :type parent_list: TaskList\n :param subtasks: A list of Task objects belonging to this TAsk.\n :type subtasks: list or None\n '''\n\n self.parent_list = parent_list\n self.info = info\n if subtasks:\n self.subtasks = subtasks\n else:\n self.subtasks = []\n dict.__init__(self, args)\n\n def __getitem__(self, key):\n return dict.__getitem__(self.info, key)\n\n def __setitem__(self, key, value):\n dict.__setitem__(self.info, key, value)\n\n def __repr__(self):\n return \"<wunderpy.wunderlist.Task: {} {}>\".format(self.title, self.id)\n\n @property\n def title(self):\n '''The Task's title.'''\n\n return self.info.get(\"title\")\n\n @property\n def id(self):\n '''The Task's ID.'''\n\n return self.info.get(\"id\")\n\n @property\n def created_at(self):\n '''Return a Datetime object for the moment the Task was created.'''\n\n created = self.info.get(\"created_at\")\n if created:\n return dateutil.parser.parse(created)\n else:\n return None\n\n @property\n def due_date(self):\n '''Return a Date object with the date the Task is due, if any.'''\n\n due = self.info.get(\"due_date\")\n if due:\n return dateutil.parser.parse(due).date()\n else:\n return None\n\n @property\n def due_date_iso(self):\n '''Return the due date as a sting in ISO format.'''\n\n return self.info.get(\"due_date\")\n\n @property\n def completed(self):\n '''Return the Task's completion status'''\n if self.info.get(\"completed_at\"):\n return True\n else:\n return False\n\n @property\n def starred(self):\n '''Is the Task starred?'''\n\n if self.info.get(\"starred\") == 1:\n return True\n else:\n return False\n"
},
{
"alpha_fraction": 0.4848484992980957,
"alphanum_fraction": 0.6969696879386902,
"avg_line_length": 15.5,
"blob_id": "8ada3a97781bd1697dcd716ac8385b6bf8044ba8",
"content_id": "f3792ecd86c805ada6c499447ba538de4bf4264e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 33,
"license_type": "no_license",
"max_line_length": 16,
"num_lines": 2,
"path": "/requirements.txt",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "wunderpy==0.2.5\nPyGithub==1.25.2\n"
},
{
"alpha_fraction": 0.6363636255264282,
"alphanum_fraction": 0.662756621837616,
"avg_line_length": 33.099998474121094,
"blob_id": "76d2cb82525bfc1f8723d24253efc4868928727a",
"content_id": "5b6144ec119261558d305fe3224e7f7a86001e6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 341,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 10,
"path": "/bin/wunderlist",
"repo_name": "ip2k/wunder-star",
"src_encoding": "UTF-8",
"text": "#!/Users/spetrow/projects/wunder-star/bin/python\n# EASY-INSTALL-ENTRY-SCRIPT: 'wunderpy==0.2.5','console_scripts','wunderlist'\n__requires__ = 'wunderpy==0.2.5'\nimport sys\nfrom pkg_resources import load_entry_point\n\nif __name__ == '__main__':\n sys.exit(\n load_entry_point('wunderpy==0.2.5', 'console_scripts', 'wunderlist')()\n )\n"
}
] | 9 |
mkashiwa/slopesense
|
https://github.com/mkashiwa/slopesense
|
c65af47dbb104e0d638ceee9b6005d5f815d1552
|
52b77a66c41b86f29cd9dd7481905a65b22c7a31
|
c12f1ed46bcb73350aad6dab74b759db3778c8aa
|
refs/heads/master
| 2022-12-03T18:27:39.707742 | 2020-08-12T11:14:58 | 2020-08-12T11:14:58 | 286,993,504 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6337448358535767,
"alphanum_fraction": 0.6502057909965515,
"avg_line_length": 39.5,
"blob_id": "7ef882373c14b4e6359040e68b96250de2e88eb4",
"content_id": "52d3b8b55c4a8d8a4b8db3b4223203d2a54c27aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 243,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 6,
"path": "/main.py",
"repo_name": "mkashiwa/slopesense",
"src_encoding": "UTF-8",
"text": "def on_forever():\n serial.write_line(\"Pitch: \" + str(input.rotation(Rotation.PITCH)))\n serial.write_line(\"Roll : \" + str(input.rotation(Rotation.ROLL)))\n serial.write_line(\"----------\")\n basic.pause(1000)\nbasic.forever(on_forever)\n"
},
{
"alpha_fraction": 0.6363636255264282,
"alphanum_fraction": 0.6440678238868713,
"avg_line_length": 45.35714340209961,
"blob_id": "946b6fc083a16477048b53d1541135b4758fe641",
"content_id": "2cbdcad876783fdb7b3517bb3c7455b7cca5f5c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 649,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 14,
"path": "/main.ts",
"repo_name": "mkashiwa/slopesense",
"src_encoding": "UTF-8",
"text": "let direct = 0\ninput.calibrateCompass()\nbasic.forever(function () {\n direct = input.compassHeading()\n serial.writeLine(\"Pitch: \" + input.rotation(Rotation.Pitch) + \" deg\")\n serial.writeLine(\"Roll : \" + input.rotation(Rotation.Roll) + \" deg\")\n serial.writeLine(\"Temp : \" + input.temperature() + \" deg\")\n serial.writeLine(\"Direc: \" + direct + \" deg\")\n serial.writeLine(\"MagnX: \" + input.magneticForce(Dimension.X) + \" uT\")\n serial.writeLine(\"MagnY: \" + input.magneticForce(Dimension.Y) + \" uT\")\n serial.writeLine(\"MagnZ: \" + input.magneticForce(Dimension.Z) + \" uT\")\n serial.writeLine(\"----------\")\n basic.pause(1000)\n})\n"
}
] | 2 |
neizvesten/pykt
|
https://github.com/neizvesten/pykt
|
226b5afb836168707035727656a0a8c13421cd9e
|
fe063a2ceb9d0a38f7be61480130cda9f5525167
|
212402cca62b1969fa82794dc7fb50a1170a7601
|
refs/heads/master
| 2018-01-10T09:13:14.253359 | 2015-12-01T00:13:29 | 2015-12-01T00:13:29 | 47,153,808 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5098176598548889,
"alphanum_fraction": 0.5182328224182129,
"avg_line_length": 30.688888549804688,
"blob_id": "ae786ec4a0e9ee775ddc7812eb4574b117b9703f",
"content_id": "ef7208936c8d9a467373bf4a25b1e05680b2cd69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1426,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 45,
"path": "/client.py",
"repo_name": "neizvesten/pykt",
"src_encoding": "UTF-8",
"text": "import socket\nimport time\nimport os\n\n\nwhile True:\n client_socket=socket.socket()\n try: #if server unavailable\n client_socket.connect(('localhost', 12345))\n except socket.error:\n# print \"Connection refused. Try again after 5 seconds.\"\n time.sleep(5)\n else:\n# print \"Connection established. Wait for commands\"\n try: #if server fail\n command=client_socket.recv(1024)\n except socket.error:\n continue\n else:\n if command==\"r\":\n# print \"Recieved command for report.\"\n os.system(\"echo '\\n<top>\\n' > report\")\n os.system(\"top -b -n 1 >> report\")\n os.system(\"echo '\\n</top>\\n\\n\\n<service>\\n' >> report\")\n os.system(\"rcconf --list --expert >> report\")\n os.system(\"echo '\\n</service>\\n\\n\\n<ifconfig>\\n' >> report\")\n os.system(\"ifconfig >> report\")\n os.system(\"echo '\\n</ifconfig>\\n' >> report\")\n file=open(\"report\",'r')\n for line in file:\n try:\n client_socket.send(line)\n except socket.error:\n continue\n# else:\n# print \"----------------------------------------------------\"\n# print line\n# print \"----------------------------------------------------\"\n try:\n client_socket.send(\"end_report\")\n except socket.error:\n continue\n file.close() \n# print \"Report has been sended\"\n client_socket.close()\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6088135838508606,
"avg_line_length": 27.365385055541992,
"blob_id": "ec1639683c4cd7bccbf1cc75c3399d10cd6c63f5",
"content_id": "a0f28f000ff5403c3d78123e901cee03b7fc3a02",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1475,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 52,
"path": "/server.py",
"repo_name": "neizvesten/pykt",
"src_encoding": "UTF-8",
"text": "import socket\nimport re\nimport sqlite3\n\nprint \"Binding socket\"\nserver_socket=socket.socket()\nserver_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver_socket.bind(('', 12345))\nserver_socket.listen(1)\nserver_socket.settimeout(1)\n\nwhile True:\n print \"Waiting for connection\"\n try:\n connection, addr = server_socket.accept()\n except socket.error:\n print \"There are no tryings for connect.\\nType 'r' for resume listening\\nOr 'q' for halt server\"\n command=raw_input('>>')\n if command==\"r\":\n continue\n elif command==\"q\":\n server_socket.close()\n break\n else:\n print 'connected:', addr\n print \"Please, type:\\n'r' for get report from server\\n'q' for halt server\"\n command=raw_input('>>')\n if command==\"r\":\n connection.send('r')\n buf=\"\"\n while True:\n line=connection.recv(1024)\n if not line:\n print \"Client seems to be disconnected.\\nType 'b' for break connection and start new listening\\nOr 't' for try one more time\"\n command=raw_input(\">>\")\n if command==\"b\":\n connection.close()\n break\n elif command==\"t\":\n continue\n buf+=line\n if re.search(r'end_report',line):\n break\n connection.close()\n print buf\n\n elif command==\"q\":\n print \"Will now halt\"\n connection.close()\n server_socket.shutdown(socket.SHUT_RDWR)\n server_socket.close()\n break\n"
}
] | 2 |
Sicarius154/ZumoPy
|
https://github.com/Sicarius154/ZumoPy
|
02d465211fc7efe73d74adc6fd6db9513501b43d
|
0f22724601a2281901172df508c48301e68c5522
|
72122cf74dbd992f3cd195e889663cac81a5afeb
|
refs/heads/master
| 2020-03-27T23:42:50.856711 | 2018-09-06T12:20:56 | 2018-09-06T12:20:56 | 147,340,084 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7124183177947998,
"alphanum_fraction": 0.7245565056800842,
"avg_line_length": 78.33333587646484,
"blob_id": "8ab31b2c08d09fbce2891ce429a3b3ded2513dbc",
"content_id": "89b80b235c37c3d8521d1f2336bb2f71ca992aa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2142,
"license_type": "no_license",
"max_line_length": 456,
"num_lines": 27,
"path": "/README.MD",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "# ZumoPy\nZumoPy is a librry designed to pair the Zumo 32u4 and a rapsberry pi microcomputer. The code is designed with the inclusion of a raspberry pi on the zumo itself in mind.\n\n## How it works\nThere are two components. The Pi side, and the Zumo side. The Zumo component will be run on the Zumo itself, and will contain all of the code necesary for manipulating and controlling the zumo. This code will simply listen for commands and act upon them.\n\nThe Pi side is what the user will see. It will contain many high level functions to facilitate the controlling of the Zumo. All error checking, data validation and so forth is done here. With minimal logic required on the Zumo\n\n# Instructions and communication\n\n## Communication\nThe library is designed to use the serial connection found on the raspberry pi and the Zumo. Data transfer is limited to X bits per second.\n\n## Instructions\nThe ZumoPy interface works with a limited instruction length, to allow for simplicity and minimal data transfer. Due to the limitations of serial, and ensuring data can be transfered at a reliable rate instructions are kept short and easy to parse. Below is a list of instructions that the Zumo will accept and ackknowledge. Any incorrect instructions are simply **discarded and ignored**. The '^' character denotes an unused char in the instruction string\nThe first character of an instruction denotes the type of instruction:\n0 = Get sensor data (Sending these instructions tell the Zumo to send the most recent sensor data back)\n1 = Set motors (Used for movement and turning)\n|Instruction|Usage |\n|-----------|-------------------------------------------|\n|000^^^^^ |Get the proximity sensor data |\n|010^^^^^ |Get the line sensor data |\n|011^^^^^ |Get both the line and proximity sensor data|\n|100YY^^^ |Set the right motor to speed Y.Y*100 |\n|110YY^^^ |Set the left motor to speed Y.Y*100 |\n\nThe Pi will *not* take instructions. It will simply receive data from the sensors. In the future it will also accept status codes. Below is the format for sensor data.\n"
},
{
"alpha_fraction": 0.5710681080818176,
"alphanum_fraction": 0.5710681080818176,
"avg_line_length": 29.487178802490234,
"blob_id": "3b1f230f88761c43ffa82e6564119c9bb55151b3",
"content_id": "0139f9d48bfbd0ae8781bc5f30e4796ec8c72798",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1189,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 39,
"path": "/Pi/zumosensors.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "class ZumoSensors:\n def __init__(self):\n pass\n\n def get_line_sensors(self):\n \"\"\"\n Returns an array containing just the line sensor data\n :returns: An array of sensor values\n \"\"\"\n pass\n\n def get_prox_sensors(self):\n \"\"\"\n Returns an array containing just the proximity sensor data\n :returns: An array of sensor values\n \"\"\"\n pass\n\n def get_sensors(self):\n \"\"\"\n Returns an array matching the array format used to set sensor data.\n :returns: An array of sensor values\n \"\"\"\n pass\n\n def set_sensor_data(self, data):\n \"\"\"\n Sets the sensor data for this instance and updates the last_updated timestamp.\n :param data: An array following the format found in the documentation.\n \"\"\"\n pass\n\n def get_last_updated(self):\n \"\"\"\n Gets the last timestamp of when the sensors were updated. This is NOT the time that the Zumo sent the data\n back but the time at which the new values were set in this class\n :returns: UNIX timestamp of last update\n \"\"\"\n pass\n"
},
{
"alpha_fraction": 0.5896860957145691,
"alphanum_fraction": 0.5986546874046326,
"avg_line_length": 26.875,
"blob_id": "9c56a2487a27ba3a5e02144c4079195ee9d85591",
"content_id": "acf861759a507ae2d6ff6d587e78242355d8f23b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 16,
"path": "/Pi/util/logging.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "import logging\nfrom datetime import datetime\n\nclass Logging:\n def __init__(self, path):\n self.path = path\n logging.basicConfig(filename=\"{datetime.now()[8:]}_{path}\", level=logging.INFO)\n\n def log_info(string):\n log.info(f\"{datetime.now()[8:]}--{string}\")\n\n def log_error(string):\n log.error(f\"{datetime.now()[8:]}--{string}\")\n\n def log_warn(string):\n log.warning(f\"{datetime.now()[8:]}--{string}\")\n"
},
{
"alpha_fraction": 0.6317073106765747,
"alphanum_fraction": 0.6317073106765747,
"avg_line_length": 26.33333396911621,
"blob_id": "aee582049429651c50f9cf76c4c656a78729ff0f",
"content_id": "6f3cb320fa444e2654fb45e21ff51a4ae6f17171",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 410,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 15,
"path": "/Pi/instructions.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "\"\"\"\n This file contains the list of instruction codes to be used.\n Information on how instructions work can be found in the docs\n\"\"\"\n\nclass Instructions(Enum):\n CONNECT = \"C\"\n DISCONNECT = \"D\"\n SET_LEFT_MOTOR_SPEED = \"SL\"\n SET_RIGHT_MOTOR_SPEED = \"SR\"\n SET_TURN_RIGHT = \"TR\"\n SET_TURN_LEFT = \"TL\"\n GET_LINE_SENSORS = \"GL\"\n GET_PROXIMITY_SENSORS = \"GP\"\n GET_BOTH_SENSORS = \"GB\"\n"
},
{
"alpha_fraction": 0.613085150718689,
"alphanum_fraction": 0.626057505607605,
"avg_line_length": 43.88607406616211,
"blob_id": "15a692624b7d091ca2602b8760d3ed46cd02d4eb",
"content_id": "ab5f40bdfb4d368eb79e99bdfb55d4082d66ef3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3546,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 79,
"path": "/Pi/zumo.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nimport math\nimport random\nfrom serialconnection import ZumoConnection\nfrom util.logging import Logging\nfrom instructions import Instructions\nfrom zumosensors import ZumoSensors\nclass Zumo32u4:\n def __init_(self, name=\"Zumo32u4\", port=\"/dev/tty/ACM0\"):\n self.name = name\n self.max_speed = 100 # This is the maximum speed allowed for the zumo. It works as a percentage\n self.logger = Logging(f\"./logs/{name}\")\n self.connection = ZumoConnection(self.logger, port)\n self.logger.log_info(\"Created Zumo32u4 instance\")\n self.sensors = ZumoSensors()\n\n def _set_right_motor_speed(self, speed):\n \"\"\"\n Sets the speed of the right motor\n :param speed: The speed for the motor. Between 0 and 100. Acts as a percentage\n \"\"\"\n instruction = \"Instructions.SET_RIGHT_MOTOR_SPEED\"\n speed = f\"{speed};\"#This will grab the value\n instruction = f\"{instruction}{speed};\"\n self.connection.send_instruction(instruction)\n\n def _set_left_motor_speed(self, speed):\n \"\"\"\n Sets the speed of the left motor\n :param speed: The speed for the motor. Between 0 and 100. Acts as a percentage\n \"\"\"\n instruction = \"Instructions.SET_LEFT_MOTOR_SPEED\"\n speed = f\"{speed};\"#This will grab the value\n instruction = f\"{instruction}{speed};\"\n self.connection.send_instruction(instruction)\n\n def move_forward(self, speed):\n \"\"\"\n Will make the zumo move forward. Does this by taking a value (the speed) and sets both\n left and right motors to this speed.\n :param speed: Speed for the zumo. Expected as a float.\n \"\"\"\n speed = float(speed)\n if speed > self.max_speed:\n self.logger.log_warn(f\"Received speed of {speed} in move_forward. Rounded down to {self.max_speed}\")\n speed = self.max_speed\n self._set_left_motor_speed(speed)\n self._set_right_motor_speed(speed)\n\n def move_backward(self, speed):\n \"\"\"\n Will make the zumo move backward. Does this by taking a value (the speed) and sets both\n left and right motors to this speed.\n :param speed: Speed for the zumo, will be taken as a negative value. Expected as a float.\n \"\"\"\n if speed > self.max_speed:\n self.logger.log_warn(f\"Received speed of {speed} in move_backward. Rounded down to {self.max_speed}\")\n speed = self.max_speed\n self._set_left_motor_speed(-speed)\n self._set_right_motor_speed(-speed)\n\n def turn_right(self, angle, speed):\n \"\"\"\n Will make the zumo rotate to the right by moving only the right motor.\n :param angle: The angle to turn. Taken as an integer between 0 and 360.\n :param speed: How fast the turn should be completed. Between 0 and 100.\n \"\"\"\n if angle < 0 or angle > 360:\n self.logger.log_warn(f\"Receieved an angle of {angle} in turn_right. Not valid. Ignoring instruction\")\n\n def turn_left(self, angle, speed):\n \"\"\"\n Will make the zumo rotate to the left by moving only the left motor.\n :param angle: The angle to turn. Taken as an integer between 0 and 360.\n :param speed: How fast the turn should be completed. Between 0 and 100.\n \"\"\"\n if angle < 0 or angle > 360:\n self.logger.log_warn(f\"Receieved an angle of {angle} in turn_right. Not valid. Ignoring instruction\")\n pass\n"
},
{
"alpha_fraction": 0.6202531456947327,
"alphanum_fraction": 0.6202531456947327,
"avg_line_length": 25.33333396911621,
"blob_id": "dc0774e0d0fff8a7d73c467161f6dd5777c24d24",
"content_id": "6888f57f25122683ce837d1dbe24a82ffd088fe8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 79,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 3,
"path": "/Pi/exceptions/connectionError.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "class ConnectionError(Exception):\n def __init__(self):\n self.super()\n"
},
{
"alpha_fraction": 0.6170598864555359,
"alphanum_fraction": 0.6195553541183472,
"avg_line_length": 41.79611587524414,
"blob_id": "f858765e8e255e42a407d9070bde77e0deb5bdf7",
"content_id": "5b580c1d2389b03f3273ddad66c1c8533544c9b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4408,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 103,
"path": "/Pi/serialconnection.py",
"repo_name": "Sicarius154/ZumoPy",
"src_encoding": "UTF-8",
"text": "import serial\nimport time\nfrom exceptions.InvalidInstruction import InvalidInstruction\nfrom exceptions.connectionError import ConnectionError\nfrom ..instructions import Instructions\n\nclass ZumoConnection:\n def __init__(self, logger, port, baud_rate=19200, timeout=5):\n \"\"\"\n Initialize the connection. Check to ensure the connection is functional\n :param logger: An instance of the logger utility\n :param port: The port to use for serial connection\n :param baud_rate: The baud rate for the connection\n :param timeout: The timeout value for the serial connection.\n \"\"\"\n self.logger = logger\n self.logger.log_info(\"Created Serial Connection to Zumo\")\n slf.baud = baud_rate\n self.sensor_thread = None #Object to interact with the thread that will listen for sensor data\n self.connection = self.connect(port, baud_rate, timeout)\n connected_ok = self._check_connection()\n if connected_ok:\n pass\n else:\n self.logger.log_warn(f\"Could not connect to Zumo. Params were:\\\n Port: {port}\\\n Baud rate: {baud_rate}\\\n Timeout: {timeout}\")\n raise ConnectionError(\"Error connecting to Zump\")\n\n def _check_connection(self):\n \"\"\"\n Checks the connection is open correctly. If the connection has been opened succesfuly the Zumo should have\n begun sending data back to the Zumo instance.\n \"\"\"\n pass\n def send_instruction(self, inst):\n \"\"\"\n Sends an instruction to the Zumo over a serial connection\n :param ins: The 8-char long instruction.\n \"\"\"\n self.logger.log_info(f\"Received instruction {inst}\")\n if(_check_inst_validity(inst)):\n data = get_bytes(inst)\n self._send(data)\n\n def _connect(self, port, baud, timeout):\n \"\"\"\n Will attempt to connect to the Zumo using the params supplied.\n :param port: The port to connect to\n :param baud: The baudrate of the connection\n :param timeout: The timeout for the connection\n \"\"\"\n #Connect and send the connect instruction\n #TODO: Look into using parity bits\n con = serial.Serial(port, baud, timeout=timeout)\n con.inner_byte_timeout = 0.5 #The time allowed between bytes being sent in a message\n con.send_instruction(self._get_bytes(Instructions.CONNECT)) #We send this now so the Zumo can instantly start sending sensor data\n return con\n\n def disconnect(self):\n \"\"\"\n Will end the serial connection and tell the Zumo to cease all operation.\n \"\"\"\n pass\n def _sensor_data_received(self, data):\n \"\"\"\n To be called asynchronously when sensor data is received by the sensor_thread. This will set the Zumo object\n sensor data to this instance\n \"\"\"\n pass\n\n def _check_inst_validity(self, inst):\n \"\"\"\n Will check the validity of an instruction by checking a handful of criteria such as the length of an instruction,\n the value of certain characters etc. The majority of checking should have been done before hand. This will not\n check that the speed for setting motors is correct for example; just the format of the instruction\n :param inst: The instruction\n :return: Whether the instruction is OK\n \"\"\"\n if inst[len(inst)-1] != \";\":\n inst = inst+\";\" #ensure the instruction is properly terminated\n self.logger.log_error(f\"Instruction not properly terminated. Inst was {inst}\")\n raise InvalidInstruction(f\"{inst} is not a valid instruction\")\n return False\n return True #if none of the if statements were triggered, all is good\n\n def _send(self, data):\n \"\"\"\n Send data across the serial connection\n :param data: The data to send\n \"\"\"\n size = None #TODO: get size of inst\n self.connection.write(data)\n self.logger.log_info(\"Sent {size} bytes of data\")\n\n def _get_bytes(self, string):\n \"\"\"\n Converts a string instruction into bytes\n :param string: The instruction\n :return: The string given as bytes\n \"\"\"\n return bytes(string, \"utf-8\")\n"
}
] | 7 |
peap/djarzeit
|
https://github.com/peap/djarzeit
|
20157bd28a844b14ec2dd52929c7d1c60122c4d1
|
79b90526dde6845d7d83ab90acebfb1f4dacd85c
|
a22267629441e6f9e5184b1e732c4eeb5f55f421
|
refs/heads/master
| 2021-07-16T13:32:56.239216 | 2019-02-13T04:56:12 | 2019-02-13T04:56:12 | 10,729,524 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6957606077194214,
"alphanum_fraction": 0.6957606077194214,
"avg_line_length": 24.0625,
"blob_id": "7a18888cb429fb5d0402bd49e1c4d677457aa696",
"content_id": "743097bb74789818ada988b00c9b08afcf643210",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 401,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 16,
"path": "/djarzeit/urls.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import include, url\n\nimport account.urls\nimport categories.urls\nimport timers.urls\nimport reports.urls\nfrom account.views import login\n\n\nurlpatterns = [\n url(r'^$', login, name='home'),\n url(r'^account/', include(account.urls)),\n url(r'^categories/', include(categories.urls)),\n url(r'^timers/', include(timers.urls)),\n url(r'^reports/', include(reports.urls)),\n]\n"
},
{
"alpha_fraction": 0.48802998661994934,
"alphanum_fraction": 0.49062588810920715,
"avg_line_length": 28.88793182373047,
"blob_id": "e283631f21ac913320c2ac488161b63407f71a03",
"content_id": "3b20bd8a63e94e7da8bcea1a37dc1c55dc81494a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3467,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 116,
"path": "/timers/management/commands/change_interval.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from datetime import timedelta\n\nfrom django.core.management import BaseCommand, CommandError\n\nfrom timers.models import Timer\n\n\nclass Command(BaseCommand):\n help = (\n 'Change a timer\\'s nth interval start/end time by the given number '\n 'of minutes.'\n 'Usage:\\n'\n ' ./manage.py change_interval <timer> <n> (start|end) (+|-) <minutes>'\n )\n\n def add_arguments(self, parser):\n super(Command, self).add_arguments(parser)\n parser.add_argument(\n 'timer',\n help='The name of the timer whose nth interval should be changed.',\n )\n parser.add_argument(\n 'n',\n type=int,\n help='The nth most recent interval to adjust; 0 = most recent.',\n )\n parser.add_argument(\n 'start_or_end',\n choices=('start', 'end'),\n help='Whether to adjust the start or end of the interval.',\n )\n parser.add_argument(\n 'plus_or_minus',\n choices=('+', '-'),\n help='Whether to adjust the interval forward or backward.',\n )\n parser.add_argument(\n 'delta',\n type=int,\n help='Number of minutes to add or subtract.',\n )\n\n def handle(self, **options):\n timer_name = options['timer']\n n = int(options['n'])\n\n s_or_e = options['start_or_end']\n adjust_start = s_or_e == 'start'\n\n p_or_m = options['plus_or_minus']\n later = p_or_m == '+'\n back_or_forward = 'forward' if p_or_m == '+' else 'back'\n\n delta = int(options['delta'])\n\n try:\n timer = Timer.objects.get(name=timer_name)\n except Timer.DoesNotExist:\n raise CommandError(\n 'Could not find a Timer name \"{0}\".'\n .format(timer_name)\n )\n except Timer.MultipleObjectsReturned:\n raise CommandError(\n 'Found multiple timers named \"{0}\"... sorry!'\n .format(timer_name)\n )\n\n try:\n interval = timer.interval_set.all()[n]\n except IndexError:\n raise CommandError('Could not find the requested interval.')\n\n self.stdout.write(\n 'Would adjust the \"{timer}\" interval[{n}] '\n '{start_or_end} time {back_or_forward} by {delta} minutes.'\n .format(\n timer=timer_name,\n n=n,\n start_or_end=s_or_e,\n back_or_forward=back_or_forward,\n delta=delta,\n )\n )\n\n self.stdout.write(\n 'Current interval timespan...\\n'\n ' start: {0}\\n'\n ' end: {1}\\n'\n ' length: {2}\\n'\n .format(interval.start, interval.end, interval.length)\n )\n\n diff = timedelta(minutes=delta)\n if adjust_start:\n if later:\n interval.start += diff\n else:\n interval.start -= diff\n else:\n if later:\n interval.end += diff\n else:\n interval.end -= diff\n\n self.stdout.write(\n 'New interval timespan...\\n'\n ' start: {0}\\n'\n ' end: {1}\\n'\n ' length: {2}'\n .format(interval.start, interval.end, interval.length)\n )\n\n confirm = input('Save this change (y/n)? ')\n if confirm == 'y':\n interval.save()\n"
},
{
"alpha_fraction": 0.6299212574958801,
"alphanum_fraction": 0.6299212574958801,
"avg_line_length": 20.16666603088379,
"blob_id": "eea845eb4221b1523dfd22edf1126664b516cc9c",
"content_id": "4c1a6a89911233b60c8891443b17cb2383ec9448",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 127,
"license_type": "permissive",
"max_line_length": 58,
"num_lines": 6,
"path": "/README.md",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "DjArZeit (Arbeit Zeit)\n======================\n\nA time tracking app\n\nKeep track of how you spend your time during the work day.\n"
},
{
"alpha_fraction": 0.6724637746810913,
"alphanum_fraction": 0.678260862827301,
"avg_line_length": 20.5625,
"blob_id": "839a95c616d0b653659f7f5787a204ee16530ccb",
"content_id": "0378804ec55019644262bceece8be9f7d8adefc2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 345,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 16,
"path": "/account/models.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "import pytz\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Profile(models.Model):\n TZ_CHOICES = tuple((tz, tz) for tz in pytz.common_timezones)\n\n user = models.OneToOneField(User)\n\n timezone = models.CharField(\n max_length=50,\n choices=TZ_CHOICES,\n verbose_name='Timezone',\n )\n"
},
{
"alpha_fraction": 0.5731661915779114,
"alphanum_fraction": 0.5759730339050293,
"avg_line_length": 29.022472381591797,
"blob_id": "dbf16a0eb4c4e6a62cca604fadb0adaa78bb89f8",
"content_id": "dc21c665c9f2576b3c2bbddecfb3fd9526c2a336",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5344,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 178,
"path": "/categories/models.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from datetime import timedelta\n\nfrom django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Category(models.Model):\n\n class Meta:\n ordering = ['name']\n\n user = models.ForeignKey(User)\n\n parent = models.ForeignKey(\n 'self',\n blank=True,\n null=True,\n db_index=True,\n )\n\n name = models.CharField(\n verbose_name='Category',\n max_length=100,\n )\n\n description = models.CharField(\n verbose_name='Description',\n max_length=1000,\n blank=True,\n null=True,\n )\n\n def __str__(self):\n return self.name\n\n @property\n def show_in_selective_reports(self):\n for timer in self.timer_set.all():\n if timer.show_in_selective_reports:\n return True\n for category in self.category_set.all():\n if category.show_in_selective_reports:\n return True\n return False\n\n @property\n def is_root_category(self):\n return self.parent is None\n\n @property\n def root_parent(self):\n \"\"\"\n The Category anscestor that is a root Category.\n \"\"\"\n if self.is_root_category:\n return self\n else:\n return self.parent.root_parent\n\n @property\n def hierarchy_display(self):\n \"\"\"\n Root Category > Child Category > This Category\n \"\"\"\n if self.is_root_category:\n return self.name\n else:\n return '{0.hierarchy_display} > {1.name}'.format(self.parent, self)\n\n def unarchived_timers(self):\n return self.timer_set.filter(archived=False)\n\n def archived_timers(self):\n return self.timer_set.filter(archived=True)\n\n def stop_all_timers(self):\n for category in self.category_set.all():\n category.stop_all_timers()\n for timer in self.timer_set.filter(active=True):\n timer.stop()\n\n def get_intervals_between_dates(self, start_date, end_date):\n intervals = []\n for category in self.category_set.all():\n intervals += category.get_intervals_between_dates(start_date, end_date)\n for timer in self.timer_set.all():\n intervals += timer.get_intervals_between_dates(start_date, end_date)\n return intervals\n\n def get_first_interval_after(self, date):\n earliest = None\n\n def update_earliest(candidate):\n nonlocal earliest\n if earliest is None:\n earliest = candidate\n else:\n if candidate is not None:\n if candidate < earliest:\n earliest = candidate\n\n for category in self.category_set.all():\n update_earliest(category.get_first_interval_after(date))\n for timer in self.timer_set.all():\n update_earliest(timer.get_first_interval_after(date))\n return earliest\n\n def get_last_interval_before(self, date):\n latest = None\n\n def update_earliest(candidate):\n nonlocal latest\n if latest is None:\n latest = candidate\n else:\n if candidate is not None:\n if candidate > latest:\n latest = candidate\n\n for category in self.category_set.all():\n update_earliest(category.get_last_interval_before(date))\n for timer in self.timer_set.all():\n update_earliest(timer.get_last_interval_before(date))\n return latest\n\n def get_total_time_on_date(self, date):\n total = timedelta(0)\n for category in self.category_set.all():\n total += category.get_total_time_on_date(date)\n for timer in self.timer_set.all():\n total += timer.get_total_time_on_date(date)\n return total\n\n def get_total_time_on_dates(self, dates):\n total = timedelta(0)\n for date in dates:\n total += self.get_total_time_on_date(date)\n return total\n\n def get_total_time_on_date_week(self, date):\n total = timedelta(0)\n for category in self.category_set.all():\n total += category.get_total_time_on_date_week(date)\n for timer in self.timer_set.all():\n total += timer.get_total_time_on_date_week(date)\n return total\n\n def get_total_time_between_dates(self, start_date, end_date):\n total = timedelta(0)\n for category in self.category_set.all():\n total += category.get_total_time_between_dates(start_date, end_date)\n for timer in self.timer_set.all():\n total += timer.get_total_time_between_dates(start_date, end_date)\n return total\n\n @property\n def today(self):\n \"\"\"\n Total time in this category today.\n \"\"\"\n total = timedelta(0)\n for category in self.category_set.all():\n total += category.today\n for timer in self.timer_set.all():\n total += timer.today\n return total\n\n @property\n def last_week(self):\n \"\"\"\n Total time in this category last week (a week is Monday to Sunday).\n \"\"\"\n total = timedelta(0)\n for category in self.category_set.all():\n total += category.last_week\n for timer in self.timer_set.all():\n total += timer.last_week\n return total\n"
},
{
"alpha_fraction": 0.5303429961204529,
"alphanum_fraction": 0.5366754531860352,
"avg_line_length": 37.67346954345703,
"blob_id": "cf75eaa10966164b0501d5e44b252ec1cec8ff1f",
"content_id": "ab547dadd1ccbc7b41d0e72771be3b04a807cb20",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1895,
"license_type": "permissive",
"max_line_length": 114,
"num_lines": 49,
"path": "/timers/migrations/0001_initial.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"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 ('categories', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Interval',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('week', models.IntegerField(db_index=True, verbose_name='Week')),\n ('year', models.IntegerField(db_index=True, verbose_name='Year')),\n ('start', models.DateTimeField(auto_now_add=True, verbose_name='Start Time')),\n ('end', models.DateTimeField(blank=True, null=True, verbose_name='End Time')),\n ('notes', models.CharField(blank=True, max_length=1000, null=True, verbose_name='Notes')),\n ],\n options={\n 'ordering': ['-start'],\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Timer',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=100, verbose_name='Name')),\n ('active', models.BooleanField(default=False, verbose_name='Active')),\n ('archived', models.BooleanField(default=False, verbose_name='Archived')),\n ('category', models.ForeignKey(to='categories.Category')),\n ],\n options={\n 'ordering': ['name'],\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='interval',\n name='timer',\n field=models.ForeignKey(to='timers.Timer'),\n preserve_default=True,\n ),\n ]\n"
},
{
"alpha_fraction": 0.6814436912536621,
"alphanum_fraction": 0.6849744915962219,
"avg_line_length": 28.63953399658203,
"blob_id": "346466438ff39fbaefe2e40e8824ec74e766091b",
"content_id": "11c53d87c1d59860e9bb1a2f5aa937ccac7cf43f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2549,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 86,
"path": "/categories/views.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.contrib import messages\nfrom django.shortcuts import render_to_response, redirect, get_object_or_404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import requires_csrf_token\n\nfrom categories.models import Category\nfrom core.context import ArZeitContext\nfrom core.views import ArZeitBaseDetailView\n\nFAKE_ROOT_PARENT = {\n 'id': 'root',\n 'name': 'Root',\n 'description': 'The root \"category\" to which all categories belong',\n}\n\n\nclass CategoriesContext(ArZeitContext):\n active_tab = 'categories'\n\n\nclass CategoryDetailView(ArZeitBaseDetailView):\n pk_url_kwarg = 'category_id'\n\n def get_queryset(self):\n return self.categories\n\n\n@login_required\n@requires_csrf_token\ndef categories(request):\n root_categories = Category.objects.filter(user=request.user, parent=None)\n context = {\n 'root_categories': root_categories,\n 'FAKE_ROOT_PARENT': FAKE_ROOT_PARENT,\n }\n context = CategoriesContext(\n request,\n context,\n extra_css=['categories/categories.css'],\n extra_js=['categories/categories.js'],\n )\n return render_to_response('categories/categories.html', {}, context)\n\n\n@login_required\ndef new_category(request, cat_id):\n if cat_id == 'root':\n parent_cat = None\n else:\n try:\n parent_cat = Category.objects.get(pk=int(cat_id))\n except (ValueError, ObjectDoesNotExist):\n messages.error(request, 'Please choose a valid parent category.')\n return redirect('categories')\n name = request.POST.get('category_name')\n if not name:\n messages.error(request, 'Please choose a category name.')\n return redirect('categories')\n category = Category(\n user=request.user,\n parent=parent_cat,\n name=request.POST.get('category_name'),\n description=request.POST.get('category_desc'),\n )\n category.full_clean()\n category.save()\n messages.success(request, 'Created new category.')\n return redirect('categories')\n\n\n@login_required\ndef category(request, cat_id):\n category = get_object_or_404(Category, pk=int(cat_id))\n context = {\n 'category': category,\n }\n return render_to_response('category/category.html', context)\n\n\n@login_required\ndef delete_category(request, cat_id):\n category = get_object_or_404(Category, pk=int(cat_id))\n category.delete()\n messages.success(request, 'Deleted category.')\n return redirect('categories')\n"
},
{
"alpha_fraction": 0.5987421274185181,
"alphanum_fraction": 0.6113207340240479,
"avg_line_length": 36.85714340209961,
"blob_id": "04e3f807586307bf23aac75af4d238473c00429e",
"content_id": "91ff0001cfbc22d552345485817182d11afc6fa0",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 795,
"license_type": "permissive",
"max_line_length": 87,
"num_lines": 21,
"path": "/timers/urls.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import include, url\n\nfrom timers import views\n\n\nclass SingleTimerPatterns():\n urlpatterns = [\n url(r'^startstop/$', views.StartStop.as_view(), name='startstop'),\n url(r'^edit/$', views.Edit.as_view(), name='edit_timer'),\n url(r'^archive/$', views.Archive.as_view(), name='archive_timer'),\n url(r'^unarchive/$', views.Archive.as_view(), name='unarchive_timer'),\n url(r'^delete/$', views.Delete.as_view(), name='delete_timer'),\n ]\n\n\nurlpatterns = [\n url(r'^$', views.Listing.as_view(), name='timers'),\n url(r'^new/(?P<category_id>[0-9]{1,20})/$', views.New.as_view(), name='new_timer'),\n url(r'^(?P<timer_id>[0-9]{1,20})/', include(SingleTimerPatterns)),\n url(r'^timeline/$', views.Timeline.as_view(), name='timeline'),\n]\n"
},
{
"alpha_fraction": 0.6122697591781616,
"alphanum_fraction": 0.6191201210021973,
"avg_line_length": 34.317203521728516,
"blob_id": "3a00e40833a732c6fe1692882b99994efc9bd751",
"content_id": "50c8a18376c58425f403e3e34661195dc783a9ea",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6569,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 186,
"path": "/reports/views.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render_to_response\nfrom django.utils.timezone import datetime, timedelta, now\nfrom django.contrib.auth.decorators import login_required\n\nfrom categories.models import Category\nfrom core.context import ArZeitContext\nfrom timers.models import Interval\nfrom reports import utils\n\nPX_PER_HOUR = 100\nTIME_FORMAT = '%I:%M %p'\n\n\nclass ReportsContext(ArZeitContext):\n active_tab = 'reports'\n extra_css = ('reports/reports.css',)\n\n\n@login_required\ndef daily_summary(request, full=False):\n report_date = utils.get_report_date(request)\n root_categories = Category.objects.filter(user=request.user, parent=None)\n\n dates = [report_date]\n totals_by_root_cat = [\n (cat, utils.get_totals_for_dates(cat, dates, full=full))\n for cat in root_categories\n if full or cat.show_in_selective_reports\n ]\n\n context = ReportsContext(request, {\n 'report_date': report_date,\n 'root_categories': root_categories,\n 'dates': dates,\n 'totals_by_root_cat': totals_by_root_cat,\n })\n return render_to_response('reports/summary_base.html', {}, context)\n\n\n@login_required\ndef weekly_summary(request, full=False):\n report_date = utils.get_report_date(request)\n root_categories = Category.objects.filter(user=request.user, parent=None)\n\n dates = utils.get_dates_for_week_of(report_date)\n totals_by_root_cat = [\n (cat, utils.get_totals_for_dates(cat, dates, full=full))\n for cat in root_categories\n if full or cat.show_in_selective_reports\n ]\n\n context = ReportsContext(request, {\n 'report_date': report_date,\n 'root_categories': root_categories,\n 'dates': dates,\n 'totals_by_root_cat': totals_by_root_cat,\n })\n return render_to_response('reports/summary_base.html', {}, context)\n\n\n@login_required\ndef intervals(request):\n report_date = utils.get_report_date(request)\n year, month, day = report_date.year, report_date.month, report_date.day\n tz = report_date.tzinfo\n nowtz = now().astimezone(tz=tz)\n is_today = utils.date_is_today(report_date)\n\n root_categories = Category.objects.filter(user=request.user, parent=None)\n category_width = _get_category_width(root_categories.count())\n user_intervals = Interval.user_intervals(request.user)\n\n def timedelta_height(td):\n hours = td.total_seconds() / 3600\n height = PX_PER_HOUR * hours\n return int(height)\n\n min_datetime = datetime(year, month, day, 0, 0, 0, 0, tz)\n max_datetime = datetime(year, month, day, 23, 59, 59, 0, tz)\n all_intervals = user_intervals.filter(\n start__range=(min_datetime, max_datetime),\n ).order_by('start')\n\n if all_intervals.count() > 0:\n min_interval_time = all_intervals[0].start.astimezone(tz=tz)\n max_interval_time = all_intervals.latest('start').start.astimezone(tz=tz)\n if max_interval_time < nowtz:\n max_interval_time = nowtz\n else:\n min_interval_time = datetime(year, month, day, 8, 0, 0, 0, tz)\n max_interval_time = datetime(year, month, day, 18, 0, 0, 0, tz)\n\n def time_top(dt):\n temp_min_time = min_interval_time.replace(minute=0, second=0)\n offset = dt - temp_min_time\n return timedelta_height(offset)\n\n time_cells = []\n for hour in range(min_interval_time.hour, max_interval_time.hour+1):\n start_time = datetime(year, month, day, hour, 0, 0, 0, tz)\n an_hour = timedelta(hours=1)\n time_cells.append({\n 'height': timedelta_height(an_hour),\n 'top': time_top(start_time),\n 'value': start_time.strftime(TIME_FORMAT),\n 'classes': 'time-cell',\n })\n if is_today:\n time_cells.append({\n 'height': 1,\n 'top': time_top(nowtz),\n 'value': '',\n 'classes': 'current-time',\n })\n\n root_category_cells = []\n for cat in root_categories:\n interval_list = []\n for interval in all_intervals:\n if interval.timer.category.root_parent == cat:\n interval_list.append(interval)\n cells = []\n for interval in interval_list:\n start = interval.start.astimezone(tz=tz).strftime(TIME_FORMAT)\n end = '[active]'\n if interval.end is not None:\n end = interval.end.astimezone(tz=tz).strftime(TIME_FORMAT)\n title = '{0} ({1}-{2})'.format(\n interval.timer.hierarchy_display, start, end)\n cells.append({\n 'height': timedelta_height(interval.length),\n 'top': time_top(interval.start.astimezone(tz=tz)),\n 'interval': interval,\n 'timer': interval.timer,\n 'title': title,\n 'start': start,\n 'end': end,\n })\n root_category_cells.append((cat, cells))\n\n context = {\n 'report_date': report_date,\n 'category_width': category_width,\n 'total_height': timedelta_height(max_interval_time - min_interval_time),\n 'time_cells': time_cells,\n 'root_category_cells': root_category_cells,\n }\n context = ReportsContext(\n request,\n context,\n )\n return render_to_response('reports/intervals.html', {}, context)\n\n\n@login_required\ndef totals(request):\n start_date_str = request.GET.get('start_date')\n end_date_str = request.GET.get('end_date')\n start_date = utils.get_normalized_date(start_date_str, request.user)\n end_date = utils.get_normalized_date(end_date_str, request.user)\n root_categories = Category.objects.filter(user=request.user, parent=None)\n flat_totals_by_root = []\n for cat in root_categories:\n cat_totals = []\n for item in utils.get_flat_list_of_categories_and_timers(cat):\n total = item.get_total_time_between_dates(start_date, end_date)\n earliest = item.get_first_interval_after(start_date)\n latest = item.get_last_interval_before(end_date)\n cat_totals.append((item, total, earliest, latest))\n flat_totals_by_root.append((cat, cat_totals))\n context = ReportsContext(request, {\n 'start_date': start_date,\n 'end_date': end_date,\n 'flat_totals_by_root': flat_totals_by_root,\n })\n return render_to_response('reports/totals_between_dates.html', {}, context)\n\n\ndef _get_category_width(num):\n cols_available = 10\n if num > 0:\n width = cols_available // num\n width = width if width > 0 else 1\n else:\n width = cols_available\n return width\n"
},
{
"alpha_fraction": 0.5654878616333008,
"alphanum_fraction": 0.5769482851028442,
"avg_line_length": 31.489360809326172,
"blob_id": "7e34878c41f7927937724651bc8b1a34f63edbe1",
"content_id": "edbe98bd5159d200d06d8894ef8f725f4c40d574",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3054,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 94,
"path": "/timers/static/timers/timeline.js",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "$(document).ready(function(){\n\n // Setup SVG container\n var nRows = window.timelineData.nCategories;\n var height = 150 + 50 * nRows;\n var width = $('#timeline').width();\n var margin = {\n 'top': 15,\n 'bottom': 25,\n 'left': 0.05 * width,\n 'right': 0.05 * width,\n }\n var h = height - margin.top - margin.bottom;\n var w = width - margin.right - margin.left;\n\n var svg = d3.select('#timeline')\n .append('svg')\n .attr('height', height)\n .attr('width', width);\n\n // Add title\n var title = svg.append('g')\n .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')\n .attr('class', 'title')\n .append('text')\n .attr('x', (w / 2))\n .attr('y', margin.top)\n .attr('text-anchor', 'middle')\n .text('Timeline of Intervals on ' + window.timelineData.dateStr);\n\n // Add axis\n var timeScale = d3.time.scale()\n .domain([window.timelineData.minHour, window.timelineData.maxHour])\n .range([0, w]);\n\n var timeAxis = d3.svg.axis()\n .scale(timeScale)\n .tickFormat(d3.time.format('%I:%M %p'))\n .orient('bottom');\n\n svg.append('g')\n .attr('class', 'time-axis')\n .attr('transform',\n 'translate(' + margin.left + ',' + (height - margin.bottom - 50) + ')')\n .call(timeAxis)\n .selectAll('text')\n .attr('x', 9)\n .attr('y', 0)\n .attr('dy', '.35em')\n .attr('transform', 'rotate(90)')\n .style('text-anchor', 'start');\n\n // Add data\n function intervalX(d) { return margin.left + timeScale(d.start); }\n function intervalY(d) { return margin.top + d.categoryNum * 50; }\n function intervalGroupTransform(d) {\n return 'translate(' + intervalX(d) + ',' + intervalY(d) + ')';\n }\n function intervalClass(d) { return 'interval-of-category-' + d.categoryNum; }\n function intervalWidth(d) { return timeScale(d.end) - timeScale(d.start); }\n function intervalHeight(d) { return 35; }\n function intervalText(d) { return d.timerName; }\n function intervalTextX(d) { return 5; }\n function intervalTextY(d) { return intervalHeight(d) - 5; }\n\n // Create interval groups\n var intervals = window.timelineData.intervals;\n var intervalGroups = svg.selectAll('g.interval')\n .data(intervals)\n .enter()\n .append('g')\n .attr('class', 'interval')\n .attr('transform', intervalGroupTransform);\n\n // add rectangles to groups\n intervalGroups.append('rect')\n .attr('class', intervalClass)\n .attr('width', intervalWidth)\n .attr('height', intervalHeight);\n\n // add labels to groups\n intervalGroups.append('text')\n .text(intervalText)\n .attr('x', intervalTextX)\n .attr('y', intervalTextY)\n .style('text-anchor', 'start');\n\n // TODO: add category group labels on left-hand side\n\n // TODO: add hover handlers for showing more interval info\n\n // TODO: add click handlers for creating/editing/deleting intervals\n\n});\n"
},
{
"alpha_fraction": 0.688622772693634,
"alphanum_fraction": 0.7544910311698914,
"avg_line_length": 15.699999809265137,
"blob_id": "c92812b3618e92d9c78ecdd47a1710fe99b9b4cf",
"content_id": "ee0faee783ea8750d133e74c1ac1f196ead52b5b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 167,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 10,
"path": "/deploy.sh",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\ngit pull\n\npip install -r requirements.txt\n\npython manage.py collectstatic --noinput\npython manage.py migrate\n\ngunicorn djarzeit.wsgi -w 2 -b 127.0.0.1:8999\n"
},
{
"alpha_fraction": 0.4312856197357178,
"alphanum_fraction": 0.43381887674331665,
"avg_line_length": 27.196428298950195,
"blob_id": "9cac3390e77691f288ca1f967e142e15ad2d92b0",
"content_id": "f6990ea2eeaf9eede748abd79efdd8beeb95f063",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 1579,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 56,
"path": "/reports/templates/reports/intervals.html",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "{% extends 'reports/reports_base.html' %}\n\n{% block reports_content %}\n<div class=\"well\">\n <div class=\"row\">\n <div class=\"col-xs-12\">\n\n <div class=\"row\">\n <div class=\"col-xs-2\">\n </div>\n {% for cat, _ in root_category_cells %}\n <div class=\"col-xs-{{ category_width }}\">\n <div class=\"interval-header\">\n {{ cat.name }}\n </div>\n </div>\n {% endfor %}\n </div>\n\n <div class=\"row\">\n\n <div class=\"col-xs-2 interval-container\"\n style=\"height: {{ total_height }}px;\">\n {% for cell in time_cells %}\n <div class=\"interval {{ cell.classes }}\"\n style=\"height: {{ cell.height }}px; top: {{ cell.top }}px;\">\n {{ cell.value }}\n </div>\n {% endfor %}\n </div>\n\n {% for cat, cells in root_category_cells %}\n <div class=\"col-xs-{{ category_width }} interval-container\">\n {% for cell in cells %}\n <div class=\"interval\" title=\"{{ cell.title }}\"\n style=\"height: {{ cell.height }}px; top: {{ cell.top }}px;\">\n <div class=\"interval-start\">\n {{ cell.start }}\n </div>\n <div class=\"interval-details\">\n {{ cell.interval.timer }}\n </div>\n <div class=\"interval-end\">\n {{ cell.end }}\n </div>\n </div>\n {% endfor %}\n </div>\n {% endfor %}\n\n </div>\n\n </div>\n </div>\n</div>\n{% endblock reports_content %}\n"
},
{
"alpha_fraction": 0.5265700221061707,
"alphanum_fraction": 0.5603864789009094,
"avg_line_length": 16.25,
"blob_id": "4170f530b29062a93dfa22e5b8eebc1dc00f548b",
"content_id": "d365fc09a43691c1eaef084bae4177b6910ca5ea",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 12,
"path": "/_local_settings_template.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "ALLOWED_HOSTS = ['localhost', '127.0.0.1']\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': 'arzeit.sqlite',\n }\n}\n\nDEBUG = True\n\nSECRET_KEY = 'a secret key'\n"
},
{
"alpha_fraction": 0.5,
"alphanum_fraction": 0.6727272868156433,
"avg_line_length": 17.33333396911621,
"blob_id": "528f14150dae4a79e9cdef0a94e9ca4394c7402b",
"content_id": "01ddf8808878a4294d8d0b28d3c793ac569c479d",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 110,
"license_type": "permissive",
"max_line_length": 57,
"num_lines": 6,
"path": "/requirements.txt",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "# Python 3.4\n\nDjango~>1.11.19 # TODO: actually update from 1.8 to 1.11\ngunicorn~>19.5.0\npsycopg2==2.6.*\npytz\n"
},
{
"alpha_fraction": 0.6875,
"alphanum_fraction": 0.6875,
"avg_line_length": 16.600000381469727,
"blob_id": "ea5c471cf4c85748d892e7d95f9b6eadf96a94af",
"content_id": "379b8c9a6f0079fb4d5a0c0b510a80b14154c9ca",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 176,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 10,
"path": "/activate",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "#!/bin/sh\n\nsource venv/bin/activate\n\nINSTALLED=$(pip freeze)\nREQUIRED=$(cat requirements.txt)\n\nif [ \"$INSTALLED\" != \"$REQUIRED\" ] ; then\n pip install -r requirements.txt\nfi\n"
},
{
"alpha_fraction": 0.6273684501647949,
"alphanum_fraction": 0.6378947496414185,
"avg_line_length": 28.6875,
"blob_id": "0ee6ad379451ce1e22f535f57c95878746b78919",
"content_id": "bb0861f39a7f4c06d6b68fa92ca75fab2e87104e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 475,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 16,
"path": "/categories/urls.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import include, url\n\nfrom categories import views\n\n\nclass SingleCategoryPatterns():\n urlpatterns = [\n url(r'^$', views.category, name='category'),\n url(r'^new/$', views.new_category, name='new_category'),\n url(r'^delete/$', views.delete_category, name='delete_category'),\n ]\n\nurlpatterns = [\n url(r'^$', views.categories, name='categories'),\n url(r'^(?P<cat_id>([0-9]{1,20}|root))/', include(SingleCategoryPatterns)),\n]\n"
},
{
"alpha_fraction": 0.623928427696228,
"alphanum_fraction": 0.6276556253433228,
"avg_line_length": 31.719512939453125,
"blob_id": "2968465fc08664c82120d936b1aa343104b9ddbd",
"content_id": "e51a8b00757518a613e5c65ec6c13bc78a31b6c7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2683,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 82,
"path": "/reports/utils.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from functools import reduce\nimport operator\nimport pytz\n\nfrom django.contrib import messages\nfrom django.utils import timezone\n\n\ndef get_report_date(request):\n user_tz = pytz.timezone(request.user.profile.timezone)\n date_string = request.GET.get('report_date')\n if date_string:\n try:\n report_date = user_tz.localize(\n timezone.datetime.strptime(date_string, '%m/%d/%Y')\n )\n except ValueError:\n messages.error(request, 'Invalid date.')\n report_date = user_tz.normalize(timezone.now())\n else:\n report_date = user_tz.normalize(timezone.now())\n return report_date\n\n\ndef get_normalized_date(date_string, user):\n user_tz = pytz.timezone(user.profile.timezone)\n if date_string:\n normalized = user_tz.localize(\n timezone.datetime.strptime(date_string, '%m/%d/%Y')\n )\n else:\n normalized = user_tz.normalize(timezone.now())\n return normalized\n\n\ndef date_is_today(date):\n tz = date.tzinfo\n nowtz = timezone.now().astimezone(tz=tz)\n year, month, day = date.year, date.month, date.day\n return all([year == nowtz.year, month == nowtz.month, day == nowtz.day])\n\n\ndef get_dates_for_week_of(date):\n \"\"\"\n Get a list of seven datetime objects representing the full week (Monday to\n Sunday) of the given date.\n \"\"\"\n year, week, dow = date.isocalendar()\n deltas = [(d + 1 - dow) for d in range(7)]\n return [(date + timezone.timedelta(days=d)) for d in deltas]\n\n\ndef get_flat_list_of_categories_and_timers(base_cat):\n def _add_to_list(category):\n l = [category]\n l += [t for t in category.timer_set.all()]\n for subcat in category.category_set.all():\n l += _add_to_list(subcat)\n return l\n return _add_to_list(base_cat)\n\n\ndef get_totals_for_dates(base_cat, dates, full=False):\n \"\"\"\n Get a flat list of 3-tuples for every reportable category and timer of the\n given base category, summarizing the time logged on the given dates. If\n full is True, do this for EVERY category and timer.\n Return format:\n [\n (<category|timer>, total, [time on dates[0], time2 on dates[1], ...]),\n (<category|timer>, total, [time on dates[0], time2 on dates[1], ...]),\n ]\n \"\"\"\n all_totals = []\n for item in get_flat_list_of_categories_and_timers(base_cat):\n if not full and not item.show_in_selective_reports:\n continue\n totals = [item.get_total_time_on_date(date) for date in dates]\n total = reduce(operator.add, totals)\n if total.total_seconds() > 0:\n all_totals.append((item, total, totals))\n return all_totals\n"
},
{
"alpha_fraction": 0.6152137517929077,
"alphanum_fraction": 0.6157690286636353,
"avg_line_length": 32.98113250732422,
"blob_id": "2c9c52ae22545a844234634eac27f99408e6850d",
"content_id": "51424a6b34962df08371cdd3b4fd4e41b0a1d734",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3602,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 106,
"path": "/account/views.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.conf import settings\nfrom django.contrib import messages\nfrom django.db import IntegrityError\nfrom django.shortcuts import redirect, render_to_response\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth import authenticate\nfrom django.contrib.auth import login as dj_login\nfrom django.contrib.auth import logout as dj_logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom account.models import Profile\nfrom core.context import ArZeitContext\n\n\nclass AccountContext(ArZeitContext):\n active_tab = 'account'\n\n\ndef login(request):\n if request.user.is_authenticated():\n return redirect('timers')\n if request.POST:\n next_url = request.POST.get('next_url')\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n dj_login(request, user)\n if next_url:\n return redirect(next_url)\n else:\n return redirect('timers')\n else:\n messages.error(request, 'Your account is inactive.')\n else:\n messages.error(request, 'Invalid login credentials')\n return redirect('home')\n else:\n next_url = request.GET.get('next')\n context = AccountContext(request, {'next_url': next_url})\n return render_to_response('account/login.html', {}, context)\n\n\ndef new_account(request):\n if request.POST:\n name_first = request.POST.get('new_name_first')\n name_last = request.POST.get('new_name_last')\n email = request.POST.get('new_email')\n username = request.POST.get('new_username')\n password = request.POST.get('new_password')\n try:\n user = User.objects.create_user(username, email, password)\n user.first_name = name_first\n user.last_name = name_last\n except IntegrityError as e:\n messages.error(request, e)\n return redirect('home')\n try:\n user.full_clean()\n except ValidationError as e:\n for err in e.message_dict:\n messages.error(request, err)\n else:\n user.save()\n profile = Profile(user=user, timezone=settings.TIME_ZONE)\n profile.full_clean()\n profile.save()\n messages.success(request, 'New user created!')\n user = authenticate(username=username, password=password)\n dj_login(request, user)\n return redirect('timers')\n else:\n context = AccountContext(request, {})\n return render_to_response('account/new.html', {}, context)\n\n\n@login_required\ndef logout(request):\n dj_logout(request)\n messages.success(request, 'Successfully logged out.')\n return redirect('home')\n\n\n@login_required\ndef account(request):\n next_url = request.POST.get('next_url')\n user = request.user\n user.profile.timezone = request.POST.get('user_timezone')\n try:\n user.profile.full_clean()\n except ValidationError as e:\n for field, errors in e.message_dict.items():\n messages.error(\n request,\n 'Error updating profile - {0}: {1}'.format(\n field, errors,\n )\n )\n else:\n user.profile.save()\n messages.success(request, 'Saved user profile.')\n if next_url:\n return redirect(next_url)\n return redirect('home')\n"
},
{
"alpha_fraction": 0.7036303877830505,
"alphanum_fraction": 0.7036303877830505,
"avg_line_length": 25.578947067260742,
"blob_id": "e1f8d163d3c87abc42669e88d921dd2905980048",
"content_id": "4f804b755c84a82ccf5df3e20e219ca9f9b31b3e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1515,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 57,
"path": "/core/views.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "import pytz\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import View, TemplateView\nfrom django.views.generic.detail import BaseDetailView\n\nfrom core.context import ArZeitContext\nfrom timers.models import Timer\n\n\nclass ArZeitViewMixin:\n\n @method_decorator(login_required)\n def dispatch(self, request, *args, **kwargs):\n self.user = request.user\n self.tz = pytz.timezone(self.user.profile.timezone)\n return super().dispatch(request, *args, **kwargs)\n\n @property\n def categories(self):\n return self.user.category_set.all()\n\n @property\n def sorted_categories(self):\n return sorted(self.categories, key=lambda c: c.hierarchy_display)\n\n @property\n def root_categories(self):\n return self.categories.filter(parent=None)\n\n @property\n def timers(self):\n return Timer.objects.filter(category__user=self.user)\n\n @property\n def active_timers(self):\n return self.timers.filter(active=True)\n\n\nclass ArZeitView(ArZeitViewMixin, View):\n pass\n\n\nclass ArZeitBaseDetailView(ArZeitViewMixin, BaseDetailView):\n pass\n\n\nclass ArZeitTemplateView(ArZeitViewMixin, TemplateView):\n context_class = ArZeitContext\n\n def get_context_data(self, **kwargs):\n ctx = super().get_context_data(**kwargs)\n ctx.update({\n 'active_timers': self.active_timers,\n })\n return self.context_class(self.request, ctx, **kwargs)\n"
},
{
"alpha_fraction": 0.5447799563407898,
"alphanum_fraction": 0.5514329671859741,
"avg_line_length": 31.032787322998047,
"blob_id": "ea65d2f64a55843c7465616335e6dc6f6c3554a1",
"content_id": "9f5a6d2d1a68f890f2760a04d73ea879993a7e83",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7816,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 244,
"path": "/timers/views.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from datetime import datetime, time, timedelta\nimport json\n\nfrom django.contrib import messages\nfrom django.core.exceptions import ValidationError\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.utils.timezone import now\n\nfrom categories.models import Category\nfrom categories.views import CategoryDetailView\nfrom core.context import ArZeitContext\nfrom core.json import get_base_json_data\nfrom core.views import ArZeitBaseDetailView, ArZeitTemplateView\nfrom reports.utils import get_report_date\nfrom timers.models import Timer, Interval\n\n\nclass TimersContext(ArZeitContext):\n active_tab = 'timers'\n auto_refresh = 300\n extra_css = ('timers/timers.css',)\n extra_js = ('timers/timers.js',)\n\n\nclass TimelineContext(ArZeitContext):\n active_tab = 'timeline'\n auto_refresh = 300\n extra_css = ('timers/timeline.css',)\n extra_js = ('core/d3-3.5.9.min.js', 'timers/timeline.js',)\n\n\nclass TimerDetailView(ArZeitBaseDetailView):\n pk_url_kwarg = 'timer_id'\n\n def get_queryset(self):\n return self.timers\n\n def process(self):\n pass\n\n def get_ajax_data(self):\n return {}\n\n def get_ajax_response(self):\n data = get_base_json_data(self.user)\n data.update(self.get_ajax_data())\n return HttpResponse(json.dumps(data), content_type='application/json')\n\n def add_error(self, action, msg):\n messages.error(\n self.request,\n 'Error {0} timer \"{1}\": {2}'.format(\n action, self.timer.linkify(), msg),\n )\n\n def post(self, request, *args, **kwargs):\n self.timer = self.get_object()\n self.process()\n if self.request.is_ajax():\n return self.get_ajax_response()\n else:\n return redirect('timers')\n\n\nclass Listing(ArZeitTemplateView):\n context_class = TimersContext\n template_name = 'timers/timers.html'\n\n def get_context_data(self, **kwargs):\n ctx = super().get_context_data(**kwargs)\n ctx.update({\n 'root_categories': self.root_categories,\n 'all_categories': self.sorted_categories,\n })\n return ctx\n\n\nclass New(CategoryDetailView):\n def post(self, request, *args, **kwargs):\n category = self.get_object()\n name = request.POST.get('timer_name')\n action = request.POST.get('create-action')\n timer = Timer(category=category, name=name)\n try:\n timer.full_clean()\n except ValidationError as e:\n msg = 'Error creating new timer: \\n'\n for field, errors in e.message_dict.items():\n msg += '{0}: {1}\\n'.format(field, ', '.join(errors))\n messages.error(request, msg)\n else:\n timer.save()\n msg = 'Created new timer, {0}'.format(timer.linkify())\n if action == 'create':\n msg += '.'\n if action == 'start':\n timer.start()\n msg += ', and started it.'\n if action == 'archive':\n timer.archive()\n msg += ', and archived it.'\n messages.success(request, msg)\n return redirect('timers')\n\n\nclass Edit(TimerDetailView):\n def process(self):\n name = self.request.POST.get('new_timer_name').strip()\n if not name:\n self.add_error('editing', 'Invalid timer name.')\n return redirect('timers')\n category_id = self.request.POST.get('new_timer_category').strip()\n reportable = bool(self.request.POST.get('new_timer_reportable'))\n try:\n category = self.categories.get(pk=int(category_id))\n except Category.DoesNotExist as e:\n self.add_error('editing', 'Unknown category.')\n except ValueError as e:\n self.add_error('editing', 'Invalid category.')\n else:\n self.timer.name = name\n self.timer.category = category\n self.timer.reportable = reportable\n try:\n self.timer.full_clean()\n except ValidationError as e:\n msg = '\\n'\n for field, errors in e.message_dict.items():\n msg += '{0}: {1}\\n'.format(field, ', '.join(errors))\n self.add_error('editing', msg)\n else:\n self.timer.save()\n messages.success(\n self.request,\n 'Edited timer \"{0}\".'.format(self.timer.linkify()),\n )\n\n\nclass StartStop(TimerDetailView):\n def process(self):\n if self.timer.active:\n self.timer.stop()\n else:\n self.timer.start()\n\n\nclass Archive(TimerDetailView):\n def process(self):\n if self.timer.archived:\n self.timer.unarchive()\n else:\n self.timer.archive()\n\n\nclass Delete(TimerDetailView):\n def process(self):\n timer = str(self.timer)\n self.timer.delete()\n messages.success(self.request, 'Deleted timer \"{0}\".'.format(timer))\n\n\nclass Timeline(ArZeitTemplateView):\n context_class = TimelineContext\n template_name = 'timers/timeline.html'\n\n def get_context_data(self, **kwargs):\n ctx = super().get_context_data(**kwargs)\n data_date = get_report_date(self.request)\n data = self.get_timeline_data(data_date)\n ctx.update({\n 'report_date': data_date,\n 'data': data,\n })\n return ctx\n\n def get_timeline_data(self, data_date):\n interval_data = {}\n min_time = None\n min_hour = None\n max_time = None\n max_hour = None\n\n user_intervals = Interval.user_intervals(self.request.user)\n y, m, d = data_date.year, data_date.month, data_date.day\n tz = data_date.tzinfo\n min_datetime = datetime(y, m, d, 0, 0, 0, 0, tz)\n max_datetime = datetime(y, m, d, 23, 59, 59, 999999, tz)\n intervals = (\n user_intervals\n .filter(start__range=(min_datetime, max_datetime))\n .order_by('start')\n )\n\n nowtz = now().astimezone(tz=tz)\n\n for interval in intervals:\n root_cat = interval.timer.category.root_parent.name\n start = interval.start.astimezone(tz=tz)\n end = interval.end.astimezone(tz=tz) if interval.end else nowtz\n\n if min_time is None or start < min_time:\n min_time = start\n if max_time is None or (end and end > max_time):\n max_time = end\n if root_cat not in interval_data:\n interval_data[root_cat] = {\n 'category_name': root_cat,\n 'intervals': [],\n }\n interval_data[root_cat]['intervals'].append({\n 'interval_id': interval.id,\n 'timer_id': interval.timer.id,\n 'timer_name': interval.timer.name,\n 'start': start,\n 'end': end,\n })\n\n if min_time is None:\n min_hour = time(8, 0, 0, 0)\n else:\n h, m, s, ms = [\n getattr(min_time, x)\n for x in ['hour', 'minute', 'second', 'microsecond']\n ]\n min_hour = time(h, 0, 0, 0)\n\n if max_time is None:\n max_hour = time(17, 0, 0, 0)\n else:\n # cap at midnight\n hour_later = max([max_time, max_time + timedelta(hours=1)])\n # TODO: handle intervals extending past midnight...\n h, m, s, ms = [\n getattr(hour_later, x)\n for x in ['hour', 'minute', 'second', 'microsecond']\n ]\n max_hour = time(h, 0, 0, 0)\n\n return {\n 'interval_data': interval_data,\n 'min_hour': min_hour,\n 'max_hour': max_hour,\n }\n"
},
{
"alpha_fraction": 0.659217894077301,
"alphanum_fraction": 0.659217894077301,
"avg_line_length": 32.5625,
"blob_id": "2f46e0f558824af9f54d88a82dedc408586c4aed",
"content_id": "ae6350967dda988540c3c0bfe1ab3fc39c190114",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 537,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 16,
"path": "/reports/urls.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from django.conf.urls import url\n\nfrom reports.views import daily_summary, intervals, totals, weekly_summary\n\n\nurlpatterns = [\n url(r'^intervals/day/$', intervals, name='intervals'),\n\n url(r'^day/$', daily_summary, name='daily_summary'),\n url(r'^day/full/$', daily_summary, {'full': True}, name='daily_summary_full'),\n\n url(r'^week/$', weekly_summary, name='weekly_summary'),\n url(r'^week/full/$', weekly_summary, {'full': True}, name='weekly_summary_full'),\n\n url(r'^totals/$', totals, name='totals_between_dates'),\n]\n"
},
{
"alpha_fraction": 0.6761229038238525,
"alphanum_fraction": 0.6761229038238525,
"avg_line_length": 21.864864349365234,
"blob_id": "3d638f0c9c61d4c72c0cf45e1bb300321a692c44",
"content_id": "8ed1aaab4c2a9721364c1f52e3f96171f8776ab5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 846,
"license_type": "permissive",
"max_line_length": 67,
"num_lines": 37,
"path": "/core/json.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "from copy import deepcopy\nimport pytz\n\nfrom django.utils.timezone import now\n\nfrom timers.models import Timer\n\nSERVER_TIME_FORMAT = '%B %d, %Y, %I:%M %p'\n\nJSON_TEMPLATE_TO_CLIENT = {\n 'data': {},\n 'error': False,\n 'error_msg': '',\n 'server_time': None,\n 'active_timers': [],\n}\n\n\ndef get_server_time(user):\n tz = pytz.timezone(user.profile.timezone)\n return tz.normalize(now())\n\n\ndef get_server_time_str(user):\n return get_server_time(user).strftime(SERVER_TIME_FORMAT)\n\n\ndef get_active_timers(user):\n timers = Timer.objects.filter(category__user=user, active=True)\n return [t.ajax_dict for t in timers]\n\n\ndef get_base_json_data(user):\n response = deepcopy(JSON_TEMPLATE_TO_CLIENT)\n response['server_time'] = get_server_time_str(user)\n response['active_timers'] = get_active_timers(user)\n return response\n"
},
{
"alpha_fraction": 0.5724206566810608,
"alphanum_fraction": 0.5803571343421936,
"avg_line_length": 33.75862121582031,
"blob_id": "18f5780f4ee0acc113fa7798e519428f3c2dab6a",
"content_id": "648c3f0dc5a09bf3b6e8d1eb70edc8740fb5bd74",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1008,
"license_type": "permissive",
"max_line_length": 118,
"num_lines": 29,
"path": "/categories/migrations/0001_initial.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('name', models.CharField(max_length=100, verbose_name='Category')),\n ('description', models.CharField(blank=True, max_length=1000, null=True, verbose_name='Description')),\n ('parent', models.ForeignKey(null=True, blank=True, to='categories.Category')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'ordering': ['name'],\n },\n bases=(models.Model,),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5547366142272949,
"alphanum_fraction": 0.5602948069572449,
"avg_line_length": 25.95765495300293,
"blob_id": "1246fd8daf2032345793033c761eadb06b37a95b",
"content_id": "59d0b2474d2213eced3c80df070651590df83dd2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8276,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 307,
"path": "/timers/models.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "import pytz\nfrom functools import total_ordering\n\nfrom django.db import models\nfrom django.utils.timezone import datetime, make_aware, now, timedelta\n\nfrom categories.models import Category\n\n\nclass Timer(models.Model):\n\n class Meta:\n ordering = ['name']\n\n category = models.ForeignKey(Category)\n\n name = models.CharField(\n verbose_name='Name',\n max_length=100,\n )\n\n reportable = models.BooleanField(\n verbose_name='Reportable',\n default=False,\n )\n\n active = models.BooleanField(\n verbose_name='Active',\n default=False,\n )\n\n archived = models.BooleanField(\n verbose_name='Archived',\n default=False,\n )\n\n def __str__(self):\n return self.name\n\n def linkify(self):\n return '<a href=\"#timer_{0.id}\">{0}</a>'.format(self)\n\n @property\n def show_in_selective_reports(self):\n return self.reportable and not self.archived\n\n def start(self):\n self.category.root_parent.stop_all_timers()\n\n interval = Interval(timer=self)\n interval.save()\n\n self.active = True\n self.save()\n\n def stop(self):\n interval = self.interval_set.get(\n end=None,\n )\n interval.end = now()\n interval.save()\n\n self.active = False\n self.save()\n\n def archive(self):\n self.archived = True\n self.save()\n\n def unarchive(self):\n self.archived = False\n self.save()\n\n def get_intervals_between_dates(self, start_date, end_date):\n user_tz = pytz.timezone(self.category.user.profile.timezone)\n local_start_date = user_tz.normalize(start_date.astimezone(user_tz))\n local_end_date = user_tz.normalize(end_date.astimezone(user_tz))\n local_date_start = datetime(\n local_start_date.year,\n local_start_date.month,\n local_start_date.day,\n 0,\n 0,\n 0,\n )\n local_date_end = datetime(\n local_end_date.year,\n local_end_date.month,\n local_end_date.day,\n 23,\n 59,\n 59,\n )\n return self.interval_set.filter(\n start__range=(\n make_aware(local_date_start, user_tz),\n make_aware(local_date_end, user_tz)\n ),\n )\n\n def get_intervals_on_date(self, date):\n user_tz = pytz.timezone(self.category.user.profile.timezone)\n local_date = user_tz.normalize(date.astimezone(user_tz))\n local_date_start = datetime(\n local_date.year, local_date.month, local_date.day, 0, 0, 0)\n local_date_end = datetime(\n local_date.year, local_date.month, local_date.day, 23, 59, 59)\n return self.interval_set.filter(\n start__range=(\n make_aware(local_date_start, user_tz),\n make_aware(local_date_end, user_tz)\n ),\n )\n\n def get_intervals_on_date_week(self, date):\n user_tz = pytz.timezone(self.category.user.profile.timezone)\n local_date = user_tz.normalize(date.astimezone(user_tz))\n year, week, dow = local_date.isocalendar()\n return self.interval_set.filter(\n start__year=year,\n week=week,\n )\n\n def get_first_interval_after(self, date):\n user_tz = pytz.timezone(self.category.user.profile.timezone)\n local_date = user_tz.normalize(date.astimezone(user_tz))\n local_date_for_filter = datetime(\n local_date.year,\n local_date.month,\n local_date.day,\n 0,\n 0,\n 0,\n )\n intervals = self.interval_set.filter(\n start__gt=make_aware(local_date_for_filter, user_tz),\n ).order_by('start')\n return intervals.first()\n\n def get_last_interval_before(self, date):\n user_tz = pytz.timezone(self.category.user.profile.timezone)\n local_date = user_tz.normalize(date.astimezone(user_tz))\n local_date_for_filter = datetime(\n local_date.year,\n local_date.month,\n local_date.day,\n 23,\n 59,\n 59,\n )\n intervals = self.interval_set.filter(\n start__lt=make_aware(local_date_for_filter, user_tz),\n ).order_by('start')\n return intervals.last()\n\n def get_total_time_between_dates(self, start_date, end_date):\n intervals = self.get_intervals_between_dates(start_date, end_date)\n total = timedelta(0)\n for interval in intervals:\n total += interval.length\n return total\n\n def get_total_time_on_date(self, date):\n intervals = self.get_intervals_on_date(date)\n total = timedelta(0)\n for interval in intervals:\n total += interval.length\n return total\n\n def get_total_time_on_date_week(self, date):\n intervals = self.get_intervals_on_date_week(date)\n total = timedelta(0)\n for interval in intervals:\n total += interval.length\n return total\n\n @property\n def total_time(self):\n intervals = self.interval_set.all()\n total = timedelta(0)\n for interval in intervals:\n total += interval.length\n return total\n\n @property\n def intervals_yesterday(self):\n yesterday = now() - timedelta(days=1)\n return self.get_intervals_on_date(yesterday)\n\n @property\n def intervals_today(self):\n return self.get_intervals_on_date(now())\n\n @property\n def yesterday(self):\n \"\"\"\n Total time for today as a datetime.timedelta object.\n \"\"\"\n yesterday = now() - timedelta(days=1)\n return self.get_total_time_on_date(yesterday)\n\n @property\n def today(self):\n \"\"\"\n Total time for today as a datetime.timedelta object.\n \"\"\"\n return self.get_total_time_on_date(now())\n\n @property\n def last_week(self):\n \"\"\"\n Total time for last_week as a datetime.timedelta object.\n \"\"\"\n year, week, dow = (now() - timedelta(days=7)).isocalendar()\n intervals = Interval.objects.filter(\n timer=self,\n start__year=year,\n week=week,\n )\n total = timedelta(0)\n for interval in intervals:\n total += interval.length\n return total\n\n @property\n def hierarchy_display(self):\n return '{0} :: {1}'.format(self.category.hierarchy_display, self)\n\n @property\n def ajax_dict(self):\n return {\n 'id': self.pk,\n 'name': self.name,\n 'hierarchy': self.hierarchy_display,\n }\n\n\n@total_ordering\nclass Interval(models.Model):\n\n class Meta:\n ordering = ['-start']\n\n timer = models.ForeignKey(Timer)\n\n week = models.IntegerField(\n verbose_name='Week',\n db_index=True,\n )\n\n year = models.IntegerField(\n verbose_name='Year',\n db_index=True,\n )\n\n start = models.DateTimeField(\n verbose_name='Start Time',\n auto_now_add=True,\n )\n\n end = models.DateTimeField(\n verbose_name='End Time',\n blank=True,\n null=True,\n )\n\n notes = models.CharField(\n verbose_name='Notes',\n max_length=1000,\n blank=True,\n null=True,\n )\n\n def __init__(self, *args, **kwargs):\n today = now()\n year, week, dow = today.isocalendar()\n kwargs['week'] = week\n kwargs['year'] = today.year\n kwargs['start'] = now()\n super().__init__(*args, **kwargs)\n\n def __eq__(self, other):\n return self.pk == other.pk\n\n def __lt__(self, other):\n return self.start < other.start\n\n @property\n def length(self):\n \"\"\"\n Length of the interval. Returns datetime.timedelta object.\n \"\"\"\n end = self.end if self.end is not None else now()\n return end - self.start\n\n @classmethod\n def user_intervals(cls, user):\n return cls.objects.filter(timer__category__user=user)\n\n def active_at(self, dt):\n active = False\n if self.start <= dt:\n if self.end is None:\n active = dt <= now()\n else:\n active = self.end >= dt\n return active\n"
},
{
"alpha_fraction": 0.6216568946838379,
"alphanum_fraction": 0.6490541696548462,
"avg_line_length": 25.894737243652344,
"blob_id": "8a167cbd6ec137795dd8253eccc76e67b1799f8b",
"content_id": "1f830a9a179ace74eb5231d8a94f20bcb3c771b6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1533,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 57,
"path": "/timers/templatetags/timer_tags.py",
"repo_name": "peap/djarzeit",
"src_encoding": "UTF-8",
"text": "import re\nfrom datetime import timedelta\n\nfrom django import template\n\nregister = template.Library()\n\nTIMEDELTA_REGEX = re.compile(r'^(.*)(\\.[0-9]*)$')\n\n\[email protected]\ndef format_date(value):\n new_value = ''\n if hasattr(value, 'strftime'):\n new_value = value.strftime('%m/%d/%Y')\n return new_value\n\n\[email protected]\ndef format_timedelta(value):\n new_value = ''\n if isinstance(value, timedelta):\n hours, remainder = divmod(round(value.total_seconds()), 3600)\n minutes, seconds = divmod(remainder, 60)\n new_value = '{0:02}:{1:02}'.format(hours, minutes)\n return new_value\n\n\[email protected]\ndef format_timedelta_blank(value):\n new_value = ''\n if isinstance(value, timedelta):\n if value.total_seconds() > 0:\n hours, remainder = divmod(round(value.total_seconds()), 3600)\n minutes, seconds = divmod(remainder, 60)\n new_value = '{0:02}:{1:02}'.format(hours, minutes)\n return new_value\n\n\[email protected]\ndef format_timedelta_long(value):\n new_value = ''\n if isinstance(value, timedelta):\n hours, remainder = divmod(round(value.total_seconds()), 3600)\n minutes, seconds = divmod(remainder, 60)\n new_value = '{0:02}:{1:02}:{2:02}'.format(hours, minutes, seconds)\n return new_value\n\n\[email protected]\ndef time_on_date(cat_or_timer, date):\n return cat_or_timer.get_total_time_on_date(date)\n\n\[email protected]\ndef time_on_date_week(cat_or_timer, date):\n return cat_or_timer.get_total_time_on_date_week(date)\n"
}
] | 25 |
arsho/shutdownscheduler
|
https://github.com/arsho/shutdownscheduler
|
d41fbe91ea264d2c0a71bb71748b3c5186907e38
|
5977d6f95626428f00c293d003f1f0a84cc87acc
|
1838a56d765b2b27a30f86da18402e2baabf63e0
|
refs/heads/master
| 2020-03-12T10:35:35.665132 | 2018-04-22T15:04:24 | 2018-04-22T15:04:24 | 130,576,634 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.56965172290802,
"alphanum_fraction": 0.5746268630027771,
"avg_line_length": 23.125,
"blob_id": "9ec1512b385db381c767f7c9399f7b2ed734d130",
"content_id": "0011ac3d213a63f4ddc9396fb022c2362319f253",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 402,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 16,
"path": "/tests/unit_tests.py",
"repo_name": "arsho/shutdownscheduler",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\nimport unittest\r\nimport os\r\nimport sys\r\nimport tkinter as tk\r\nimport platform\r\nBASEDIR = os.path.abspath(os.path.join(\r\n os.path.dirname(os.path.abspath(__file__)),\r\n \"..\"))\r\nsys.path.insert(0, BASEDIR)\r\nimport main\r\n\r\nclass TestShutdownScheduler(unittest.TestCase):\r\n pass\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n"
},
{
"alpha_fraction": 0.6745613813400269,
"alphanum_fraction": 0.6956140398979187,
"avg_line_length": 24.772727966308594,
"blob_id": "2fba0408b20892dce73843e2c9598d7e6431a389",
"content_id": "bbf2a1324a14e4da65c36f6ead358877bc54caf8",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 1140,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 44,
"path": "/README.rst",
"repo_name": "arsho/shutdownscheduler",
"src_encoding": "UTF-8",
"text": "SHUTDOWN SCHEDULER\n==================\n\n|Build Status| |Size| |Codecov|\n\nSchedule shutdown of your machine using Shutdown Scheduler.\n\nIt currently supports Ubuntu (16.04 and later) and Windows (8 and later).\n\nFeatures\n~~~~~~~~\n\n- Shutdown your machine after:\n\n - 5 / 15 / 30 / 45 / 60 / 65 / 75 / 105 / 120 minutes\n\n- Cancel previous scheduled shutdown.\n\nInstallation\n~~~~~~~~~~~~\n\nWill be added soon.\n\n.. code:: bash\n\n $ pip install bangla\n\n\t\nContribute\n~~~~~~~~~~\n\nCreate Github Pull Request https://github.com/arsho/shutdownscheduler/pulls\n\nIf you have suggestion use GitHub issue system or send a message in Facebook https://www.facebook.com/ars.shovon.\n\n\n.. |Build Status| image:: https://travis-ci.org/arsho/shutdownscheduler.svg?branch=master\n :target: https://travis-ci.org/arsho/shutdownscheduler\n \n.. |Size| image:: https://img.shields.io/github/size/arsho/bangla/bangla/__init__.py.svg?\n :target: https://github.com/arsho/shutdownscheduler/ \n \n.. |Codecov| image:: https://codecov.io/github/arsho/shutdownscheduler/coverage.svg?branch=master\n :target: https://codecov.io/github/arsho/shutdownscheduler \n"
},
{
"alpha_fraction": 0.5190128684043884,
"alphanum_fraction": 0.5320503115653992,
"avg_line_length": 38.030303955078125,
"blob_id": "db4df798da560fdb7167fcd06979a330755eb7b8",
"content_id": "d31f97c7cc7e654295b26077142805ef213fd359",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6443,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 165,
"path": "/main.py",
"repo_name": "arsho/shutdownscheduler",
"src_encoding": "UTF-8",
"text": "import subprocess\nimport os\nimport tkinter as tk\nimport platform\n\n\nclass Application(tk.Frame):\n def __init__(self, master = None):\n super().__init__(master)\n self.set_constants()\n self.pack()\n self.max_columns = 5\n self.current_row = 0\n self.set_initial_window()\n self.create_widgets()\n\n def set_constants(self):\n self.os = self.get_os().lower()\n self.program_title = \"Shutdown Scheduler - arsho\"\n self.header_title = \"Shutdown Scheduler\"\n self.shutdown_helper_text = \"Schedule shutdown between 5 to 120 minutes\"\n\n def set_initial_window(self):\n self.set_window_title()\n self.set_window_size(width = 1080, height = 550)\n\n def set_window_size(self, width = 720, height = 250):\n screen_width = root.winfo_screenwidth()\n screen_height = root.winfo_screenheight()\n x_position = int((screen_width/4)-(width/4))\n y_position = int((screen_height/2)-(height/2))\n root.geometry('{}x{}+{}+{}'.format(width, height, x_position, y_position)) \n\n def set_window_title(self):\n root.title(self.program_title)\n\n def create_widgets(self):\n self.create_header_label()\n self.create_command_output_label()\n self.create_shutdown_buttons([5, 15, 30, 45, 60, 65, 75, 90, 105, 120])\n self.create_shutdown_now_button()\n self.create_shutdown_cancel_button()\n self.create_exit_button()\n\n def create_header_label(self):\n self.header = tk.Label(self)\n self.header[\"text\"] = self.header_title\n self.header[\"font\"] = (\"Arial Bold\", 24)\n self.header.grid(row=self.current_row,\n columnspan=self.max_columns,\n padx=10,\n pady=10,\n sticky=tk.W+tk.E+tk.S+tk.N)\n self.current_row+=1\n\n def create_command_output_label(self):\n self.command_output = tk.Label(self)\n self.command_output[\"font\"] = (\"Arial\", 14)\n self.command_output[\"text\"] = self.shutdown_helper_text\n self.command_output.grid(row=self.current_row,\n columnspan=self.max_columns,\n sticky=tk.W+tk.E+tk.S+tk.N)\n self.current_row+=1\n\n def create_shutdown_buttons(self, times):\n times_length = len(times)\n column=0\n for i in range(times_length):\n value = times[i]\n if i%self.max_columns==0:\n self.current_row+=1\n column=0\n shutdown_btn = tk.Button(self)\n shutdown_btn[\"text\"] = \"{} minutes\".format(value)\n shutdown_btn[\"font\"] = (\"Arial Bold\", 18)\n shutdown_btn[\"command\"] = lambda value=value:self.shutdown(value)\n shutdown_btn.grid(row=self.current_row,\n column=column,\n padx=5,\n pady=5,\n sticky=tk.W+tk.E+tk.S+tk.N)\n column+=1\n self.current_row+=1\n\n def create_shutdown_now_button(self):\n self.shutdown_now_button = tk.Button(self)\n self.shutdown_now_button[\"text\"]=\"Shutdown Now\"\n self.shutdown_now_button[\"font\"] = (\"Arial Bold\", 18)\n self.shutdown_now_button[\"fg\"]=\"white\"\n self.shutdown_now_button[\"bg\"]=\"red\" \n self.shutdown_now_button[\"command\"]=lambda value=0:self.shutdown(value)\n self.shutdown_now_button.grid(row=self.current_row,\n padx=5,\n pady=5,\n columnspan=self.max_columns,\n sticky=tk.W+tk.E+tk.S+tk.N)\n self.current_row+=1\n\n def create_shutdown_cancel_button(self):\n self.shutdown_cancel_button = tk.Button(self)\n self.shutdown_cancel_button[\"text\"]=\"Cancel Shutdown\"\n self.shutdown_cancel_button[\"font\"] = (\"Arial Bold\", 18)\n self.shutdown_cancel_button[\"fg\"]=\"blue\"\n self.shutdown_cancel_button[\"command\"]=self.shutdown_cancel\n self.shutdown_cancel_button.grid(row=self.current_row,\n padx=5,\n pady=5,\n columnspan=self.max_columns,\n sticky=tk.W+tk.E+tk.S+tk.N)\n self.current_row+=1\n\n def create_exit_button(self):\n self.exit_button = tk.Button(self)\n self.exit_button[\"text\"] = \"Exit\"\n self.exit_button[\"font\"] = (\"Arial Bold\", 18)\n self.exit_button[\"fg\"]=\"red\"\n self.exit_button[\"command\"]=root.destroy\n self.exit_button.grid(row=self.current_row,\n columnspan=self.max_columns,\n padx=5,\n pady=5,\n sticky=tk.W+tk.E+tk.S+tk.N)\n self.current_row+=1\n\n def execute_command(self, command):\n command = command.split()\n try:\n command_process = subprocess.run(command,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n output = command_process.stdout.decode('utf-8') \n output_message = \"{}\".format(output)\n error = command_process.stderr.decode('utf-8') \n error_message = \"{}\".format(error)\n self.show_message(output_message)\n self.show_message(error_message)\n except Exception as error:\n command_error_message = str(error)\n self.show_message(command_error_message)\n\n def show_message(self, message):\n if message!=\"\":\n print(message)\n self.command_output[\"text\"] = message\n\n def shutdown_cancel(self):\n command = 'shutdown -c'\n if self.os == \"windows\":\n command = 'shutdown -a -y'\n self.command_output[\"text\"] = \"Cancelled scheduled shutdown\"\n self.execute_command(command)\n\n def shutdown(self, value):\n command = 'shutdown -h {}'.format(value)\n if self.os == \"windows\":\n command = 'shutdown -s -t {} -y'.format(value*60)\n self.execute_command(command)\n\n def get_os(self):\n return platform.system()\n\nif __name__ == '__main__':\n root = tk.Tk()\n app = Application(master=root)\n app.mainloop() \n"
}
] | 3 |
kyungeonchoi/ServiceXforNtupleMaker
|
https://github.com/kyungeonchoi/ServiceXforNtupleMaker
|
afd4ac6594981ddcf1fb7cf049be445d0f10e046
|
ed0e365a478e84f440f92950a845da2ee3749729
|
ee22b5d21cc81d9a53bb81117ec4ab0eeffdbdd4
|
refs/heads/master
| 2022-11-06T16:56:29.335372 | 2020-06-22T15:44:29 | 2020-06-22T15:44:29 | 257,713,415 | 0 | 0 | null | 2020-04-21T20:54:12 | 2020-06-22T15:40:21 | 2020-06-22T15:44:30 |
Python
|
[
{
"alpha_fraction": 0.5522565245628357,
"alphanum_fraction": 0.559144914150238,
"avg_line_length": 47.40229797363281,
"blob_id": "f50ee941e663803a20a9939252b8dfd25d92c0d8",
"content_id": "9bed3ede60481c941c2aebc0f85928bbf5f402f4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4210,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 87,
"path": "/servicex_postprocessing.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "import uproot\n# import awkward\nimport pyarrow.parquet as pq\nimport numpy\nimport coffea\nimport os\nimport re\nimport logging\nfrom minio import Minio\n# from ServiceXRequests import read_configuration, load_requests\n# from ServiceXConfig import connect_servicex_backend, disconnect_servicex_backend\n# from ServiceXRequests import read_configuration\n\nlogger = logging.getLogger('servicex_logger')\n\ndef _download_output_files(request_id_list, did_list, base_outpath):\n if len([x for x in request_id_list if x is not None]):\n minio_endpoint = \"localhost:9000\"\n minio_client = Minio(minio_endpoint,\n access_key='miniouser',\n secret_key='leftfoot1',\n secure=False)\n for request_id, did in zip(request_id_list, did_list):\n if request_id is not None:\n objects = minio_client.list_objects(request_id)\n sample_files = list([file.object_name for file in objects]) \n for i in range(len(sample_files)):\n minio_client.fget_object(request_id, sample_files[i], f'{base_outpath}/{did.split(\":\")[1]}/{sample_files[i].split(\":\")[-1]}')\n else:\n return None\n\n\n# def get_lumi(full_config):\n# lumi = full_config['Job0']['Lumi'].split('%')[0].strip()\n# if re.findall(r'(XXX_\\w+)',lumi):\n# replacements = re.findall(r'(XXX_\\w+)',lumi)\n# replacement_file = full_config['Job0']['ReplacementFile']\n# with open( replacement_file ) as replacementFile:\n# for line in enumerate(replacementFile.readlines()):\n# for xxx in replacements:\n# if re.search(rf'{xxx}\\b', line[1]):\n# lumi = re.sub(xxx, line[1].strip(xxx + \":\").strip(), lumi)\n# return lumi\n\n\n# def output_to_histogram(servicex_request, full_config, request_id_list, sample_list):\n# if len([x for x in request_id_list if x is not None]):\n# if servicex_request[\"result-format\"] == \"parquet\":\n# # logger.info(f'Merge files from request id: {request_id}')\n\n# # output_file per REGION\n# output_file_name = full_config[\"Job0\"][\"Job\"] + \"/Histograms/\" + full_config[\"Job0\"][\"InputName\"]+\"_\"+full_config['Region0']['Region'] + \"_histos.root\"\n# fout = uproot.recreate( output_file_name )\n\n# binFromVariable = False\n# try:\n# full_config['Region0']['Binning'].split(\",\")\n# binFromVariable = True\n# logger.info(f'Histogram binning from \"Region/Variable\"')\n# except KeyError:\n# logger.info(f'Histogram binning from \"Region/Binning\"')\n\n# if binFromVariable:\n# hist_binning = full_config['Region0']['Binning'].split(\",\") \n# else:\n# start = float(full_config['Region0']['Variable'].split(\",\")[2])\n# stop = float(full_config['Region0']['Variable'].split(\",\")[3])\n# step = (stop-start)/int(full_config['Region0']['Variable'].split(\",\")[1])\n# hist_binning = [x for x in numpy.arange(start, stop, step)]\n\n# # histograms for SAMPLE in REGION\n# for (request_id, sample) in zip(request_id_list, sample_list):\n# hist_name = full_config[\"Region0\"][\"Region\"] + \"_\" + sample\n# h = coffea.hist.Hist(hist_name, coffea.hist.Bin(\"var\", \"\", hist_binning))\n# for file in os.listdir(full_config[\"Job0\"][\"Job\"]+'/Histograms'): \n# if request_id in file: \n# columns = pq.read_table(full_config[\"Job0\"][\"Job\"]+\"/Histograms/\"+file)\n# h.fill(var=numpy.array(columns.column(0)))\n# # h.scale(float(get_lumi(full_config)))\n# os.remove(full_config[\"Job0\"][\"Job\"]+\"/Histograms/\"+file)\n# h.scale(float(get_lumi(full_config))) # Normalize to the luminosity\n# fout[hist_name] = coffea.hist.export1d(h)\n \n# fout.close()\n# logger.info(f'Output file is created at: {output_file_name}')\n# else:\n# return None"
},
{
"alpha_fraction": 0.6204195022583008,
"alphanum_fraction": 0.6229466795921326,
"avg_line_length": 34.98181915283203,
"blob_id": "e7beef138cf0fa06b9961c57fefa67642ff4e8e8",
"content_id": "58b8f895fd58c6f2219c10a86a3a029485e59c44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3957,
"license_type": "no_license",
"max_line_length": 180,
"num_lines": 110,
"path": "/servicex_config.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "import subprocess\nimport json\nimport logging\nimport psutil\nimport time\n\nlogger = logging.getLogger('servicex_logger')\n\ndef _is_chart_running(name: str):\n \"\"\"\n Check whether a helm chart with `name` is running\n \"\"\"\n result = subprocess.run(['helm', 'list', '--filter', name, '-q'], stdout=subprocess.PIPE)\n if result.returncode != 0:\n return False\n if result.stdout.decode('utf-8').strip() != name:\n return False\n return True\n\n\ndef _get_pod_status(name: str):\n \"\"\"\n Get the pod status for everything that starts with name\n \"\"\"\n result = subprocess.run(['kubectl', 'get', 'pod', '-o', 'json'], stdout=subprocess.PIPE)\n # print(result)\n data = json.loads(result.stdout)\n return [{'name': p['metadata']['name'], 'status': all([s['ready'] for s in p['status']['containerStatuses']])} for p in data['items'] if p['metadata']['name'].startswith(name)]\n\n\ndef _get_existing_transformers():\n result = subprocess.run(['kubectl', 'get', 'pod', '-o', 'json'], stdout=subprocess.PIPE)\n # print(result)\n data = json.loads(result.stdout)\n existing_transformers = len([p for p in data['items'] if p['metadata']['name'].startswith('transformer')])\n logger.debug(f'Number of existing transformer pods before make request: {existing_transformers}')\n\n\ndef _check_servicex_pods(name: str):\n \"\"\"\n Checking helm chart of ServiceX and pod status\n \"\"\"\n # if not _is_chart_running(name):\n # raise BaseException(f\"Helm chart is not deployed!\") \n status = _get_pod_status(name)\n is_ready = all(s['status'] for s in status)\n if not is_ready:\n raise BaseException(f\"ServiceX is not ready! Pod(s) are not running.\")\n logger.info(f'ServiceX is up and running!')\n \n\ndef _find_pod(helm_release_name:str, pod_name:str):\n \"\"\"\n Find the pod name in the release and return the full name\n \"\"\"\n pods = _get_pod_status(helm_release_name)\n named_pods = [p['name'] for p in pods if p['name'].startswith(f\"{helm_release_name}-{pod_name}\")]\n assert len(named_pods) == 1 \n return named_pods[0]\n\n\ndef _check_portforward_running(processName: str):\n \"\"\"\n Iterate over the all the running process\n \"\"\"\n for proc in psutil.process_iter():\n try:\n if \"kubectl\" in proc.name().lower() and processName in proc.cmdline()[2]:\n return True\n except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):\n pass\n return False\n\n\ndef _connect_servicex_backend(name: str, app_name: str, port: int):\n \"\"\"\n Connect ServiceX backend\n \"\"\"\n if not _check_portforward_running(app_name): \n try:\n subprocess.Popen([\"kubectl\", \"port-forward\", _find_pod(name, app_name), \"{}:{}\".format(port,port)], stdout=subprocess.DEVNULL)\n logger.info(f\"Connect to the backend of {app_name}\")\n time.sleep(2) # Wait until port-forward is being established \n except:\n logger.info(f\"Cannot connect to the backend of {app_name}\")\n else:\n logger.info(f\"Already connected to the backend of {app_name}\") \n\n\ndef _disconnect_servicex_backend():\n \"\"\"\n Disconnect ServiceX backend\n \"\"\"\n servicex_backend_pids = []\n for p in psutil.process_iter():\n try:\n all_process = p.name()\n except (psutil.AccessDenied, psutil.ZombieProcess):\n pass\n except psutil.NoSuchProcess:\n continue\n if all_process.lower() == \"kubectl\" and (\"servicex-app\" in p.cmdline()[2] or \"minio\" in p.cmdline()[2]):\n servicex_backend_pids.append(p.pid)\n\n for connection in servicex_backend_pids:\n try:\n logger.info( \"Disconnected to the backend: \" + psutil.Process(connection).cmdline()[2] )\n psutil.Process(connection).kill()\n except:\n logger.info( \"Cannot disconnect to the backend: \" + psutil.Process(connection).cmdline()[2] )"
},
{
"alpha_fraction": 0.5018247961997986,
"alphanum_fraction": 0.5064697861671448,
"avg_line_length": 48.01626205444336,
"blob_id": "cd00f0913b004fab4ad40263147910d266bb83f1",
"content_id": "f4f4c512d0d2c48200a46ecea83c0aeb763bf75c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6028,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 123,
"path": "/servicex_tcut_to_qastle_wrapper.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "import re\nimport logging\nimport qastle,ast\n\nlogger = logging.getLogger('servicex_logger')\n\ndef multiple_replace(dict, text):\n # Create a regular expression from the dictionary keys\n regex = re.compile(\"(%s)\" % \"|\".join(map(re.escape, dict.keys())))\n\n # For each match, look-up corresponding value in dictionary\n return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) \n\ndef tcut_to_qastle( selection, variable ):\n\n if selection.lower() != \"none\":\n\n # 1st step: recognize all variable names\n ignore_patterns = { # These are supported by Qastle\n \"abs\" : \" \",\n \"(\" : \" \",\n \")\" : \" \",\n \"*\" : \" \",\n \"/\" : \" \",\n \"+\" : \" \",\n \"-\" : \" \"\n }\n temp = multiple_replace(ignore_patterns, selection)\n\n output1 = re.sub('[<&>!=|-]',' ',temp)\n variables = []\n for x in output1.split():\n try:\n float(x)\n except ValueError:\n variables.append(x)\n variables = list(dict.fromkeys(variables)) # Remove duplicates\n # logging.info(f'Number of accessed branches for the selection: {len(variables)}')\n\n # 2nd step: replace variable names with event.\n for x in variables:\n selection = re.sub(r'\\b(%s)\\b'%x, r'event.%s'%x, selection)\n\n # 3rd step: replace operators \n replace_patterns = {\n \"&&\" : \" and \",\n \"||\" : \" or \",\n \"!=\" : \" != \",\n \">=\" : \" >= \",\n \"<=\" : \" <= \",\n \">\" : \" > \",\n \"<\" : \" < \" \n }\n output = multiple_replace(replace_patterns, selection)\n output = \" \".join(output.split()) # Remove duplicate whitespace\n\n # 4th step: bool (!! Still missing many combinations!!)\n output = \"and \" + output + \" and\" # Prepare for search. Better idea?\n for x in variables:\n if re.search(r'and\\s*event.%s\\s*and'%x, output): # and variable and\n output = re.sub(r'and\\s*event.%s\\s*and'%x, r'and event.%s > 0 and'%x, output)\n if re.search(r'and\\s*!event.%s\\s*and'%x, output): # and !variable and\n output = re.sub(r'and\\s*!event.%s\\s*and'%x, r'and event.%s == 0 and'%x, output)\n if re.search(r'and\\s*event.%s\\s*\\)'%x, output): # and variable )\n output = re.sub(r'and\\s*event.%s\\s*\\)'%x, r'and event.%s > 0)'%x, output)\n if re.search(r'and\\s*!event.%s\\s*\\)'%x, output): # and !variable )\n output = re.sub(r'and\\s*!event.%s\\s*\\)'%x, r'and event.%s == 0)'%x, output)\n if re.search(r'\\(\\s*event.%s\\s*and'%x, output): # ( variable and\n output = re.sub(r'\\(\\s*event.%s\\s*and'%x, r'(event.%s > 0 and'%x, output)\n if re.search(r'\\(\\s*!event.%s\\s*and'%x, output): # ( !variable and\n output = re.sub(r'\\(\\s*!event.%s\\s*and'%x, r'(event.%s == 0 and'%x, output)\n if re.search(r'or\\s*event.%s\\s*or'%x, output): # or variable or\n output = re.sub(r'or\\s*event.%s\\s*or'%x, r'or event.%s > 0 or'%x, output)\n if re.search(r'or\\s*!event.%s\\s*or'%x, output): # or !variable or\n output = re.sub(r'or\\s*!event.%s\\s*or'%x, r'or event.%s == 0 or'%x, output)\n if re.search(r'and\\s*event.%s\\s*or'%x, output): # and variable or\n output = re.sub(r'and\\s*event.%s\\s*or'%x, r'and event.%s > 0 or'%x, output)\n if re.search(r'and\\s*!event.%s\\s*or'%x, output): # and !variable or\n output = re.sub(r'and\\s*!event.%s\\s*or'%x, r'and event.%s == 0 or'%x, output) \n if re.search(r'or\\s*event.%s\\s*and'%x, output): # or variable and\n output = re.sub(r'or\\s*event.%s\\s*and'%x, r'or event.%s > 0 and'%x, output)\n if re.search(r'or\\s*!event.%s\\s*and'%x, output): # or !variable and\n output = re.sub(r'or\\s*!event.%s\\s*and'%x, r'or event.%s == 0 and'%x, output)\n if re.search(r'\\(\\s*event.%s\\s*or'%x, output): # ( variable or\n output = re.sub(r'\\(\\s*event.%s\\s*or'%x, r'(event.%s > 0 or'%x, output)\n if re.search(r'\\(\\s*!event.%s\\s*or'%x, output): # ( !variable or\n output = re.sub(r'\\(\\s*!event.%s\\s*or'%x, r'(event.%s == 0 or'%x, output)\n if re.search(r'or\\s*event.%s\\s*\\)'%x, output): # or variable )\n output = re.sub(r'or\\s*event.%s\\s*\\)'%x, r'or event.%s > 0)'%x, output)\n if re.search(r'or\\s*!event.%s\\s*\\)'%x, output): # or !variable )\n output = re.sub(r'or\\s*!event.%s\\s*\\)'%x, r'or event.%s == 0)'%x, output)\n if re.search(r'!\\([^()]*\\)', output): # Search for !(something)\n output = re.sub(r'!\\([^()]*\\)',re.search(r'!\\([^()]*\\)', output).group(0).lstrip('!') + \"==0\",output)\n \n output = output.rsplit(' ', 1)[0].split(' ', 1)[1] # Delete `and` at the beginning and the last\n else:\n variables = []\n\n passList = False\n passDict = True\n\n if variable.lower() == 'all':\n variable_text = 'event'\n else:\n if passDict:\n variable = [num.strip() for num in variable.split(',')]\n variable_list_new = [f'\\'{i}\\': event.{i}' for i in variable]\n variable_text = ', '.join(variable_list_new)\n variable_text = '{' + variable_text + '}'\n elif passList:\n variable = [num.strip() for num in variable.split(',')]\n variable_list_new = [f'event.{i}' for i in variable]\n variable_text = ', '.join(variable_list_new)\n variable_text = '(' + variable_text + ')'\n\n # Add Func ADL wrapper\n if selection.lower() == \"none\":\n query = \"EventDataset().Select(\\\"lambda event: \" + variable_text + \"\\\")\"\n else:\n query = \"EventDataset().Where('lambda event: \" + output + \"').Select(\\\"lambda event: \" + variable_text + \"\\\")\"\n text_ast = qastle.python_ast_to_text_ast(qastle.insert_linq_nodes(ast.parse(query)))\n\n return text_ast"
},
{
"alpha_fraction": 0.7942708134651184,
"alphanum_fraction": 0.7942708134651184,
"avg_line_length": 63.16666793823242,
"blob_id": "7f1acad54c126e5b2b03e335aec2bcf5c5b8bfb2",
"content_id": "10ab4facbfb671e62edc791d6f26d5885d01e0f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 384,
"license_type": "no_license",
"max_line_length": 248,
"num_lines": 6,
"path": "/README.md",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "# ServiceX for NtupleMaker\n\n## Overview\n[`ServiceX`](https://github.com/ssl-hep/ServiceX), a component of the IRIS-HEP DOMA group's iDDS, is an experiment-agnostic service to enable on-demand data delivery from data lakes in different data formats, including Apache Arrow and ROOT ntuple.\n\nServiceX reads `ROOT` flat ntuple files to perform a selection then deliver selected branches."
},
{
"alpha_fraction": 0.6063081622123718,
"alphanum_fraction": 0.6110733151435852,
"avg_line_length": 35.733333587646484,
"blob_id": "fd3acc4b3dfcd7a24cdc178e47ee3d9f8b0e08ec",
"content_id": "05d3fb40a78aefbf8720b7f30531e2d20dcfc217",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4407,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 120,
"path": "/servicex_request.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "import requests\nimport re\nimport linecache\nimport json\nimport time\nimport logging\nimport asyncio\nfrom tqdm import tqdm\nfrom servicex_tcut_to_qastle_wrapper import tcut_to_qastle\nfrom servicex_config import _get_existing_transformers\nfrom servicex_timer_logger import _write_transformer_log\n\nlogger = logging.getLogger('servicex_logger')\n\n\ndef _load_requests(inputDIDs: str):\n \"\"\"\n Prepare requests for ServiceX\n \"\"\"\n with open(inputDIDs) as f: \n did_list = ['.'.join(line.split(\".\")[:2])+':'+line.rstrip() for line in f] # Add scope to DID\n \n\n request_list = [] \n for did in did_list:\n\n selection = \"n_jets >= 0\"\n variable = \"n_jets\"\n request = {}\n request[\"did\"] = did\n request[\"tree-name\"] = \"NOMINAL\"\n request[\"selection\"] = tcut_to_qastle( selection, variable )\n request[\"image\"] = \"kyungeonchoi/servicex_pyroot_transformer:0.1\"\n request[\"result-destination\"] = \"object-store\" \n request[\"result-format\"] = \"parquet\"\n request[\"chunk-size\"] = \"1000\"\n request[\"workers\"] = \"2\"\n\n request_list.append(request) \n\n return request_list\n\n\ndef print_requests(request: str, request_id):\n console_print = {\"Input DID\": request[\"did\"], \\\n \"Request ID\": request_id}\n print(json.dumps(console_print, indent=4))\n request_log = request.copy()\n # del request_log['selection']\n logger.debug(json.dumps(request_log, indent=4))\n\n\n# def make_requests(request_list, full_config):\ndef _make_requests(request_list):\n \"\"\"\n Make transform request\n \"\"\" \n _get_existing_transformers()\n request_id_list = []\n did_list = []\n for req in request_list: \n response = requests.post(\"http://localhost:5000/servicex/transformation\", json=req) \n request_id = response.json()[\"request_id\"]\n request_id_list.append( request_id )\n did_list.append(req['did'])\n print_requests(req, request_id) # print simplified request query\n\n return request_id_list, did_list\n\n# async def monitor_requests(request_id, sample, pos:int):\nasync def _monitor_requests(request_id, pos:int):\n \"\"\"\n Monitor jobs\n \"\"\"\n if request_id == None:\n return None\n else:\n status_endpoint = f\"http://localhost:5000/servicex/transformation/{request_id}/status\"\n running = False\n while not running:\n status = requests.get(status_endpoint).json()\n files_remaining = status['files-remaining']\n files_processed = status['files-processed']\n if files_processed is not None and files_remaining is not None:\n running = True\n else:\n print('Status: Creating transformer pods...', end='\\r')\n status = requests.get(status_endpoint).json() \n files_remaining = status['files-remaining']\n files_processed = status['files-processed']\n total_files = files_remaining + files_processed\n t = tqdm(total=total_files, unit='file', desc=request_id, position=pos, leave=False)\n job_done = False\n while not job_done: \n t.refresh() \n await asyncio.sleep(1)\n status = requests.get(status_endpoint).json() \n t.update(status['files-processed'] - t.n)\n files_remaining = status['files-remaining']\n files_processed = total_files-files_remaining\n if files_remaining is not None:\n if files_remaining == 0:\n job_done = True\n t.close()\n _write_transformer_log(request_id)\n return request_id + \" - \" + str(status['files-processed']) + \"/\" + str(total_files) + \" files are processed\"\n\n\n# def _monitor_multiple_requests(request_id_list, sample_list):\ndef _monitor_multiple_requests(request_id_list):\n loop = asyncio.get_event_loop()\n # request_list = [monitor_requests(req, sam, i) for (req, sam, i) in zip(request_id_list, sample_list, range(len(request_id_list)))]\n request_list = [_monitor_requests(req, i) for (req, i) in zip(request_id_list, range(len(request_id_list)))]\n jobs = asyncio.wait(request_list)\n output,_ = loop.run_until_complete(jobs)\n print(\"\\n\")\n for job in output:\n # print(f\"Finished jobs: {job.result()}\")\n logger.info(f\"Finished jobs: {job.result()}\")\n loop.close()"
},
{
"alpha_fraction": 0.7472690939903259,
"alphanum_fraction": 0.7581926584243774,
"avg_line_length": 26.602739334106445,
"blob_id": "94839dc1e8b5ee57346a02820b2bce48d05b6b60",
"content_id": "a54786e73ba278e887a90755d218a3063384f6c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2014,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 73,
"path": "/servicex_reader.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "# ServiceX to deliver histogram out of flat ntuple at grid for ttH ML analysis\n# Requires Kubernetes cluster and ServiceX has to be deployed\n\nimport logging\n# import requests\nfrom servicex_config import _check_servicex_pods, _connect_servicex_backend, _disconnect_servicex_backend\nfrom servicex_request import _load_requests, _make_requests, _monitor_multiple_requests\nfrom servicex_postprocessing import _download_output_files\nfrom servicex_timer_logger import time_measure, logger\n\n# from ServiceX\ninputDIDs = 'test_list.txt'\nbase_outpath = '/Users/kchoi/Work/UTAustin/Computing/ServiceX/ServiceXforNtupleMaker/V03_new/mc/hadhad/mc16e/nom/'\n\n\n# Load logger\nlogger = logging.getLogger('servicex_logger')\n\n\n# Initialize timer\nt = time_measure(\"servicex\")\nt.set_time(\"start\")\n\n\n# Helm chart name of ServiceX\nservicex_helm_chart_name = \"uproot\"\n\n\n# Step 1: Check SerivceX pods\n_check_servicex_pods(servicex_helm_chart_name)\n# t.set_time(\"t_check_servicex_pods\")\n\n\n# Step 2: Prepare backend to make a request\n_connect_servicex_backend(servicex_helm_chart_name, \"servicex-app\", 5000)\n# t.set_time(\"t_connect_servicex_app\")\n\n\n# Step 3: Prepare transform requests\nservicex_request_list = _load_requests(inputDIDs)\n# t.set_time(\"t_prepare_request\")\n\n\n# Step 4: Make requests\nrequest_id_list, did_list = _make_requests(servicex_request_list)\n# t.set_time(\"t_make_request\")\n\n\n# Step 5: Monitor jobs\n_monitor_multiple_requests(request_id_list)\n# t.set_time(\"t_request_complete\")\n\n\n# Step 6: Prepare backend to download output\n_connect_servicex_backend(servicex_helm_chart_name, \"minio\", 9000)\n# t.set_time(\"t_connect_minio\")\n\n\n# Step 7: Download output\n_download_output_files(request_id_list, did_list, base_outpath)\n# t.set_time(\"t_download_outputs\")\n\n\n# Step 8: Post processing\n# output_to_histogram(servicex_request_list[0], full_config, request_id_list, sample_list)\n# t.set_time(\"t_postprocessing\")\n\n\n# Step 9: Disconnect from backends\n_disconnect_servicex_backend()\n# t.set_time(\"t_disconnect_apps\")\n\n# t.print_times()"
},
{
"alpha_fraction": 0.6637418866157532,
"alphanum_fraction": 0.667138397693634,
"avg_line_length": 46.119998931884766,
"blob_id": "5696c1a8237fd4f7bc5d16e8f93a1ae47a12f075",
"content_id": "7c6139c5a50b8751ac8ff3e64deed9b6b4170340",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3533,
"license_type": "no_license",
"max_line_length": 171,
"num_lines": 75,
"path": "/servicex_timer_logger.py",
"repo_name": "kyungeonchoi/ServiceXforNtupleMaker",
"src_encoding": "UTF-8",
"text": "import time\nfrom datetime import datetime\nimport logging\nimport subprocess\nimport json\n\n# create logger\nlogger = logging.getLogger('servicex_logger')\nlogger.setLevel(logging.DEBUG)\n\n# create console handler and set level to info\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n\n# create file handler and set level to debug\nfh = logging.FileHandler(filename=f'logs/{datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")}.log')\nfh.setLevel(logging.DEBUG)\n\n# create formatter\n# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nformatter = logging.Formatter('%(levelname)s:: %(message)s')\nfformatter = logging.Formatter('%(message)s')\n\n# add formatter to ch\nch.setFormatter(formatter)\nfh.setFormatter(fformatter)\n\n# add ch to logger\nlogger.addHandler(ch)\nlogger.addHandler(fh)\n\nlogger.info('Welcome to the ServiceX for NtupleMaker!!')\nlogger.debug(f'Job submission: {datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")}')\n\n# # 'application' code\n# logger.debug('debug message')\n# logger.info('info message')\n# logger.warning('warn message')\n# logger.error('error message')\n# logger.critical('critical message')\n\n\ndef _write_transformer_log(request_id):\n result = subprocess.run(['kubectl', 'get', 'pod', '-o', 'json'], stdout=subprocess.PIPE)\n data = json.loads(result.stdout)\n transformer_list = [p['metadata']['name'] for p in data['items'] if request_id in p['metadata']['name']]\n logger.debug(f'Transformer logs:')\n for transformer in transformer_list:\n logger.debug(subprocess.run(['kubectl', 'logs', transformer], stdout=subprocess.PIPE, universal_newlines=True).stdout)\n\n\nclass time_measure:\n times = {}\n\n def __init__(self, name):\n self.name = name\n\n def set_time(self, step:str):\n self.times.update({step:time.monotonic()})\n \n # def print_times(self):\n # col_width = 30\n # print(\"\\n\")\n # logger.info('Summary of durations')\n # logger.info(\"\\t\\tCheck ServiceX Pods:\".ljust(col_width) + f\"{str(round(self.times['t_check_servicex_pods'] - self.times['start'], 1))} sec\")\n # logger.info(\"\\t\\tConnect to ServiceX App:\".ljust(col_width) + f\"{str(round(self.times['t_connect_servicex_app'] - self.times['t_check_servicex_pods'], 1))} sec\")\n # logger.info(\"\\t\\tPrepare Transform request:\".ljust(col_width) + f\"{str(round(self.times['t_prepare_request'] - self.times['t_connect_servicex_app'], 1))} sec\")\n # logger.info(\"\\t\\tMake Request:\".ljust(col_width) + f\"{str(round(self.times['t_make_request'] - self.times['t_prepare_request'], 1))} sec\")\n # logger.info(\"\\t\\tTransform:\".ljust(col_width) + f\"{str(round(self.times['t_request_complete'] - self.times['t_make_request'], 1))} sec\")\n # logger.info(\"\\t\\tConnect to Minio:\".ljust(col_width) + f\"{str(round(self.times['t_connect_minio'] - self.times['t_request_complete'], 1))} sec\")\n # logger.info(\"\\t\\tDownload Outputs:\".ljust(col_width) + f\"{str(round(self.times['t_download_outputs'] - self.times['t_connect_minio'], 1))} sec\")\n # logger.info(\"\\t\\tPostprocessing:\".ljust(col_width) + f\"{str(round(self.times['t_postprocessing'] - self.times['t_download_outputs'], 1))} sec\")\n # logger.info(\"\\t\\tDisconnect ServiceX Apps:\".ljust(col_width) + f\"{str(round(self.times['t_disconnect_apps'] - self.times['t_postprocessing'], 1))} sec\")\n # logger.info(\"\\t\\t\" + \"-\"*col_width)\n # logger.info(\"\\t\\tTotal duration:\".ljust(col_width) + f\"{str(round(self.times['t_disconnect_apps'] - self.times['start'], 1))} sec\")"
}
] | 7 |
unixer/boost_program_options
|
https://github.com/unixer/boost_program_options
|
67b3fd96dfab75e526d232d962cc485b871d1b49
|
c8e63e35b8be2555f09d2cfd8d87f96231247690
|
fd04b91f351e24ac3ce0103a1f83f7c635c5f3d9
|
refs/heads/master
| 2021-01-16T19:47:15.470574 | 2011-04-11T17:07:40 | 2011-04-11T17:07:40 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7364184856414795,
"alphanum_fraction": 0.7364184856414795,
"avg_line_length": 61.125,
"blob_id": "6a9804d231c9d51ab29bf18c3b84183726cfec3d",
"content_id": "52c0f1c40423ce3ccd83d856796110593d31f070",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 8,
"path": "/SConstruct",
"repo_name": "unixer/boost_program_options",
"src_encoding": "UTF-8",
"text": "Program('program_options.cpp', LIBS=['boost_program_options'])\nProgram('regex.cpp', LIBS=['boost_program_options', 'boost_regex'])\nProgram('custom_syntax.cpp', LIBS=['boost_program_options'])\nProgram('multiple_sources.cpp', LIBS=['boost_program_options'])\nProgram('option_groups.cpp', LIBS=['boost_program_options'])\nProgram('options_description.cpp', LIBS=['boost_program_options'])\nProgram('real.cpp', LIBS=['boost_program_options'])\nProgram('response_file.cpp', LIBS=['boost_program_options'])\n"
}
] | 1 |
shafali731/capital_one_app
|
https://github.com/shafali731/capital_one_app
|
edb90617674b05731e77be7e8a16749faeb77c6c
|
235829ff3b2cfd0e5881ae3d41e9a7eade397ffd
|
4b5914d77ec50f59ad08c0b566bef9a4498a77a5
|
refs/heads/master
| 2021-02-07T22:30:02.973724 | 2020-03-05T07:01:01 | 2020-03-05T07:01:01 | 244,083,287 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5607432126998901,
"alphanum_fraction": 0.5655074119567871,
"avg_line_length": 31.045801162719727,
"blob_id": "304db2fad62074c2043d7dd82425f401d55470d5",
"content_id": "f3b0026f9abab1bc827dac9ba427b1a560a6048f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4198,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 131,
"path": "/app.py",
"repo_name": "shafali731/capital_one_app",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport os\nfrom flask import Flask, request, render_template, session, redirect, flash, url_for\nfrom util import sample\nfrom urllib.parse import quote\n\nimport argparse\nimport json\nimport pprint\nimport requests\nimport sys\nimport urllib\n\n\napp=Flask(__name__)\n\[email protected]('/')\ndef start():\n return render_template('new_welcome.html')\[email protected]('/result/<term>/<place>')\ndef welcome(term,place):\n ret = sample.query_api(term,place)\n y = json.loads(ret)\n t = list(y.values())\n amount = t[-1]\n lats = [\"\" for p in range(int(amount))]\n longs = [\"\" for p in range(int(amount))]\n resturs_urls = [\"\" for x in range(int(amount))]\n resturs_names = [\"\" for x in range(int(amount))]\n # locations = []\n # print(locations)\n for k in range(int(amount)):\n lats[k]= y[str(k)][\"coordinates\"][\"latitude\"]\n longs[k] = y[str(k)][\"coordinates\"][\"longitude\"]\n # resturs[k]= y[str(k)]['name']\n # print(locations[k])\n # print(t[0])\n amount_double = (int(amount))\n u =0\n while(u <amount_double):\n resturs_urls[u]= y[str(u)]['url']\n u+=1\n # print(\"u: \")\n # print(u)\n # print(amount_double*2)\n for k in range(int(amount)):\n resturs_names[k]= y[str(k)]['name']\n # while(u<(amount_double*2)):\n # resturs[u]= y[str(u)]['name']\n # u+=1\n # resturs[u+1]=y[str(u)]\n # u+=2\n # print(locations)\n # print(lats)\n # print(y)\n # print(y[\"1\"]['name'])\n # print(resturs)\n # print(amount)\n return render_template('index.html', resturs_urls=resturs_urls, resturs_names=resturs_names,ret =y, lats=lats, longs= longs, amount = int(amount))\[email protected]('/res/<term>/<place>')\ndef search_result(term,place):\n ret = sample.query_api(term, place)\n y = json.loads(ret)\n t = list(y.values())\n # amount = y.slice(-1);\n # amount = sorted(y.keys())[-4]\n # amount = sorted(y.keys())\n amount = t[-1]\n # for p in range(int(amount)):\n # lats[p] = \"\"\n # longs[p] = \"\"\n lats =[\"\" for p in range(int(amount))]\n longs =[\"\" for p in range(int(amount))]\n for a in range(int(amount)):\n lats[a] = y[str(a)][\"coordinates\"]['latitude']\n longs[a] = y[str(a)][\"coordinates\"]['longitude']\n a = y['2'][\"coordinates\"]['latitude']\n b = y['2']['coordinates']['longitude']\n\n return render_template('index.html',amount = amount,ret = ret, a= a, b= b, lats= lats,longs=longs)\n# def search_result():\n# ret = sample.query_api(\"turkish\",\"New York\")\n# y = json.loads(ret)\n# t = list(y.values())\n# # amount = y.slice(-1);\n# # amount = sorted(y.keys())[-4]\n# # amount = sorted(y.keys())\n# amount = t[-1]\n# # for p in range(int(amount)):\n# # lats[p] = \"\"\n# # longs[p] = \"\"\n# lats =[\"\" for p in range(int(amount))]\n# longs =[\"\" for p in range(int(amount))]\n# for a in range(int(amount)):\n# lats[a] = y[str(a)][\"coordinates\"]['latitude']\n# longs[a] = y[str(a)][\"coordinates\"]['longitude']\n# a = y['2'][\"coordinates\"]['latitude']\n# b = y['2']['coordinates']['longitude']\n#\n# return render_template('index.html',amount = amount,ret = ret, a= a, b= b, lats= lats,longs=longs)\n\n # return render_template('index.html', ret = ret)\n\n\[email protected]('/search', methods=[\"GET\"])\ndef search():\n term = request.args.get('term')\n loc = request.args.get('place')\n if(loc == \"\"):\n loc = \"new york\"\n if(term == \"\"):\n term = \"indian\"\n return redirect(url_for('welcome',term=term,place=loc))\n\n# @app.route('/search', methods=[\"GET\"])\n# def search():\n# '''If search query is for books, then redirects to book_search.\n# If search query is for books, then redirects to movie_search.'''\n# place = request.args.get(\"h\")\n# query =request.args.get(\"query\").replace(\" \" , \"+\")\n# if(query==\"\"):\n# return redirect(url_for('index'))\n# # if(type == \"Books\"):\n# # return redirect(url_for('book_search', query=query))\n# # else:\n# # return redirect(url_for('movie_search', query=query))\n\n\nif __name__ == '__main__':\n app.debug = True # Set to `False` before release\n app.run()\n"
},
{
"alpha_fraction": 0.6638935208320618,
"alphanum_fraction": 0.6838602423667908,
"avg_line_length": 34.35293960571289,
"blob_id": "62e7b3c240d0b1a3a11bc434a201afebf668aecb",
"content_id": "e840a71d1762dce40c77c7bb22ba281820a9fee5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 601,
"license_type": "no_license",
"max_line_length": 187,
"num_lines": 17,
"path": "/static/script.js",
"repo_name": "shafali731/capital_one_app",
"src_encoding": "UTF-8",
"text": "var x = document.getElementById(\"mapholder\");\n\n// function getLocation() {\n// if (navigator.geolocation) {\n// navigator.geolocation.watchPosition(showPosition);\n// } else {\n// x.innerHTML = \"Geolocation is not supported by this browser.\";\n// }\n// }\n\nfunction showPosition(lat,long) {\n var latlon = lat + \",\" + long;\n\n var img_url = \"https://maps.googleapis.com/maps/api/staticmap?center=\"+latlon+\"&size=400x300&markers=color:red%7Clabel:S%7C\"+lat+\",\"+long+\"&key=AIzaSyBeUnLveEXl8MY27GnXVACU-gnhaGIMIQ8\";\n\n document.getElementById(\"mapholder\").innerHTML = \"<img src='\"+img_url+\"'>\";\n}\n"
}
] | 2 |
PENGsBIT/TechSummary
|
https://github.com/PENGsBIT/TechSummary
|
8aa10a9f8e8a0988073269e7a0119f8870714254
|
117ad89a06d0d794b3732afcbeff86886631c86e
|
9ecca973762154e4fdb479bf66b546831a54370d
|
refs/heads/master
| 2022-04-29T10:55:43.310100 | 2022-04-27T06:57:40 | 2022-04-27T06:57:40 | 195,925,133 | 2 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.9124087691307068,
"alphanum_fraction": 0.9124087691307068,
"avg_line_length": 44.66666793823242,
"blob_id": "3405fa773c2c98d22ca4452cf10414954589fbd4",
"content_id": "e7c17ce0b2753982a2e09d02a7be43aefe162964",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 373,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 3,
"path": "/PythonSummary/并发编程/并发编程.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Python 并发编程\n对于计算密集型程序,多进程并发优于多线程并发。计算密集型程序指的程序的运行时间大部分消耗在CPU的运算处理过程,而硬盘和内存的读写消耗的时间很短;\n相对地,IO密集型程序指的则是程序的运行时间大部分消耗在硬盘和内存的读写上,CPU的运算时间很短。\n"
},
{
"alpha_fraction": 0.5927456617355347,
"alphanum_fraction": 0.6230486631393433,
"avg_line_length": 28.445945739746094,
"blob_id": "c2a86241a24d25fcf590d0470277cd65fee9090b",
"content_id": "49e766baa61be879550f6672a5c1248e37cda7b3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2628,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 74,
"path": "/PythonSummary/并发编程/线程池/ThreadPoolExecutor使用.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : ThreadPoolExecutor使用.py\n@Time : 2020/11/16 14:38\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n# 相比 threading 等模块,该模块通过 submit 返回的是一个 future 对象,\n# 它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值:\n# 主线程可以获取某一个线程(或者任务的)的状态,以及返回值。\n# 当一个线程完成的时候,主线程能够立即知道。\n# 让多线程和多进程的编码接口一致。\n# coding: utf-8\nfrom concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, ALL_COMPLETED, as_completed\nimport time\n\n\ndef spider(page):\n time.sleep(page)\n print \"crawl task{} finished\".format(page)\n return page + 10\n\n\nwith ThreadPoolExecutor(max_workers=5) as t:\n print('========test ThreadPoolExecutor =========')\n # 创建一个最大容纳数量为5的线程池\n task1 = t.submit(spider, 1)\n task2 = t.submit(spider, 2) # 通过submit提交执行的函数到线程池中\n task3 = t.submit(spider, 3)\n\n # 通过done来判断线程是否完成\n print \"task1:{}\".format(task1.done())\n print \"task2:{}\".format(task2.done())\n print\"task3:{}\".format(task3.done())\n\n time.sleep(2.5)\n print \"task1:{}\".format(task1.done())\n print \"task2:{}\".format(task2.done())\n print\"task3:{}\".format(task3.done())\n # 通过result来获取返回值\n print(task1.result())\n\nwith ThreadPoolExecutor(max_workers=5) as t:\n print('========test wait =========')\n all_task = [t.submit(spider, page) for page in range(1, 5)]\n # 当完成第一个任务的时候,就停止等待,继续主线程任务\n wait(all_task, return_when=FIRST_COMPLETED)\n print('finished')\n print(wait(all_task, timeout=2.5))\n\nwith ThreadPoolExecutor(max_workers=5) as t:\n print('========test as_completed =========')\n obj_list = [t.submit(spider, page) for page in range(1, 5)]\n # obj_list = []\n # for page in range(1, 5):\n # obj = t.submit(spider, page)\n # obj_list.append(obj)\n\n for future in as_completed(obj_list):\n data = future.result()\n print(\"main: {}\".format(data))\n\nwith ThreadPoolExecutor(max_workers=5) as t:\n print('========test map =========')\n i = 0\n # def map(self, func, *iterables, **kwargs):\n for result in t.map(spider, [2, 3, 1, 4]):\n print(\"task{}:{}\".format(i, result))\n i += 1"
},
{
"alpha_fraction": 0.5309168696403503,
"alphanum_fraction": 0.5842217206954956,
"avg_line_length": 17.038461685180664,
"blob_id": "a3772a552d68392500cad09bdaafd805366be789",
"content_id": "d66c1b6434b3dc95fa33ca3d0e28c4c867fe5cec",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 601,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 26,
"path": "/PythonSummary/python原理及特性/字典dict/单字典处理/单字典处理.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 单字典处理.py\n@Time : 2020/10/30 15:39\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : 之前写代码很多时候会遇到这么一种情况:在python的字典中只有一个key/value键值对,想要获取其中的这一个元素还要写个for循环获取。\n\"\"\"\n\nd = {}\n# 方法一\nd = {'name': 'haohao'}\n(key, value), = d.items()\n\n# 方法二\nd = {'name': 'haohao'}\nkey = list(d)[0]\nvalue = list(d.values())[0]\n\n# 方法三\nd = {'name': 'haohao'}\nkey, = d\nvalue, = d.values()\n"
},
{
"alpha_fraction": 0.4901960790157318,
"alphanum_fraction": 0.5574229955673218,
"avg_line_length": 16,
"blob_id": "6958461822504acf95ba5d549d6303e759e953c0",
"content_id": "6d98aadc609ae38f4f33f3c09f79c1fded3068a2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 391,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 21,
"path": "/PythonSummary/python原理及特性/py2绑定方法对象和未绑定方法对象/py类方法.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : py类方法.py\n@Time : 2021/4/16 11:42\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n\nclass Foo(object):\n @classmethod # 定义类方法要点1\n def foo(cls): # 定义类方法要点2\n print 'call foo'\n\n\nFoo.foo() # call foo\nFoo().foo() # call foo\n"
},
{
"alpha_fraction": 0.5602150559425354,
"alphanum_fraction": 0.5618279576301575,
"avg_line_length": 36.95918273925781,
"blob_id": "4e86e5c98a0fae84e03274dd7bd650eac614c61b",
"content_id": "96d8f386780368d8283740ae7e22f55a9601a810",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2026,
"license_type": "permissive",
"max_line_length": 128,
"num_lines": 49,
"path": "/JavaSummary/src/List/List删除值/CopyOnWriteArrayListMultiThread.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package List.List删除值;\n\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\npublic class CopyOnWriteArrayListMultiThread {\n //CopyOnWriteArrayList也是一个线程安全的ArrayList,其实现原理在于,每次add,remove等所有的操作都是重新创建一个新的数组,再把引用指向新的数组\n static List<String> list = new CopyOnWriteArrayList<>();\n //防止一个线程修改了list的modCount导致另外一个线程迭代时modCount与该迭代器的expectedModCount不相等。\n public static void main(String[] args) {\n list.add(\"a\");\n list.add(\"b\");\n list.add(\"c\");\n list.add(\"d\");\n System.out.println(\"when process start list is: \"+list);\n new Thread(() -> {\n Iterator<String> iterator = list.iterator();\n\n while (iterator.hasNext()) {\n System.out.println(Thread.currentThread().getName()\n + \":\" + iterator.next());\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n System.out.println(\"when thread\"+ Thread.currentThread().getName()+\"check list modCount in copyonwrite is correct\");\n System.out.println(\"when thread\"+ Thread.currentThread().getName()+\"end list is\"+list);\n }).start();\n\n new Thread(()-> {\n Iterator<String> iterator = list.iterator();\n while (iterator.hasNext()) {\n String element = iterator.next();\n System.out.println(Thread.currentThread().getName()\n + \":\" + element);\n if (element.equals(\"c\")) {\n list.remove(element);\n }\n }\n System.out.println(\"when thread\"+ Thread.currentThread().getName()+\"end list is\"+list);\n }).start();\n\n\n }\n}\n"
},
{
"alpha_fraction": 0.8296173214912415,
"alphanum_fraction": 0.84093177318573,
"avg_line_length": 60.28571319580078,
"blob_id": "a8eb544d35e44bbbafb6661e2f0e8c3522f1466a",
"content_id": "d03d47a045e042b0be2c6a7c71834c1b43d77096",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6069,
"license_type": "permissive",
"max_line_length": 408,
"num_lines": 49,
"path": "/PythonSummary/游戏设计/排队系统/排队系统.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# 百万级排队服务\n## 问题背景\n缓解因开服或者开活动等场景大量玩家涌入而造成的服务器压力,起到保护后台服务的作用,排队系统就可以很好的解决这个问题。\n##技术思路\n* 要实现海量玩家排队的目标,服务应该做成一个分布式的队列,支持横向扩展。参考分段数组的思路,一个队列服务满了应能够自动分配下一个队列服务,各个队列服务间保持有序性,尽可能对用户透明,以http访问的方式方便各个产品接入 \n* 放行用户通过队列的速率应可动态变化,后台服务繁忙的时候放行少量,后台服务不繁忙的时候增大放行。\n## 技术实现\n\n针对海量用户的需求,排队服要设计成可扩容的队列服务。 segment就是排队的服务,多个segment组成一个全局队列,segment1, segment2间的顺序由queuemng维护。用户从router进入,去segment1排队,当segment1排满了就排到segment2。 \n### 各个角色服间的作用:\n#### router\nrouter是由rt_cluster启动,用户通过router 来请求后端的segment服务,对用户透明。\n#### segment\nsegment是由seg_cluster启动,用来存储用户token和排名的队列,用户通过轮询的方式请求segment, 由于查询的频率相对于出队/入队/删除的操作比较频繁,故使用分段数组来实现segment上的queue\n如下图 \n每个seg是一个链表,并记录当前seg的位置偏移pos_tag \n**入队**:在最后的一个seg 插入,时间复杂度O(1) \n**查询**:当前链表上名次加上位置偏移。 pos_current – pos_head + 1 + pos_tag, 时间复杂度O(1) \n**删除**:在当前seg上删除,在向后更新其他seg的pos_tag, 时间复杂度O(m+n), m为seg的个数,n为seg的长度 \n**出队**:向后更新其他seg的pos_tag, 时间复杂度O(m),m为seg的个数 \n#### queuemng\n扩展到分布式,由queuemng管理各个队列服务segment,主要负责服务发现和维护segment链表,以及放行用户。 \n\n**服务发现**:所有的router服务,segment服务都要事先配置queuemng的地址端口,当一个服务连上queuemng 服务后,由queuemng来通知其他在线的服务节点上线,断线也是通过queuemng通知其他服务节点下线 \n\n**维护segment链表**:管理着一堆空闲的segment 和维护由若干个segment 服务串联起来的一个链表,链表的首部为出队的segment, 链表的尾部为入队的segment。 每个router记录当前入队的segment, router收到排队的请求便向入队segment 请求入队操作,每个segment限制了最大人数,如果入队segment没塞满,即返回该segment的serverid和一个唯一标识token ; 当入队segment 上的人数塞满了,该segment拒绝入队操作返回要求用户重新请求,并通知queuemng 分配下一个入队segment,并通知所有router 更新当前入队segment。 segment 上的每个用户设置了超时时间,长时间没收到用户的请求将其从该segment 上删除,当一个segment 上的用户数为零时会被queuemng 回收,待下次分配使用。 \n\n**放行用户**:定时从服务监控后台monitor 拉取机器的监控数据,这个由配置文件 配置具体监控的进程实例,根据监控返回的CPU或者其他指标的数据和配置的放行挡位决定每次放行的用户数 \n#### rt_cluster, seg_cluster\n同理为了建立分布式的系统,我们需要创建多个router和多个segment,那么就需要东西去分配这样的资源。 \nrt_cluster 以cluster.fork 创建子进程router,seg_cluster 以cluster.fork 创建子进程segment,一个rt_cluster/seg_cluster 对应一个配置文件,由rt_cluster/seg_cluster 去分配节点id 和节点的配置,扩容时只需增加一组cluster。\n\n\n## 优化1\n**问题:线上运行在高并发的情况下角色服rt_cluster CPU特别高** \n原因:在使用cluster.fork后会标记该进程是master还是child, 在调用net, dgram 网络模块 listen 时,child会通过管道发送消息给它所在的master,让master去listen,而后将连接rr分发给child,后续由child读写该连接的数据。\n\n这种模式下虽然帮我们做了负载均衡,但是这种方式对于我们使用的短连接不友好,所有router的http连接建立都会经过一次rt_cluster,所以rt_cluster 的CPU才会特别高。 \nrt_cluster 改进: \n**方案A**. 改成长连接,http 开启keep alive, 缓解父进程压力,貌似lbc 的那种七层的模型不允许设置http keep alive,故没采取这种 \n**方案B**. 增多rt_cluster 数量,减少router 数量,减为1个,另特殊处理下只有一个router不使用fork\n\n## 优化2\n**整个系统的队列利用率不足**\n如图,假设一台segment最多排10000人,中间的segment因为超时从队列中删除了,但只要该segment上的存在一个用户,该segment就不会被重新分配利用。 \n\nqueuemng会根据每个segemnt上报的用户数,检查当相邻两个segment的人数小于一个segment最大容量时,将靠后的segment的token合并到靠前的segment, 回收靠后的segment。迁移期间segment上的用户token自动保活,迁移后客户端首次访问靠后的segment,会让客户端重定向到靠前的segment,从而实现用户的迁移,这样就加快回收一个 segment服务,供queuemng再次分配使用\n\n例如:segment2 + segment3 的用户数小于单个segment最大容量10000,queuemng就会向segment2和segment3发送migrate的信号, segment3就开始将用户token打包发送到segment2, 迁移过程中segment3的用户还是在segment3查询,等数据完全迁移过去后,segment3上原本的token查询就会被重定向到segment2, 同时segment3 就可以被回收利用了,提高整个排队系统segment的利用率。\n\n "
},
{
"alpha_fraction": 0.676300585269928,
"alphanum_fraction": 0.7144508957862854,
"avg_line_length": 27.766666412353516,
"blob_id": "0e9fbc41092918aed8d70809bf80568c4d0947bf",
"content_id": "0554e04250fcd08e86336de22bec2e6bddc2b284",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 951,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 30,
"path": "/BatSummary/计时/计时.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Bat批处理文件中用于计时的一个小工具\n[计时](计时.bat)\n```commandline\n@echo off\nset time_begin=%time%\nset /A time_begin_minute=%time_begin:~3,2%\nset /A time_begin_second=%time_begin:~-5,2%\nset /A time_begin_millisec=%time_begin:~-2,2%\n\nping -n 70 -w 1000 127.0.0.1 > nul\nrem your program\n\nset time_end=%time%\nset /A time_end_minute=%time_end:~3,2%\nset /A time_end_second=%time_end:~-5,2%\nset /A time_end_millisec=%time_end:~-2,2%\n\nif %time_end_millisec% lss %time_begin_millisec% set /A time_end_millisec+=100&set /A time_end_second-=1\nif %time_end_second% lss %time_begin_second% set /A time_end_second+=60&set /A time_end_minute-=1\n\nset /A minute=time_end_minute-time_begin_minute\nset /A second=time_end_second-time_begin_second\nset /A millisec=time2_millisec-time1_millisec\n\necho 程序运行开始时间:%time_begin% 结束时间:%time_end%\necho 程序运行时间为%minute%分%second%秒%millisec%毫秒\n\npause & exit\n\n```\n\n\n"
},
{
"alpha_fraction": 0.8115183115005493,
"alphanum_fraction": 0.8254799246788025,
"avg_line_length": 30.88888931274414,
"blob_id": "e1d59e122d0543194e55661818cdafa538e0ff53",
"content_id": "f0bdbef66113eed753f789f89d73a736c9d7bd93",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1213,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 18,
"path": "/JavaSummary/src/cpu使用分析/CPU使用分析.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-CPU使用分析\nCPU使用率与机器负载的关系与区别\n\nload average:系统平均负载是CPU的Load,它所包含的信息不是CPU的使用率状况,而是在一段时间内CPU正在处理以及等待CPU处理的进程数之和的统计信息,也就是CPU使用队列的长度的统计信息。这个数字越小越好。\n## CPU负载和CPU利用率的区别\n* CPU利用率:显示的是程序在运行期间实时占用的CPU百分比 \n\n* CPU负载:显示的是一段时间内正在使用和等待使用CPU的平均任务数。CPU利用率高,并不意味着负载就一定大。 \n \n\n\n## CPU负载和CPU利用率的关系\n正常情况下,cpu 使用率高,load 也会比较高。cpu 使用率低,load 也会比较低。\n\n也有例外情况:\n\n* load average低,利用率高:如果CPU执行的任务数很少,则load average会低,但是这些任务都是CPU密集型,那么利用率就会高。\n* load average高,利用率低:如果CPU执行的任务数很多,则load average会高,但是在任务执行过程中CPU经常空闲(比如等待IO),那么利用率就会低。"
},
{
"alpha_fraction": 0.5166825652122498,
"alphanum_fraction": 0.5548141002655029,
"avg_line_length": 24.609756469726562,
"blob_id": "37c8f79ff1f908ca634861c7ff4c91d21bb93821",
"content_id": "b99e02ad7bec94add66d8fa2ecb14aa40b11d0ce",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1197,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 41,
"path": "/PythonSummary/python原理及特性/python简洁编程总结/List解析/List解析.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : List解析.py\n@Time : 2020/10/12 15:30\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\nif __name__ == '__main__':\n newList = [] # 先定义一个空列表\n for i in range(11):\n newList.append(i * 2) # 将每个元素都乘以2\n print(newList)\n # 列表解析式:\n print([i * 2 for i in range(11)])\n\n project_name = '1'\n data_list = []\n all_data = None\n # 没有使用List解析的时候,使用for in 循环\n for data in data_list:\n if data.get(\"project_name\") and data.get(\"project_name\") == project_name:\n all_data += data\n # 使用了List解析写在一行中:\n all_data += [data for data in data_list if (data.get(\"project_name\") and data.get(\"project_name\") == project_name)]\n\n\n # 没有使用List解析的时候,使用if else 循环\n data_all = []\n for i in xrange(10):\n if i == 0:\n data_all.append(0)\n else:\n data_all.append(1)\n print(data_all)\n # 使用了List解析写在一行中:\n print([data if data == 0 else 1 for data in range(10)])"
},
{
"alpha_fraction": 0.613095223903656,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 23,
"blob_id": "8fa4e2f5973d4dbd08884df823fb8e2ae7ee8a67",
"content_id": "1a617823fb9574320cda1b76b08ede3fe6582a65",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 376,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 14,
"path": "/PythonSummary/网络编程/Socket Learn/Base Demo/BaseClient.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\n\nimport socket # 导入 socket 模块\n\nhost = socket.gethostname() # 获取本地主机名\nport = 12345 # 设置端口号\n\n# 创建 socket 对象\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((host, port))\n s.sendall(b'this message from cient')\n data = s.recv(1024)\n print('Received', repr(data))\n s.close()\n"
},
{
"alpha_fraction": 0.6087689995765686,
"alphanum_fraction": 0.6926644444465637,
"avg_line_length": 36.66666793823242,
"blob_id": "0daab489c526575d1f34794a1f4515286b2eaa9e",
"content_id": "1b141147acdf154a811b314e2cc7b4cce4aa6f76",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3592,
"license_type": "permissive",
"max_line_length": 147,
"num_lines": 63,
"path": "/PythonSummary/python原理及特性/字典dict/Python3 dict优化/Python3 dict优化.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Python3 dict优化\nPython3.6之后,修改了dict的数据结构,内存利用率有一定提升。(有些文章称之为compact dict)\n\n原理如下:\n\n假设字典的数据为:\n \n d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}\n \n旧dict的数据布局如下,每个entry的内容是hash value,key pointer、value pointer,在64bit机器上,占用3 * 8 = 24bytes。查找数据时,根据key计算出hash值,取模,得到entries的下标,获取相应内容(实际还要考虑hash值冲突)\n \n entries = [['--', '--', '--'],\n [-8522787127447073495, 'barry', 'green'],\n ['--', '--', '--'],\n ['--', '--', '--'],\n ['--', '--', '--'],\n [-9092791511155847987, 'timmy', 'red'],\n ['--', '--', '--'],\n [-6480567542315338377, 'guido', 'blue']]\n \n新dict加了一个中间层indices数组,用于记录数据在entries下标。entries的数据布局变为更稠密(中间没有空洞)。查找数据时,也是根据key,计算出hash值,取模,而这里得到的是indices的下标,再通过其值,得到entries的下标,从而获取key对应的数据。\n```\nindices = [None, 1, None, None, None, 0, None, 2]\nentries = [[-9092791511155847987, 'timmy', 'red'],\n [-8522787127447073495, 'barry', 'green'],\n [-6480567542315338377, 'guido', 'blue']]\n\n```\n \nindices数组中的整数,会按照数组的大小使用变长整数(int8、int16、int32、int64)表示。\n当dict元素数量 > 容量的2/3,就会发生扩容。 详见CPython的dictresize()函数。\ndict的容量(即len(indices ))规则:2^n(2的指数倍)。选这个规则,[原因之一](Python3 dict优化.py):根据容量大小计算出mask值的bit位末尾都是1,这样在计算key的hash值,计算放在哪个slot(槽位),可以直接用与运算,而非取模运算,可以加快速度。\nentries 的大小(即len(entries))规则:2/3的dict容量,即len(entries ) == 2/3*len(indices)。\n总结起来,新dict节省内存的原因:\n\n(1)indices数组的整数采用变长整数表示;\n\n(2)entries的大小是dict容量的2/3;\n\n注:\n\n(1)使用del删除dict数据,不会触发缩容;\n\n(2)使用clear()清空dict,会触发缩容;\n## 新dict优点\n* 节省内存。\n* 数据遍历是有序的(即按插入数据的顺序遍历),功能相当于OrderedDict。\n* 数据遍历操作变快,例如:keys(), values(), items()操作。entries数据分布比较密集,中间没有空洞,遍历时,有助于CPU cache预加载。(详见:[Python-Dev] Guarantee ordered dict literals in v3.7?)\n* hash表扩容变快。当entries采用combined table时,使用memcpy()函数进行数据搬移,而memcpy()使用了4字节或8字节的指令批量进行数据搬移,比较快。而旧dict,在数据搬移时,需要过滤value为NULL的数据。(详见:glibc--memcpy源码分析)\n* 使用内存比较少,有助于减少内存碎片。 \n\n关于新dict的详细介绍,可以看下面的文章:\n\n\n[[Python-Dev] More compact dictionaries with faster iteration](https://mail.python.org/pipermail/python-dev/2012-December/123028.html)\n\n[[Python-Dev] Guarantee ordered dict literals in v3.7?](https://mail.python.org/pipermail/python-dev/2017-December/151283.html)\n\n[python3.7源码分析-字典](https://blog.csdn.net/qq_33339479/article/details/90446988)\n\n新dict的python实现代码:\n\n[PROOF-OF-CONCEPT FOR A MORE SPACE-EFFICIENT, FASTER-LOOPING DICTIONARY (PYTHON RECIPE)](https://code.activestate.com/recipes/578375/)"
},
{
"alpha_fraction": 0.42561984062194824,
"alphanum_fraction": 0.4655647277832031,
"avg_line_length": 20.382352828979492,
"blob_id": "c23ced2b46d9e50b37fb553a61ae3c7a62bbf8db",
"content_id": "5155777f6035c870b02a07be262c3b9995a44b1e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 798,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 34,
"path": "/PythonSummary/python原理及特性/python简洁编程总结/if条件判断/if条件判断.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : if条件判断.py\n@Time : 2020/10/12 16:05\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nif __name__ == '__main__':\n gid = []\n service = []\n if ('1' in gid) or ('2' in gid):\n if ('a' in service) or ('b' in service):\n print True\n\n # 代码改进后\n # 同理 set(gid).intersection(set(['1', '2'])),检查两个set 中相同的元素\n # 适用于全是or的情况\n gid_set = set(gid) & set(['1', '2'])\n service_set = set(service) & set(['a', 'b'])\n if gid_set and service:\n print True\n\n r = \"\"\n if r == 'a' or r == 'b':\n print\n \"or 判断\"\n\n if r in ['a', 'b']:\n print\n \"使用集合\""
},
{
"alpha_fraction": 0.6705320477485657,
"alphanum_fraction": 0.6793997287750244,
"avg_line_length": 28.918367385864258,
"blob_id": "d57a45845191464c3e4df858fc80ddaa83c3b293",
"content_id": "0686180e6444f1964e264908facf1b73d99dc3fc",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2134,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 49,
"path": "/PythonSummary/网络编程/Socket Learn/Multiple Client Connections/DefaultSelector Demo/DefaultSelector Demo.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "import selectors\nimport socket\n\nsel = selectors.DefaultSelector()\n\n\ndef accept(sock, mask):\n conn, addr = sock.accept() # Should be ready\n print('accepted', conn, 'from', addr)\n # 设置socket的阻塞或非阻塞模式\n # 阻塞模式下当试图对该文件描述符进行读写时,如果当时没有东西可读,或者暂时不可写,程序就进入等待状态,直到有东西可读或者可写为止\n # 非阻塞模式下如果没有东西可读,或者不可写,读写函数马上返回,而不会等待\n conn.setblocking(False)\n # 对描述符进行注册,也就是对该描述符的EVENT_READ事件进行监听,当又READ事件通知时,调用回调函数read\n # selectors库提供了两个监听事件:EVENT_READ和EVENT_WRITE\n sel.register(conn, selectors.EVENT_READ, read)\n\n\ndef read(conn, mask):\n data = conn.recv(1000) # Should be ready\n if data:\n print('echoing', repr(data), 'to', conn)\n conn.send(data) # Hope it won't block\n else:\n print('closing', conn)\n # 注销描述符\n sel.unregister(conn)\n conn.close()\n\n\nsock = socket.socket()\nsock.bind(('localhost', 1234))\nsock.listen(100)\nsock.setblocking(False)\nsel.register(sock, selectors.EVENT_READ, accept)\n\nwhile True:\n # select()函数是实现I/O异步的关键,等待,直到一些已注册的文件对象准备就绪,或者超时。\n # 如果timeout>0,则指定最大等待时间,以秒为单位,如果超时没有,则调用将阻塞,\n # 直到被监视的文件对象准备就绪。如果timeout< 0,调用将不会阻塞,并将报告当前就绪的文件对象。\n # 该函数返回一个元组(key, events)\n # key为class selectors.SelectorKey对象,SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data'])\n # fileobj为注册的文件对象\n # fd为文件描述符\n # data为与文件对象相关联的自定义数据,如上面的回调函数\n events = sel.select()\n for key, mask in events:\n callback = key.data\n callback(key.fileobj, mask)\n"
},
{
"alpha_fraction": 0.3243243098258972,
"alphanum_fraction": 0.44144144654273987,
"avg_line_length": 29.272727966308594,
"blob_id": "c986a8ba956d9925fba4c07d62784c42266ee5ab",
"content_id": "b51cf2fd6f8b6b216122095e5c1f373689919bc3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 391,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 11,
"path": "/PythonSummary/python原理及特性/__slots__限制实例的属性/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "if __name__ == '__main__':\n list = [3, 5, 2, 6, 7]\n for index, i in enumerate(list):\n print(\"%d,%s\" % (index, i))\n a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n a[1:6:-1]\n # print[]\n # step=-1,决定了从右往左取值,而start_index=1到end_index=6决定了从左往右取值,两者矛盾\n a[2+1:3*2:7%3]\n # >>> [3, 4, 5]\n # 即:a[2+1:3*2:7%3] = a[3:6:1]\n"
},
{
"alpha_fraction": 0.822263777256012,
"alphanum_fraction": 0.822263777256012,
"avg_line_length": 27.83783721923828,
"blob_id": "381a879d529eff939eed79296875984bb114de15",
"content_id": "acf9b13ee64f8172896e47747a35e7d768c80167",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2217,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 37,
"path": "/JavaSummary/out/production/JavaSummary/设计模式DesignPatterns/proxy/proxy.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-设计模式DesignPatterns.proxy\n总结静态代理、动态代理\n一种软件设计模式,目的地希望能做到代码重用\n## 静态代理\n静态代理其实就是在程序运行之前,提前写好被代理方法的代理类,编译后运行。 \n静态代理需要针对被代理的方法提前写好代理类,如果被代理的方法非常多则需要编写很多代码\n\n## 动态代理:JDK\nJDK中生成代理对象主要涉及的类有\n\n* java.lang.reflect Proxy,主要方法为\n```\nstatic Object newProxyInstance(ClassLoader loader, //指定当前目标对象使用类加载器\n\n Class<?>[] interfaces, //目标对象实现的接口的类型\n InvocationHandler h //事件处理器\n) \n//返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序。\n```\n* java.lang.reflect InvocationHandler,主要方法为\n```\n@Override\nObject invoke(Object 设计模式DesignPatterns.proxy, Method method, Object[] args) \n// 在代理实例上处理方法调用并返回结果。\n```\n## 动态代理:CGlib\ncglib (Code Generation Library )是一个第三方代码生成类库,运行时在内存中动态生成一个子类对象从而实现对目标对象功能的扩展。\n* JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。如果想代理没有实现接口的类,就可以使用CGLIB实现。\n* CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接口。\n它广泛的被许多AOP的框架使用,例如Spring AOP和dynaop,为他们提供方法的interception(拦截)。 \n* CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。\n不鼓励直接使用ASM,因为它需要你对JVM内部结构包括class文件的格式和指令集都很熟悉。\n\n## 静态代理与动态代理的区别主要在:\n静态代理在编译时就已经实现,编译完成后代理类是一个实际的class文件\n\n动态代理是在运行时动态生成的,即编译完成后没有实际的class文件,而是在运行时动态生成类字节码,并加载到JVM中\n\n\n"
},
{
"alpha_fraction": 0.824867308139801,
"alphanum_fraction": 0.8369977474212646,
"avg_line_length": 36.628570556640625,
"blob_id": "e9a86773f5ae27da065cc816a2e105a6a7b6c9c4",
"content_id": "85b1208d86a52d3eb9bbb0dcc3214c3c7c6a1894",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2643,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 35,
"path": "/PythonSummary/网络编程/Socket Learn/Multiple Client Connections/python select模块详解.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Learn Python select summary\n**select模块专注于I/O多路复用,提供了select poll epoll三个方法(其中后两个在Linux中可用,windows仅支持select)**\n##select方法\nselect()时:内核监听哪些文件描述符(最多监听1024个fd)的哪些事件,当没有文件描述符事件发生时,进程被阻塞;当一个或者多个文件描述符事件发生时,进程被唤醒。\n1.上下文切换转换为内核态\n2.将fd从用户空间复制到内核空间\n3.内核遍历所有fd,查看其对应事件是否发生\n4.如果没发生,将进程阻塞,当设备驱动产生中断或者timeout时间后,将进程唤醒,再次进行遍历\n5.返回遍历后的fd\n6.将fd从内核空间复制到用户空间\n(fd:file descriptor 文件描述符:内核(kernel)利用文件描述符(file descriptor)来访问文件。文件描述符是非负整数。)\n\n###方法详解\nselect.select模块其实主要就是要理解它的参数, 以及其三个返回值.\n**fd_r_list, fd_w_list, fd_e_list = select.select(rlist, wlist, xlist, [timeout])**\n\n参数: 可接受四个参数(前三个必须)\nrlist: wait until ready for reading\nwlist: wait until ready for writing\nxlist: wait for an “exceptional condition”\ntimeout: 超时时间\n\n返回值:三个列表\nselect方法用来监视文件描述符(当文件描述符条件不满足时,select会阻塞),当某个文件描述符状态改变后,会返回三个列表\n* 当参数1 序列中的fd满足“可读”条件时,则获取发生变化的fd并添加到fd_r_list中\n* 当参数2 序列中含有fd时,则将该序列中所有的fd添加到 fd_w_list中\n* 当参数3 序列中的fd发生错误时,则将该发生错误的fd添加到 fd_e_list中\n* 当超时时间为空,则select会一直阻塞,直到监听的句柄发生变化,当超时时间 = n(正整数)时,那么如果监听的句柄均无任何变化,则select会阻塞n秒,之后返回三个空列表,如果监听的句柄有变化,则直接执行。\n\n##select方法\nepoll很好的改进了select:\n\n1.epoll的解决方案在epoll_ctl函数中。每次注册新的事件到epoll句柄中时,会把所有的fd拷贝进内核,而不是在epoll_wait的时候重复拷贝。epoll保证了每个fd在整个过程中只会拷贝一次。\n2.epoll会在epoll_ctl时把指定的fd遍历一遍(这一遍必不可少)并为每个fd指定一个回调函数,当设备就绪,唤醒等待队列上的等待者时,就会调用这个回调函数,而这个回调函数会把就绪的fd加入一个就绪链表。epoll_wait的工作实际上就是在这个就绪链表中查看有没有就绪的fd\n3.epoll对文件描述符没有额外限制\n\n\n"
},
{
"alpha_fraction": 0.5556514263153076,
"alphanum_fraction": 0.566868007183075,
"avg_line_length": 32.11428451538086,
"blob_id": "8dc4a6baf27f28ff37bf13f7a51dc55efbd1e0b8",
"content_id": "d94757489c384322612b0bf15ce89540664ee1f1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1189,
"license_type": "permissive",
"max_line_length": 108,
"num_lines": 35,
"path": "/JavaSummary/src/设计模式DesignPatterns/proxy/DynamicProxy.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 设计模式DesignPatterns.proxy;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Proxy;\n\n/**\n * @program: TechSummary\n * @author: zpc\n * @create: 2019-07-10 21:47\n **/\n\npublic class DynamicProxy {\n private Target target;\n\n public DynamicProxy(Target target) {\n this.target = target;\n }\n\n // 为目标对象生成代理对象\n public Object getProxyInstance() {\n return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),\n new InvocationHandler() {\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n System.out.println(\"method:\" + method.getName());\n System.out.println(\"args:\" + args[0].getClass().getName());\n System.out.println(\"Before invoke method...\");\n Object object = method.invoke(target, args);\n System.out.println(\"After invoke method...\");\n return object;\n }\n });\n }\n}\n"
},
{
"alpha_fraction": 0.5636574029922485,
"alphanum_fraction": 0.5804398059844971,
"avg_line_length": 28.288135528564453,
"blob_id": "d36a7f0c060d50f68d96bc85737ad7a05549fc3a",
"content_id": "34638172cf0841c6dc7aa07a3aa4ac8b2238ff39",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2350,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 59,
"path": "/PythonSummary/网络编程/Socket Learn/Multiple Client Connections/SelectAndEpollDemo/Epoll Server.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport socket\nimport select\n\ns = socket.socket()\ns.bind(('192.168.12.172', 9999))\ns.listen(5)\n\n# 创建一个epoll对象\nepollObj = select.epoll()\n# 在服务端socket上面注册对读事件(event)的关注。一个读event随时会触发服务端socket去接收一个socket连接\nepollObj.register(s, select.EPOLLIN)\n\nconnections = {}\n\nwhile True:\n # 查询epoll对象,看是否有任何关注的event被触发。参数“1”表示,我们会等待1秒来看是否有event发生。\n # 如果有任何我们感兴趣的event发生在这次查询之前,这个查询就会带着这些event的列表立即返回,返回一个元组列表[(fd1, events1), (...)]\n events = epollObj.poll(1)\n\n # event作为一个序列(fileno,event code)的元组返回。fileno是文件描述符的代名词,始终是一个整数。\n for fd, event in events:\n help(event)\n # 如果是服务端产生event,表示有一个新的连接进来\n if fd == s.fileno():\n # 创建一个新套接字,并且连接到对应到客户端(ip:port)\n conn, addr = s.accept()\n\n print('client connected: ', addr)\n # 将上述新增服务端套接字注册到epoll_obj对象中\n epollObj.register(conn, select.EPOLLIN)\n connections[conn.fileno()] = conn\n print(\"connections: {0}\".format(connections))\n\n print(\"Starting receving data...\")\n\n # 将客户端发送的数据接收进来\n msg = conn.recv(200)\n\n # 给客户端响应\n conn.sendall('Server OK'.encode())\n else:\n # 当fd不是上面声明的服务端套接字s的时候,执行以下操作\n try:\n # 说明该客户端是已经来过的,则直接操作数据\n fd_obj = connections[fd] # 获取文件描述符指向的套接字对象\n msg = fd_obj.recv(200)\n fd_obj.sendall('Client OK'.encode())\n except BrokenPipeError:\n print(\"ending up ....\")\n # 注销对此socket连接的关注\n epollObj.unregister(fd)\n # 关闭socket连接\n connections[fd].close()\n del connections[fd]\ns.close()\nepollObj.close()\n"
},
{
"alpha_fraction": 0.682748556137085,
"alphanum_fraction": 0.6959064602851868,
"avg_line_length": 23.464284896850586,
"blob_id": "72f34ad4f4f6b4c4c824ebc8fc453d3a69a48648",
"content_id": "b0f47e111122a863e3d9158d525d175c296b346b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1026,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 28,
"path": "/PythonSummary/python原理及特性/__slots__限制实例的属性/__slots__限制实例的属性.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# __slots__限制实例的属性\n\nPython允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性:\n例如:\n```\nclass Student(object):\n __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称\ns = Student() # 创建新的实例\n\n```\n```\ns.name = 'Michael' # 绑定属性'name'\ns.age = 25 # 绑定属性'age'\ns.score = 99 # 绑定属性'score'\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'Student' object has no attribute 'score'\n```\n由于'score'没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。\n使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:\n```\nclass GraduateStudent(Student):\n pass\n\ng = GraduateStudent()\ng.score = 9999\n```\n除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。"
},
{
"alpha_fraction": 0.5120457410812378,
"alphanum_fraction": 0.5365455150604248,
"avg_line_length": 22.11320686340332,
"blob_id": "39f23db810fcdf2fb918352acd19a938b63a9a72",
"content_id": "d08f2e36eaee29931bff458f958a9f307e698a5b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2681,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 106,
"path": "/JavaSummary/src/ThreadLocal/ThreadLocal示例.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package ThreadLocal;\n\n/**\n * @Program: JavaSummary\n * @Author: zhoupengcheng03\n * @Package: ThreadLocal\n * @ClassName: ThreadLocal\n * @Description:\n * @Create: 2022-02-14 11:50\n **/\n\npublic class ThreadLocal示例 {\n\n /**\n * 运行入口\n *\n * @param args 运行参数\n */\n public static void main(String[] args) {\n safeDeposit();\n notSafeDeposit();\n }\n\n /**\n * 线程安全的存款\n */\n private static void safeDeposit() {\n SafeBank bank = new SafeBank();\n Thread thread1 = new Thread(() -> bank.deposit(200), \"张成瑶\");\n Thread thread2 = new Thread(() -> bank.deposit(200), \"马云\");\n Thread thread3 = new Thread(() -> bank.deposit(500), \"马化腾\");\n thread1.start();\n thread2.start();\n thread3.start();\n }\n\n /**\n * 非线程安全的存款\n */\n private static void notSafeDeposit() {\n NotSafeBank bank = new NotSafeBank();\n Thread thread1 = new Thread(() -> bank.deposit(200), \"张成瑶\");\n Thread thread2 = new Thread(() -> bank.deposit(200), \"马云\");\n Thread thread3 = new Thread(() -> bank.deposit(500), \"马化腾\");\n thread1.start();\n thread2.start();\n thread3.start();\n }\n\n}\n\n/**\n * 非线程安全的银行\n */\nclass NotSafeBank {\n\n /**\n * 当前余额\n */\n private int balance = 1000;\n\n /**\n * 存款\n *\n * @param money 存款金额\n */\n public void deposit(int money) {\n String threadName = Thread.currentThread().getName();\n System.out.println(threadName + \" -> 当前账户余额为:\" + this.balance);\n this.balance += money;\n System.out.println(threadName + \" -> 存入 \" + money + \" 后,当前账户余额为:\" + this.balance);\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}\n\n/**\n * 线程安全的银行\n */\nclass SafeBank {\n\n /**\n * 当前余额\n */\n private ThreadLocal<Integer> balance = ThreadLocal.withInitial(() -> 1000);\n\n /**\n * 存款\n *\n * @param money 存款金额\n */\n public void deposit(int money) {\n String threadName = Thread.currentThread().getName();\n System.out.println(threadName + \" -> 当前账户余额为:\" + this.balance.get());\n this.balance.set(this.balance.get() + money);\n System.out.println(threadName + \" -> 存入 \" + money + \" 后,当前账户余额为:\" + this.balance.get());\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n}"
},
{
"alpha_fraction": 0.5507766008377075,
"alphanum_fraction": 0.5675029754638672,
"avg_line_length": 25.15625,
"blob_id": "aa3562bfc39ef40ce498e90caa49c0d5db4997a3",
"content_id": "0049cf0995ad02f2867480d7bda1e27e208dc9e1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 991,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 32,
"path": "/PythonSummary/网络编程/Socket Learn/Base Demo/NonBlocingServer.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "import socket\n\nsk = socket.socket()\n\nsk.bind(('127.0.0.1', 8080))\n# 不阻塞,即将socket当中的所有需要阻塞的方法都改变成非阻塞\nsk.setblocking(False)\nsk.listen()\n# 用来存储所有来请求server端的conn\nconnectList = []\n# 用来存储所有已经断开与server端连接的conn\nconnDisconnect = []\nwhile True:\n # 不阻塞,但是没人连接就返回error\n try:\n conn, addr = sk.accept()\n print('connect success', addr)\n connectList.append(conn)\n except BlockingIOError:\n for conn in connectList:\n try:\n msg = conn.recv(1024) # 不阻塞,但是没有消息会报错\n if msg == b'':\n connDisconnect.append(conn)\n continue\n print(msg)\n conn.send(b'bye')\n except BlockingIOError:\n pass\n for conn in connDisconnect:\n connectList.remove(conn)\n connDisconnect.clear()\n"
},
{
"alpha_fraction": 0.5375795960426331,
"alphanum_fraction": 0.571974515914917,
"avg_line_length": 19.657894134521484,
"blob_id": "c2ad290e9adea2e584117fbc03cfcd96070b6ded",
"content_id": "77d42637fb3c4831db1af386e0fc08637ca31d4a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 801,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 38,
"path": "/PythonSummary/并发编程/进程池/异步提交.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 异步提交.py\n@Time : 2020/11/20 11:31\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n# from multiprocessing import Process,Pool\nfrom concurrent.futures import ProcessPoolExecutor\nimport time, random, os\n\n\ndef task(name, n):\n print('%s is task %s' % (name, os.getpid()))\n time.sleep(1)\n return n ** 2\n\n\nif __name__ == '__main__':\n p = ProcessPoolExecutor(2)\n objs = []\n start = time.time()\n for i in range(5):\n obj = p.submit(task, 'num: %s' % i, i) # 异步调用\n objs.append(obj)\n\n p.shutdown(wait=True)\n print('main', os.getpid())\n for obj in objs:\n print(obj.result())\n\n stop = time.time()\n print(stop - start)\n"
},
{
"alpha_fraction": 0.5692307949066162,
"alphanum_fraction": 0.6346153616905212,
"avg_line_length": 19,
"blob_id": "649f4a3f10102a737fa727e6b9970c779f7e515a",
"content_id": "a5da4d6574b0944087166af5b4e7886ed5644b63",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 260,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 13,
"path": "/PythonSummary/网络编程/Socket Learn/Base Demo/NonBlockingClient.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "import socket\nimport time\nfrom threading import Thread\ndef func():\n sk = socket.socket()\n sk.connect(('127.0.0.1',8080))\n sk.send(b'hello')\n time.sleep(1)\n print(sk.recv(1024))\n sk.close()\n\nfor i in range(20):\n Thread(target=func).start()\n"
},
{
"alpha_fraction": 0.8276422619819641,
"alphanum_fraction": 0.8292682766914368,
"avg_line_length": 35.117645263671875,
"blob_id": "74783a8a51626a1a6602ace3925b28f137c3c0fc",
"content_id": "05d1b7e84a35c418ccf49b185356f3c3ae4a36b5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1719,
"license_type": "permissive",
"max_line_length": 143,
"num_lines": 17,
"path": "/PythonSummary/设计模式/黑板模式/黑板模式.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#黑板模式\n黑板模式是观察者模式的扩展。允许消息的读写同时进行,广泛地交互消息。 \n黑板模式允许多个消息读写者同时存在,消息的生产者和消费者完全分开,两者在空间和时间上可以解耦,并且互不干扰。 \n\n黑板模式是消息的广播,主要解决消息的生产者和消费者之间的耦合问题,核心是消息存储(黑板),它存储所有消息,并可以随时被读取。当然,消息的写入者也可以变身为消息的阅读者,读写者在时间上解耦。对于这些消息,消费者只需要关注特定消息,不处理与自己不相关的消息,这一点通常通过过滤器来实现。 \n## 黑板架构风格\n基于上面的描述,我们可以看到黑板有几个功能:\n* 记录:每个人可以写下自己的看法。\n* 更新:调整已有的看法。\n* 删除:删除对于过时的,或者错误的看法。\n* 读取:黑板上的内容谁都能自由阅读。 \n\n所以从本质上来说,黑板就是这样一个共享数据的结构,它对于多个系统间通信是很有帮助的。它提供一种数据传递的方式,有助于系统的封装和解耦合。\n\n对于各个子系统而言,只需要把自己的运算的结果数据记录在黑板上,至于这个数据谁会去用,并不需要关心。 \n反过来也是一样,对于自己的运算时需要用到的数据,可以从黑板上去获取,至于这个数据是谁提供的,也不需要关心。 \n只要这个数据在黑板上,就够可以认为是合法数据,这就提供的了一种灵活性,各个子系统的设计也会相对独立。 "
},
{
"alpha_fraction": 0.5836669206619263,
"alphanum_fraction": 0.6148918867111206,
"avg_line_length": 31.86842155456543,
"blob_id": "347d32668cc27822efbb10c88e9965a5ce7205b6",
"content_id": "1b921f1591d2cc80bb6b74051d8420001df7ed5f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1425,
"license_type": "permissive",
"max_line_length": 123,
"num_lines": 38,
"path": "/JavaSummary/src/时间戳TimeStamp/当前时间戳和时间戳转换.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 时间戳TimeStamp;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Date;\n\npublic class 当前时间戳和时间戳转换 {\n public static void main(String[] args) {\n // 精确到毫秒\n // 获取当前时间戳\n System.out.println(System.currentTimeMillis());\n System.out.println(Calendar.getInstance().getTimeInMillis());\n System.out.println(new Date().getTime());\n long time = new Date().getTime();\n\n // 精确到秒\n // 获取当前时间戳\n System.out.println(System.currentTimeMillis() / 1000);\n System.out.println(Calendar.getInstance().getTimeInMillis() / 1000);\n System.out.println(new Date().getTime() / 1000);\n\n // 精确到毫秒\n // 获取指定格式的时间\n SimpleDateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss:SSS\");\n // 输出字符串\n System.out.println(df.format(new Date()));\n // 获取指定时间Date对象,参数是时间戳,只能精确到秒\n System.out.println(new Date(1510369871));\n df.getCalendar();\n // 获取指定时间的时间戳\n try {\n System.out.println(new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss:SSS\").parse(\"2017/11/11 11:11:11:111\").getTime());\n } catch (ParseException e) {\n e.printStackTrace();\n }\n }\n}\n"
},
{
"alpha_fraction": 0.7402439117431641,
"alphanum_fraction": 0.7402439117431641,
"avg_line_length": 40,
"blob_id": "7dfadaa130abd4991f4bf2ae045ecb444931e979",
"content_id": "2ecec230287785cc454df7f340e79dd041e57708",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1110,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 20,
"path": "/JavaSummary/src/动态代理/JDK动态代理/Main.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 动态代理.JDK动态代理;\n\nimport java.lang.reflect.InvocationHandler;\nimport java.lang.reflect.Proxy;\n\npublic class Main {\n public static void main(String[] args) {\n // 指明一个类加载器,要操作class文件,怎么少得了类加载器呢\n ClassLoader classLoader = Main.class.getClassLoader();\n // 为代理对象指定要是实现哪些接口,这里我们要为UserServiceImpl这个目标对象创建动态代理,所以需要为代理对象指定实现UserService接口\n Class[] classes = new Class[]{UserService.class};\n // 初始化一个InvocationHandler,并初始化InvocationHandler中的目标对象\n InvocationHandler invocationHandler = new UserServiceInvocationHandler(new UserServiceImpl());\n // 创建动态代理\n UserService userService = (UserService) Proxy.newProxyInstance(classLoader, classes, invocationHandler);\n // 执行代理对象的方法,通过观察控制台的结果,判断我们是否对目标对象(UserServiceImpl)的方法进行了增强\n userService.insert();\n\n }\n}\n"
},
{
"alpha_fraction": 0.4995977580547333,
"alphanum_fraction": 0.526146411895752,
"avg_line_length": 19.04838752746582,
"blob_id": "d1097db85026b5f30d7b8dd3c402d377f73fc761",
"content_id": "3878d83177f45b115b1737402147d1236825e4f5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1457,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 62,
"path": "/JavaSummary/src/凸包问题的五种解法/Point.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 凸包问题的五种解法;/**\n * @program: javatest\n * @author: zpc\n * @create: 2019-09-16 15:29\n **/\n\n/**\n * @Author: zpc\n * @Description:\n * @Create: 2019-09-16 15:29\n **/\nclass Point {\n\n // 定义点的x,y坐标,之所以是int类型,是为了日后可以在计算机屏幕上进行可视化。\n public int x;\n public int y;\n\n // x,y的get方法\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n // 定义点到屏幕边缘的距离\n private static double PADDING = 20;\n // 点在屏幕中的范围\n private static double POINT_RANGE = (800 - PADDING * 2);\n\n // 默认构造方法,产生随机点\n public Point() {\n this.x = (int) ((Math.random() * POINT_RANGE) + PADDING);\n this.y = (int) ((Math.random() * POINT_RANGE) + PADDING);\n }\n\n // 带参构造方法,可以实现手动输入固定点\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n // 覆写hashCode()和equals()方法,实现比较和Hash\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + x;\n result = prime * result + y;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n Point other = (Point) obj;\n if ((x == other.x) && (y == other.y))\n return true;\n\n return false;\n }\n\n}\n"
},
{
"alpha_fraction": 0.653813898563385,
"alphanum_fraction": 0.6554903388023376,
"avg_line_length": 26.76744270324707,
"blob_id": "0d64c3b85154785a6e10ed93811343251f6b04f7",
"content_id": "8e62d34cee94211062b5e75af61bdaedb1e42ad0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1619,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 43,
"path": "/PythonSummary/游戏设计/Reload热更新/function code 热更时的陷阱.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# function code 热更时的陷阱\n\n## reload\nfunction code做的事情,可以总结为:\n1. 将希望reload的模块,从 sys.modules 中 pop 出去\n\n2. 对于每一个希望reload的模块,调用 __import__ 函数重新加载\n\n这里就存在了上文[import机制](import.md)阐述的情况:当执行 from A.B import C 这类 import_from 语句时,不会真的发生重新加载的情况! \n因为 function code 热更时,并不会创建新的Module,而是在原有的Module上执行reload操作。 \n于是 A 模块里已经有 B 模块的引用,B 模块里也有 C 模块的引用,所以执行 from A.B import C 时,不会真正的重新加载C模块\n\n## 修正\n在热更新前,首先将模块间的互相引用删除,这样 import_from 就不会无辜的忽略掉某个模块了: \n```\ndef remove_old_modules(module_names):\n for name in module_names:\n tmp = []\n m = sys.modules[name]\n for k, v in m.__dict__.iteritems():\n if inspect.ismodule(v):\n tmp.append(k)\n\n for k in tmp:\n del m.__dict__[k]\n```\n在load一个模块时,显式的reload其引用的所有其他模块\n```\nclass finder(object):\n\tdef setup_old_module(self, name):\n\t\told_module = self.get_old_module(name)\n\t\tif not old_module:\n\t\t\treturn\n\n\t\told_module.__dict__.pop('_reload_all', None)\n\t\tsys.modules[name] = old_module # for imp.load_module to reload the module\n\n\t\tfor k, v in old_module.__dict__.iteritems():\n\t\t\tif inspect.ismodule(v):\n\t\t\t\tname = getattr(v, \"__name__\", \"\")\n\t\t\t\tif name not in sys.modules:\n\t\t\t\t\tself.get_module(name, None)ne)\n```"
},
{
"alpha_fraction": 0.5851590037345886,
"alphanum_fraction": 0.5865724086761475,
"avg_line_length": 30.422222137451172,
"blob_id": "f49873aedfeeb9fd47bce68aec624e4c98bd15aa",
"content_id": "ddcf289d8a7e2418a66d01f9ee49e48a24136f32",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1423,
"license_type": "permissive",
"max_line_length": 91,
"num_lines": 45,
"path": "/JavaSummary/src/Optional/useOptional.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package Optional;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\npublic class useOptional {\n public static void main(String[] args) throws Exception {\n Optional<Integer> a;\n }\n\n public void getUserID(int id) {\n User user = new User(\"a\", 3);\n user= user.getUserById(id);\n //basic\n if (user != null) {\n String username = user.getUserName();\n System.out.println(\"Username is: \" + username); // 使用 username\n }\n //use isPresent()\n Optional<User> userOptional = Optional.ofNullable(user.getUserById(id));\n if (userOptional.isPresent()) {\n String username = userOptional.get().getUserName();\n System.out.println(\"Username is: \" + username); // 使用 username\n }\n //optimize\n userOptional = Optional.ofNullable(user.getUserById(id));\n userOptional.ifPresent(u -> System.out.println(\"Username is: \" + u.getUserName()));\n\n //use .orElse()\n user = Optional\n .ofNullable(user.getUserById(id))\n .orElse(new User(\"Unknown\",0 ));\n\n System.out.println(\"Username is: \" + user.getUserName());\n\n //map\n Optional<String> username = Optional\n .ofNullable(user.getUserById(id))\n .map(element -> element.getUserName());\n\n System.out.println(\"Username is: \" + username.orElse(\"Unknown\"));\n\n }\n\n}\n\n"
},
{
"alpha_fraction": 0.8500000238418579,
"alphanum_fraction": 0.8500000238418579,
"avg_line_length": 46,
"blob_id": "e76167286d7f97a40be71b92441045e37a4afae2",
"content_id": "a7a18527ad0ab37af69bf8b8d631877275fc5cea",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 298,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 3,
"path": "/PythonSummary/python原理及特性/__import__的事项/__import__的事项.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# __import__的事项\n__import__ 可以直接从sys.path中动态加载模块,因此当无法正确加载的时候检查sys.path中是否包含正确的路径\n特别是:多进程并发的时候主/子进程各自有各自的path,所以需要在各自的进程中sys,path.append相应的路径"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 14,
"blob_id": "105f25e646f3e5fb0096af56d26ad264cd73a3bf",
"content_id": "31d01872e85e71b84b67c8787446e992dd603f33",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 28,
"license_type": "permissive",
"max_line_length": 14,
"num_lines": 1,
"path": "/PythonSummary/python原理及特性/python简洁编程总结/PythonConciseCode.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Python 简洁编程总结\n\n"
},
{
"alpha_fraction": 0.7081581354141235,
"alphanum_fraction": 0.7544154524803162,
"avg_line_length": 27.95121955871582,
"blob_id": "f79409badcdc5ef874adec589a01bce59fdb2dfc",
"content_id": "38cd57b865df5f7371717e8897dd099ea331d8c7",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5578,
"license_type": "permissive",
"max_line_length": 137,
"num_lines": 82,
"path": "/JavaSummary/out/production/JavaSummary/凸包问题的五种解法/凸包问题的五种解法.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-凸包问题的五种解法\n什么是凸包?\n假设平面上有p0~p3共4个点,过某些点作一个多边形,使这个多边形能把所有点都“包”起来。\n当这个多边形是凸多边形的时候,我们就叫它“凸包”。 \np0-----p1 \n| p2 | \np3------p4 \n\n## Melkman算法\n1. 问题描述 \n给定一组二维坐标的集合,求从这个集合中找出这些二维坐标的外围边界。经过查询,确定了这是一个二维凸包的问题,属于计算几何的范畴。\n\n2. Melkman 算法 \n \n\n3. 算法描述 \n \n\n\n## Graham扫描法\n时间复杂度:O(n㏒n) \n思路:Graham扫描的思想和Jarris步进法类似,也是先找到凸包上的一个点,\n然后从那个点开始按逆时针方向逐个找凸包上的点,但它不是利用夹角 \n \n步骤:\n\n1、把所有点放在二维坐标系中,则纵坐标最小的点一定是凸包上的点,如图中的P0。 \n2、把所有点的坐标平移一下,使 P0 作为原点,如上图。 \n3、计算各个点相对于 P0 的幅角 α ,按从小到大的顺序对各个点排序。当 α 相同时,距离 P0 比较近的排在前面。例如上图得到的结果为 P1,P2,P3,P4,P5,P6,P7,P8。我们由几何知识可以知道,结果中第一个点 P1 和最后一个点 P8 一定是凸包上的点。 \n(以上是准备步骤,以下开始求凸包) \n以上,我们已经知道了凸包上的第一个点 P0 和第二个点 P1,我们把它们放在栈里面。现在从步骤3求得的那个结果里,把 P1 后面的那个点拿出来做当前点,即 P2 。接下来开始找第三个点: \n4、连接P0和栈顶的那个点,得到直线 L 。看当前点是在直线 L 的右边还是左边。如果在直线的右边就执行步骤5;如果在直线上,或者在直线的左边就执行步骤6。 \n5、如果在右边,则栈顶的那个元素不是凸包上的点,把栈顶元素出栈。执行步骤4。 \n6、当前点是凸包上的点,把它压入栈,执行步骤7。 \n7、检查当前的点 P2 是不是步骤3那个结果的最后一个元素。是最后一个元素的话就结束。如果不是的话就把 P2 后面那个点做当前点,返回步骤4。 \n最后,栈中的元素就是凸包上的点了。 \n以下为用Graham扫描法动态求解的过程: \n \n\n## Jarvis步进法\n时间复杂度:O(nH)。(其中 n 是点的总个数,H 是凸包上的点的个数) \n思路:\n\n纵坐标最小的那个点一定是凸包上的点,例如图上的 P0。\n从 P0 开始,按逆时针的方向,逐个找凸包上的点,每前进一步找到一个点,所以叫作步进法。\n怎么找下一个点呢?利用夹角。假设现在已经找到 {P0,P1,P2} 了,\n要找下一个点:剩下的点分别和 P2 组成向量,\n设这个向量与向量P1P2的夹角为 β 。\n当 β 最小时就是所要求的下一个点了,此处为 P3 。 \n \n\n注意:\n找第二个点 P1 时,因为已经找到的只有 P0 一个点,所以向量只能和水平线作夹角 α,当 α 最小时求得第二个点。\n共线情况:如果直线 P2P3 上还有一个点 P4,即三个点共线,此时由向量P2P3 和向量P2P4 产生的两个 β 是相同的。我们应该把 P3、P4 都当做凸包上的点,并且把距离 P2 最远的那个点(即图中的P4)作为最后搜索到的点,继续找它的下一个连接点。\n\n\n## 分治法\n时间复杂度:O(n㏒n)。 \n思路:应用分治法思想,把一个大问题分成几个结构相同的子问题,把子问题再分成几个更小的子问题……。然后我们就能用递归的方法,分别求这些子问题的解。最后把每个子问题的解“组装”成原来大问题的解。 \n步骤:\n把所有的点都放在二维坐标系里面。那么横坐标最小和最大的两个点 P1 和 Pn 一定是凸包上的点(为什么呢?用反证法很容易证明,这里不详讲)。直线 P1Pn 把点集分成了两部分,即 X 轴上面和下面两部分,分别叫做上包和下包。\n对上包:求距离直线 P1Pn 最远的点,即下图中的点 Pmax 。\n作直线 P1Pmax 、PnPmax,把直线 P1Pmax 左侧的点当成是上包,把直线 PnPmax 右侧的点也当成是上包。\n重复步骤 2、3。\n对下包也作类似操作. \n \n然而怎么求距离某直线最远的点呢?我们还是用到解一中的公式: \n设有一个点 P3 和直线 P1P2 。(坐标:p1(x1,y1),p2(x2,y2),p3(x3,y3)) \n \n对上式的结果取绝对值,绝对值越大,则距离直线越远。\n注意: \n在步骤一,如果横坐标最小的点不止一个,那么这几个点都是凸包上的点,此时上包和下包的划分就有点不同了,需要注意。\n\n## 穷举法(蛮力法)\n时间复杂度:O(n³)。 \n思路:两点确定一条直线,如果剩余的其它点都在这条直线的同一侧,则这两个点是凸包上的点,否则就不是。 \n步骤:\n将点集里面的所有点两两配对,组成 n(n-1)/2 条直线。\n对于每条直线,再检查剩余的 (n-2) 个点是否在直线的同一侧。\n如何判断一个点 p3 是在直线 p1p2 的左边还是右边呢?(坐标:p1(x1,y1),p2(x2,y2),p3(x3,y3)) \n \n当上式结果为正时,p3在直线 p1p2 的左侧;当结果为负时,p3在直线 p1p2 的右边。\n\n\n\n\n"
},
{
"alpha_fraction": 0.720678985118866,
"alphanum_fraction": 0.7561728358268738,
"avg_line_length": 39.5,
"blob_id": "0102f62f017168818f8df09e5af96b6422a245e3",
"content_id": "bc75efbe42335d2f7fb8be2a245a5b9a450a7838",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1054,
"license_type": "permissive",
"max_line_length": 103,
"num_lines": 16,
"path": "/BatSummary/重定向/重定向.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Bat批处理文件中用于计时的一个小工具\n[重定向](重定向.bat) \n[stack overflow](https://superuser.com/questions/338277/windows-cmd-batch-start-and-output-redirection)\n```commandline\necho hhhhhh 1>con.log 将清空原来的内容\necho hhhhhh 1>>con.log 不清空原来的内容,追加在末尾\necho hhhhhh >nul nul代表的是“空设备”,输出流重定向到空设备就相当于屏蔽掉了一样\necho hhhhhh 1>con 2>con 意思是将echo命令的结果中的标准输出和标准错误输出输出到控制台con中\ndir file.c 1> output.msg 2>&1 用“2>&1”将标准错误输出重定向到标准输出。\nstart cmd /b python 1st.py arg1 arg2 ^> out.txt /b代表后台运行 /k代表不关闭 /c代表执行完以后关闭\n^>代表转义\">\"否则\">\"将作为python的参数传入脚本\nstart call delay.bat ^1^> log.txt ^2^>^&^1 同理\nstart call delay.bat ^>^> log.txt 同理\n```\n\n1代表正常输出(即所谓的“标准输出”–stdout),2代表错误输出(即所谓的“标准错误输出”–stderr)。\n"
},
{
"alpha_fraction": 0.7058823704719543,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 7.5,
"blob_id": "8b88fcd36f452a162076a7c830e337ad11620410",
"content_id": "c7bf97ebb31a52ab7700a95d89961ed3b0e0d2a5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 17,
"license_type": "permissive",
"max_line_length": 9,
"num_lines": 2,
"path": "/README.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog\ntech bLog\n"
},
{
"alpha_fraction": 0.6768157482147217,
"alphanum_fraction": 0.6914049983024597,
"avg_line_length": 23.818897247314453,
"blob_id": "48706390e1491cae3677ccc2c4c2d09cbe9ea380",
"content_id": "2b9708efa9edadfce048183808bd2e1f9c99ae8e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4411,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 127,
"path": "/JavaSummary/out/production/JavaSummary/Java11新特性/Java11NewFeatures.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-Java11 New Features\n总结Java 11 8 个新特性相关问题\n\n## 1.本地变量类型推断\n```java\nvar javastack = \"javastack\";\nSystem.out.println(javastack);\n```\n局部变量类型推断就是左边的类型直接使用 var 定义,而不用写具体的类型,编译器能根据右边的表达式自动推断类型,如上面的 String 。\n## 2.字符串加强\n```java\n// 判断字符串是否为空白\n\" \".isBlank(); // true\n\n// 去除首尾空格\n\" Javastack \".strip(); // \"Javastack\"\n\n// 去除尾部空格 \n\" Javastack \".stripTrailing(); // \" Javastack\"\n\n// 去除首部空格 \n\" Javastack \".stripLeading(); // \"Javastack \"\n\n// 复制字符串\n\"Java\".repeat(3); // \"JavaJavaJava\"\n\n// 行数统计\n\"A\\nB\\nC\".lines().count(); // 3\n```\n\n## 3.集合加强\n集合(List/ Set/ Map)都添加了 of 和 copyOf 方法,它们两个都用来创建不可变的集合,来看下它们的使用和区别。\n```java\nvar list = List.of(\"Java\", \"Python\", \"C\");\nvar copy = List.copyOf(list);\nSystem.out.println(list == copy); // true\n```\n```java\nvar list = new ArrayList<String>();\nvar copy = List.copyOf(list);\nSystem.out.println(list == copy); // false\n```\ncopyOf 方法会先判断来源集合是不是 AbstractImmutableList 类型的,如果是,就直接返回,如果不是,则调用 of 创建一个新的集合。\n\n示例2因为用的 new 创建的集合,不属于不可变 AbstractImmutableList 类的子类,所以 copyOf 方法又创建了一个新的实例,所以为false.\n\n注意:使用 of 和 copyOf 创建的集合为不可变集合,不能进行添加、删除、替换、排序等操作,不然会报 java.lang.UnsupportedOperationException 异常。\n上面演示了 List 的 of 和 copyOf 方法,Set 和 Map 接口都有。\n\n## 4.Stream 加强\n1) 增加单个参数构造方法,可为null\n```java\nStream.ofNullable(null).count(); // 0\n```\n\n2) 增加 takeWhile 和 dropWhile 方法\n```java\nStream.of(1, 2, 3, 2, 1)\n .takeWhile(n -> n < 3)\n .collect(Collectors.toList()); // [1, 2]\n```\n\n从开始计算,当 n < 3 时就截止。\n```java\nStream.of(1, 2, 3, 2, 1)\n .dropWhile(n -> n < 3)\n .collect(Collectors.toList()); // [3, 2, 1]\n```\n\n这个和上面的相反,一旦 n < 3 不成立就开始计算。\n\n3)iterate重载\n\n这个 iterate 方法的新重载方法,可以让你提供一个 Predicate (判断条件)来指定什么时候结束迭代。\n## 5.Optional 加强\n现在可以很方便的将一个 Optional 转换成一个 Stream, 或者当一个空 Optional 时给它一个替代的。\n```java\nOptional.of(\"javastack\").orElseThrow(); // javastack\nOptional.of(\"javastack\").Stream().count(); // 1\nOptional.ofNullable(null)\n .or(() -> Optional.of(\"javastack\"))\n .get(); // javastack\n```\n\n## 6.InputStream 加强\nInputStream 终于有了一个非常有用的方法:transferTo,可以用来将数据直接传输到 OutputStream,这是在处理原始数据流时非常常见的一种用法,如下示例。\n```java\nvar classLoader = ClassLoader.getSystemClassLoader();\nvar inputStream = classLoader.getResourceAsStream(\"javastack.txt\");\nvar javastack = File.createTempFile(\"javastack2\", \"txt\");\ntry (var outputStream = new FileOutputStream(javastack)) {\n inputStream.transferTo(outputStream);\n}\n```\n\n## 7.HTTP Client API\n这是 Java 9 开始引入的一个处理 HTTP 请求的的孵化 HTTP Client API,该 API 支持同步和异步,而在 Java 11 中已经为正式可用状态,你可以在 java.net 包中找到这个 API。\n```java\nvar request = HttpRequest.newBuilder()\n .uri(URI.create(\"https://javastack.cn\"))\n .GET()\n .build();\nvar client = HttpClient.newHttpClient();\n\n// 同步\nHttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());\nSystem.out.println(response.body());\n\n// 异步\nclient.sendAsync(request, HttpResponse.BodyHandlers.ofString())\n .thenApply(HttpResponse::body)\n .thenAccept(System.out::println);\n```\n上面的 .GET() 可以省略,默认请求方式为 Get\n## 8.命令编译运行源代码\n```\n// 编译\njavac Javastack.java\n\n\n// 运行\njava Javastack\n```\n在我们的认知里面,要运行一个 Java 源代码必须先编译,再运行,两步执行动作。而在未来的 Java 11 版本中,通过一个 java 命令就直接搞定了,如以下所示。\n```youtrack\njava Javastack.java\n```\n\n"
},
{
"alpha_fraction": 0.5254237055778503,
"alphanum_fraction": 0.6271186470985413,
"avg_line_length": 22.600000381469727,
"blob_id": "ded043a82cf73558a29ef7f9448164f0855d69ec",
"content_id": "5100f8bed1cb3366dd1a063183fd1e2d7377b329",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 118,
"license_type": "permissive",
"max_line_length": 28,
"num_lines": 5,
"path": "/PythonSummary/游戏设计/Timer设计/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python \n# -- coding: utf-8 -- \n# Time : 2021/12/7 17:56\n# Author : zhou pengcheng\n# ProjectName: PythonSummary\n"
},
{
"alpha_fraction": 0.8589933514595032,
"alphanum_fraction": 0.8649148941040039,
"avg_line_length": 53.040000915527344,
"blob_id": "4cb98ad9b5ffe2fee5adf172ac276992e2bfb176",
"content_id": "5f9fb31aa43c5ffcb210b137b8c34cc18a515c1c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6131,
"license_type": "permissive",
"max_line_length": 272,
"num_lines": 50,
"path": "/PythonSummary/网络编程/Socket Learn/IO.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Learn IO summary\n同步:提交一个任务之后要等待这个任务执行完毕\n\n异步:只管提交任务,不等待这个任务执行完毕就可以做其它的事情\n\n阻塞:当用户线程发出IO请求之后,内核会去查看数据是否就绪,如果没有就绪就会等待数据就绪,而用户线程就会处于阻塞状态,用户线程交出CPU。当数据就绪之后,内核会将数据拷贝到用户线程,并返回结果给用户线程,用户线程才解除block状态。(例如:在socket中的这些recvfrom,recv,accept都会产生阻塞。)\n\n非阻塞:**当用户线程发起一个read操作后,并不需要等待,而是马上就得到了一个结果。** 如果结果是一个error时,它就知道数据还没有准备好,于是它可以再次发送read操作。一旦内核中的数据准备好了,并且又再次收到了用户线程的请求,那么它马上就将数据拷贝到了用户线程,然后返回。\n (所以事实上,在非阻塞IO模型中,用户线程需要不断地询问内核数据是否就绪,也就说非阻塞IO不会交出CPU,而会一直占用CPU。)\n \n###在linux中,默认情况下所有的socket都是blocking,一个读操作的大致流程如下:\n\n1、当用户进程调用了recvfrom这个系统调用,kernel就开始了IO的第一个阶段:准备数据。对于network io来说,很多时候数据在一开始还没有到达(比如,还没有收到一个完整的UDP包),这个时候kernel就要等待足够的数据到来。\n\n2、而在用户进程这边,整个进程会被阻塞。当kernel一直等到数据准备好了,它就会将数据从kernel中拷贝到用户内存,然后kernel返回结果,用户进程才解除block的状态,重新运行起来。\n\n**所以,blocking IO的特点就是在IO执行的两个阶段(等待数据和拷贝数据两个阶段)都被block了。**\n几乎所有的IO接口 ( 包括socket接口 ) 都是阻塞型的。这给网络编程带来了一个很大的问题,如在调用recv(1024)的同时,线程将被阻塞,在此期间,线程将无法执行任何运算或响应任何的网络请求。\n\n###Linux下,可以通过设置socket使其变为non-blocking。当对一个non-blocking socket执行读操作时,流程是这个样子\n\n从图中可以看出,当用户进程发出read操作时,如果kernel中的数据还没有准备好,那么它并不会block用户进程,而是立刻返回一个error。从用户进程角度讲 ,它发起一个read操作后,并不需要等待,而是马上就得到了一个结果。用户进程判断结果是一个error时,它就知道数据还没有准备好,于是用户就可以在本次到下次再发起read询问的时间间隔内做其他事情,或者直接再次发送read操作。一旦kernel中的数据准备好了,并且又再次收到了用户进程的system call,那么它马上就将数据拷贝到了用户内存(这一阶段仍然是阻塞的),然后返回。\n\n也就是说非阻塞的recvform系统调用之后,进程并没有被阻塞,内核马上返回给进程,如果数据还没准备好,此时会返回一个error。进程在返回之后,可以干点别的事情,然后再发起recvform系统调用。重复上面的过程,循环往复的进行recvform系统调用。这个过程通常被称之为轮询。轮询检查内核数据,直到数据准备好,再拷贝数据到进程,进行数据处理。需要注意,拷贝数据整个过程,进程仍然是属于阻塞的状态。\n\n**所以,在非阻塞式IO中,用户进程其实是需要不断的主动询问kernel数据准备好了没有。**\n##多路复用IO(IO multiplexing)\n**也就是单个process就可以同时处理多个网络连接的IO.** 通常select poll epoll三个方法。详解见[select详解](./Multiple%20Client%20Connections/python%20select模块详解.md)\nselect/epoll的好处就在于单个process就可以同时处理多个网络连接的IO。它的基本原理就是select/epoll这个function会不断的轮询所负责的所有socket,当某个socket有数据到达了,就通知用户进程。\n\n当用户进程调用了select,那么整个进程会被block,而同时,kernel会“监视”所有select负责的socket,当任何一个socket中的数据准备好了,select就会返回。这个时候用户进程再调用read操作,将数据从kernel拷贝到用户进程。\n\n**强调:** \n1.如果处理的连接数不是很高的话,使用select/epoll的web server不一定比使用multi-threading + blocking IO的web server性能更好,可能延迟还更大。select/epoll的优势并不是对于单个连接能处理得更快,而是在于能处理更多的连接。\n\n2. 在多路复用模型中,对于每一个socket,一般都设置成为non-blocking,但是,如上图所示,整个用户的process其实是一直被block的。只不过process是被select这个函数block,而不是被socket IO给block。\n\n**结论: select的优势在于可以处理多个连接,不适用于单个连接** \n\n优点:\n\n相比其他模型,使用select() 的事件驱动模型只用单线程(进程)执行,占用资源少,不消耗太多 CPU,同时能够为多客户端提供服务。如果试图建立一个简单的事件驱动的服务器程序,这个模型有一定的参考价值。\n\n缺点:\n\n首先select()接口并不是实现“事件驱动”的最好选择。因为当需要探测的句柄值较大时,select()接口本身需要消耗大量时间去轮询各个句柄。window提供select()机制\n\n很多操作系统提供了更为高效的接口,如linux提供了epoll,BSD提供了kqueue,Solaris提供了/dev/poll,…。Linux 也有select()、poll机制\n\n使用类似于epoll的接口实现具有较好跨平台能力的服务器会比较困难。其次,该模型将事件探测和事件响应夹杂在一起,一旦事件响应的执行体庞大,则对整个模型是灾难性的。\n"
},
{
"alpha_fraction": 0.7182044982910156,
"alphanum_fraction": 0.7446383833885193,
"avg_line_length": 22.057470321655273,
"blob_id": "93d26f7482833480828b32d97a63e3d806001cd3",
"content_id": "bf23ae2094d8a17355e73bbc36ad921e1b71ac25",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3177,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 87,
"path": "/PythonSummary/网络编程/Protobuf/ProtoBuf.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Learn Google.ProtoBuf summary\n(版本:python 2.7,protobuf2 和 protobuf3)\nProtoBuf 所生成的二进制文件在存储效率上比 XML 高 3~10 倍,并且处理性能高 1~2 个数量级\n这是为什么选择 ProtoBuf 作为序列化方案的一个重要因素\n## Protobuf 使用方法\n\n1.安装 protoc: ProtoBuf基于 C++ 进行的实现, protoc作为编译器编译 *.proto\n在python_out指定的path中生成 *_pb2.py 文件\n```bash\n$ protoc --python_out=. *.proto\n``` \n2.安装 ProtoBuf 相关的 python 依赖库\n```$python\n$ pip install protobuf\n```\n\n## ProtoBuf字段与方法\n```protobuf\n//声明使用的protobuf版本\nsyntax = \"proto2\";\n//package的声明,为了帮助防止在不同的工程中命名冲突。在Python中,包通常由目录结构决定的,\n// 所以这个由你的.proto文件定义的包,在你生成你代码中是没有效果的。 \n//但是,你应该坚持声明这条语句,为了在protocol Buffers的命名空间中防止名子的冲突,就像其它非Python的语言那样 \npackage tutorial;\n\nmessage Person {\n//“=1”,“=2”标记每个元素的识别,作为二进制编码中字段的唯一的标签。标签要求数字1-15比更高的数字少一个字节编码,\n//所以,作为最优化的方案,你可以决定对常用的和要重复使用的元素使用这些标签,把16或最高的数字留给不常用和可选择的元素。\n required string name = 1;\n//修饰语修饰\n//required:一定要提供一个值给这个字段,否则这条Message会被认为“没有初始化”。\n required int32 id = 2;\n optional string email = 3;\n\n enum PhoneType {\n MOBILE = 0;\n HOME = 1;\n WORK = 2;\n }\n\n message PhoneNumber {\n required string number = 1;\n//optional:这个字段可以设置也可以不设置 。如果一个可选字段没有设置值,一个默认值将赋予该字段,也可以指定自己的默认值\n optional PhoneType type = 2 [default = HOME];\n }\n\n repeated PhoneNumber phone = 4;\n}\n\nmessage AddressBook {\n//repeated:这个字段会重复几次一些号码(包括0)\n//这个addressbook例子便有个很好的该修饰符的应用场景,即每个人可能有多个电话号码。(类似动态的数组)\n repeated Person person = 1;\n}\n```\n\n```protobuf\nsyntax = \"proto3\";\npackage RpcMsg;\n//使用any需要把any.protobuf放入当前目录用于编译\nimport \"google/protobuf/any.proto\";\n\nmessage RpcPacket{\n //不需要关键字optional,每一个都是一个optional\n string method = 1;\n google.protobuf.Any args = 2;\n}\n\nmessage LoginInfoFromClient {\n string name = 1;\n string password = 2;\n}\n\nmessage LoginInfoFromServer {\n int32 feedbackCode = 2;\n string name = 3;\n int32 hid = 4;\n}\n\n```\n\n##遇到的问题与解决方案\n1.protobuf2 在optional的序列化没有[default = HOME]的话,反序列化就不会得到相应字段 \n -使用proto3就不会存在1的问题 \n2.protobuf3 文件中使用any泛型,编译 not found \"google/protobuf/any.proto\" \n -在官网上下载相应的protoc-x.xx.x-win64.zip,解压得到include中的[google](./google)文件,\n 放在自己需要编译的.proto文件下"
},
{
"alpha_fraction": 0.7022815942764282,
"alphanum_fraction": 0.7150806784629822,
"avg_line_length": 33.5,
"blob_id": "d2a001a5e9ec3c31bfb6a00bf7dcacad4986eb4d",
"content_id": "319823748dec1a8d370f7993b95a6ada519153a3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2901,
"license_type": "permissive",
"max_line_length": 172,
"num_lines": 52,
"path": "/PythonSummary/游戏设计/Reload热更新/import.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# python import的一些机制\n\n## import\n示例见[import机制](import机制.py)\n从 sys.modules 中 pop 掉 \"a.b\",再次import,\n竟然没有再次放入 sys.modules。也没有报任何异常,一切看起来都是OK的。\n但“a.b\"并没有再次转载入sys中 \n“import a.b as b” 之后才发现可以找到\n\n## 原理\nPython中的import方式分为2种:\n```\nimport_stmt: import_name | import_from\nimport_name: 'import' dotted_as_names\nimport_from: ('from' ('.'* dotted_name | '.'+)\n 'import' ('*' | '(' import_as_names ')' | import_as_names)\n```\n第一种: import A.B.C。称之为 import_name。这种情况比较简单,只有1个参数:\"A.B.C\", 称之为 module。\n\n第二种:from A.B import C, D。称之为 import_from。这种情况下就有2个参数: \"A.B\" 称之为 module,\"C, D\" 称之为 names (代码里也表示为 fromlist)。\n\nPython在执行 import 加载模块时,对上述2种情况中的module,都是先检查 sys.modules 是否存在,不存在就重新加载。 \n(参见 Import.c (line 2668) : import_submodule(...) 函数中检查sys.modules中是否存在)。 \n但对于 import_from 中的 names,是通过 ensure_fromlist 函数来处理的,这个函数并不是立刻从 sys.modules 中查找是否存在,而是优先在刚才加载的module中查找。 \n(参见 Import.c (line 2273) : import_module_level(..)函数中调用 ensure_fromlist)(参见 Import.c (line 2597) : ensure_fromlist 中从刚加载的module中判断是否存在)。\n\n### 重点在上面例子中的第二个import:\n[import机制](import机制.py)\n```\nsys.modules.pop(\"a.b\")\nfrom a import b\n```\n1.首先加载 a, sys.modules 中不存在 a,则从文件里加载 a \n2.<font color=red>**然后从 a 里面检查是否有 b**</font>,没有,从sys.modules中检查,也没有,则从文件里加载 b \n3.加载成功后,<font color=red>**a 中有了 b 的引用:a.b is b。**</font>\n```\nsys.modules.pop(\"a.b\")\nfrom a import b\n```\n4.这时候,a 已经存在于 sys.modules 中了,所以不会再次加载 \n5.对于 b 是否存在优先检查 a.b 是否存在,此时 a.b 是存在的,所以 b 也不会再次被加载(当 a.b 不存在时,才会检查 sys.modules) \n6.于是一切都结束以后, sys.modules 中是没有 \"a.b\" 模块的\n```\nimport a.b\n```\n7.这次就会到 sys.modules 中检查 \"a.b\" 是否存在了,由于不存在,则会重新加载 b\n\n总结:\n\nimport A.B.C 这种 import_name 的形式,只会在 sys.modules 中检查是否存在,不存在则重新加载。\n\nfrom A.B import C 这种 import_from 的形式,module的部分和 import_name 的形式是一样的,但 names 或 fromlist 的部分是通过 ensure_fromlist 函数处理的,此函数优先检查刚才加载的module中是否存在,如果不存在才会再执行和 import_name 相同的加载逻辑。 \n\n"
},
{
"alpha_fraction": 0.6098191142082214,
"alphanum_fraction": 0.6627907156944275,
"avg_line_length": 26.678571701049805,
"blob_id": "86f18b6a41534ba3eba0c8a3edbfcf83b994a0d2",
"content_id": "a2487311430178e3562d24a6fd28aa850fb12085",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 802,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 28,
"path": "/PythonSummary/python原理及特性/py2绑定方法对象和未绑定方法对象/py2绑定方法对象和未绑定方法对象.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : py2绑定方法对象和未绑定方法对象.py\n@Time : 2021/4/16 10:55\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n\nclass Foo(object):\n def foo():\n print 'call foo'\n\n\tdef foo_one(self):\n\t\t\tprint 'call foo_one'\n\nFoo.foo() # TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)\nFoo().foo() # TypeError: foo() takes no arguments (1 given)\n\nFoo.foo #<unbound method Foo.foo>\nFoo().foo #<bound method Foo.foo of <__main__.Foo object at 0x0000000002835278>>\n\nFoo.foo_one() # TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)\nFoo().foo_one() # print call foo_one"
},
{
"alpha_fraction": 0.7742899656295776,
"alphanum_fraction": 0.7742899656295776,
"avg_line_length": 28.086956024169922,
"blob_id": "543b08ae096154e7015a257747a81dc8f5b5547e",
"content_id": "1aeee2e1686e4e53bcd57f832ef5c09fcde98483",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 977,
"license_type": "permissive",
"max_line_length": 98,
"num_lines": 23,
"path": "/JavaSummary/src/单例模式/StaticNestedClassSingleton.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 单例模式;\n\n// 静态内部类 static nested class\n// 这种方法也是《Effective Java》上所推荐的。\nclass StaticNestedClassSingleton {\n// 外部类加载时并不需要立即加载内部类,内部类不被加载则不去初始化INSTANCE,故而不占内存。\n// 即当SingleTon第一次被加载时,并不需要去加载SingleTonHoler,只有当getInstance()方法第一次被调用时,\n// 才会去初始化INSTANCE,第一次调用getInstance()方法会导致虚拟机加载SingleTonHoler类,\n// 这种方法不仅能确保线程安全,也能保证单例的唯一性,同时也延迟了单例的实例化。\n\n public StaticNestedClassSingleton() {\n }\n\n public static synchronized StaticNestedClassSingleton getInstance() {\n return SinletonHolder.instance;\n }\n\n private static class SinletonHolder {\n private static final StaticNestedClassSingleton instance=new StaticNestedClassSingleton();\n }\n\n\n}\n"
},
{
"alpha_fraction": 0.5341426134109497,
"alphanum_fraction": 0.5766312479972839,
"avg_line_length": 18.382352828979492,
"blob_id": "c54322f82a2c00738d1bee0593b8bdfbe60c65dc",
"content_id": "3ecb30adf4f05f4f13856c011afbc02edb51b874",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 717,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 34,
"path": "/JavaSummary/src/多线程/一主多从多线程协作/Thread/MyThread.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "/**\n * @program: TechSummary\n * @author: zpc\n * @create: 2019-08-18 20:56\n **/\npackage 多线程.一主多从多线程协作.Thread;\n/**\n * @Author: zpc\n * @Description: 线程类,查看执行的线程是哪个线程。\n * @Create: 2019-08-18 20:56\n **/\n\n\npublic class MyThread implements Runnable{\n private Integer number;\n\n public MyThread(int number){\n this.number = number;\n }\n\n @Override\n public void run() {\n try {\n Thread.sleep(2000);\n System.out.println(\"NOW! ThreadPoolExecutor - \" + getNumber());\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n public Integer getNumber() {\n return number;\n }\n}\n"
},
{
"alpha_fraction": 0.5611510872840881,
"alphanum_fraction": 0.5719424486160278,
"avg_line_length": 26.799999237060547,
"blob_id": "e6614f8ddd247a47bf4db9b8896ff3886d07c516",
"content_id": "557034bfa4f8f3f04a956797e720f6aee0ba9c7d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 294,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 10,
"path": "/PythonSummary/正则匹配/ReComment.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# ReComment Blog\n# Python 正则匹配代码注释\n```python\n s=\"aaaaaaa/*afdshdafhda*/hhhhhhhhhh/*afdshdafhda*/ // data2 2.5f\"\n m = re.compile(r'//.*')\n outtmp = re.sub(m, ' ', s)\n m = re.compile(r'/\\*.*?\\*/', re.S)\n result = re.sub(m, ' ', outtmp)\n```\nresut:aaaaaaa hhhhhhhhhh\n"
},
{
"alpha_fraction": 0.5831485390663147,
"alphanum_fraction": 0.6363636255264282,
"avg_line_length": 15.703703880310059,
"blob_id": "c7f2d13e4b99f68856cd80901a0c859dcfe1d791",
"content_id": "d7afa822bce3dd632939c5381e78ef5cf0f14c2e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 491,
"license_type": "permissive",
"max_line_length": 68,
"num_lines": 27,
"path": "/JavaSummary/src/多线程/一主多从多线程协作/Check/BaseCheckThread.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "/**\n * @program: TechSummary\n * @author: zpc\n * @create: 2019-08-18 21:11\n **/\npackage 多线程.一主多从多线程协作.Check;\nimport java.util.concurrent.Callable;\n\n/**\n * @Author: zpc\n * @Description: 检查服务是否成功\n * @Create: 2019-08-18 21:11\n **/\n\n\npublic abstract class BaseCheckThread implements Callable<Boolean> {\n\n protected final int uid;\n\n public BaseCheckThread(int uid){\n this.uid = uid;\n }\n\n public int getUid() {\n return uid;\n }\n}\n"
},
{
"alpha_fraction": 0.8711943626403809,
"alphanum_fraction": 0.8711943626403809,
"avg_line_length": 34.66666793823242,
"blob_id": "8f2d918afb62bfaa0f6471ca78fbd3a57f2d00d2",
"content_id": "64fcd8b6dc7c84873e5699dbe1fb9879f46a23b3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 939,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 12,
"path": "/JavaSummary/out/production/JavaSummary/Socket编程/Socket.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-Socket编程(基于Java实现)\n总结Socket编程入门(基于Java实现)相关问题\nsocket,又称套接字,是在不同的进程间进行网络通讯的一种协议、约定或者说是规范。\n\n对于socket编程,它更多的时候像是基于TCP/UDP等协议做的一层封装或者说抽象,是一套系统所提供的用于进行网络通信相关编程的接口。\n\n## 建立socket的基本流程\n我们以linux操作系统提供的基本api为例,了解建立一个socket通信的基本流程:\n\nSocket示范\n./BaseSocketClient.java \n注意这里的IO操作实现,我们使用了一个大小为MAX_BUFFER_SIZE的byte数组作为缓冲区,然后从输入流中取出字节放置到缓冲区,再从缓冲区中取出字节构建到字符串中去,这在输入流文件很大时非常有用,事实上,后面要讲到的NIO也是基于这种思路实现的。"
},
{
"alpha_fraction": 0.7468239665031433,
"alphanum_fraction": 0.7549909353256226,
"avg_line_length": 42.959999084472656,
"blob_id": "af680977e85d8ed6c763769f3bdc52d6cb690d09",
"content_id": "21c156f60eca57b3cc4bccd96851d2dcd03fe060",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1998,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 25,
"path": "/PythonSummary/网络编程/Socket Learn/socket.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Learn Python Socket programming summary\n\n##Socket 相关方法\n###服务器端socket\n| 方法 | 作用 |\n| :------: |:------: |\n|s.bind()|\t绑定地址(host,port)到套接字, 在AF_INET下,以元组(host,port)的形式表示地址。 \n|s.listen()|开始TCP监听。backlog指定在拒绝连接之前,操作系统可以挂起的最大连接数量。该值至少为1,大部分应用程序设为5就可以了。|\n|s.accept()|被动接受TCP客户端连接,(阻塞式)等待连接的到来|\n###客户端socket\n| 方法 | 作用 |\n| :------: |:------: |\n|s.connect()|主动初始化TCP服务器连接,。一般address的格式为元组(hostname,port),如果连接出错,返回socket.error错误。|\n|s.recv()|接收TCP数据,数据以字符串形式返回,bufsize指定要接收的最大数据量。flag提供有关消息的其他信息,通常可以忽略。| \n|s.send()|发送TCP数据,将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。| \n|s.recvfrom()|接收UDP数据,与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。| \n|s.sendto()|发送UDP数据,将数据发送到套接字,address是形式为(ipaddr,port)的元组,指定远程地址。返回值是发送的字节数。| \n|s.close()|关闭套接字| \n\t\n#服务器支持多客户端连接以及io复用\t\n##python 3.x\nselectors 模块能在 select 模块原型的基础上进行高级且高效的 I/O 复用。推荐用户改用 selectors 模块,除非用户希望对 OS 级的函数原型进行精确控制。 \n\t\nselectors定义了一个BaseSelector抽象基类,以及几个具体的实现(KqueueSelector,EpollSelector…),可用于等待多个文件对象的I / O准备就绪通知。\t\n实例见[DefaultSelector Demo.py](./Multiple%20Client%20Connections/DefaultSelector%20Demo.py)\t\n\t\n"
},
{
"alpha_fraction": 0.4907521605491638,
"alphanum_fraction": 0.6202219724655151,
"avg_line_length": 27.928571701049805,
"blob_id": "d77386a522e13f7e62d407ccd70d39d4d081a100",
"content_id": "ef6ed19a58547afad1184cfd4c0fb26910ab66ef",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1271,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 28,
"path": "/Linux Summary/日志查看.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#日志查看\n```\n 1 #输出文件末尾行(默认10行),当文件有追加时,会输出后续添加的行,不会中断输出,除非ctrl+c中断 \n 2 #-f 即 --follow=file.log\n 3 tail -f file.log \n 4 \n 5 #输出文件末尾100行,实时更新\n 6 tail -100f file.log \n 7 \n 8 #输出文件末尾包含关键字的行,当文件有追加时,会输出后续添加的行,不会中断输出,除非ctrl+c中断 \n 9 #-f 即 --follow=file.log\n10 tail -f file.log | grep \"关键字\" \n11 \n12 #输出文件的后100行中包含关键字的行(-n 100 即 --lines=100) \n13 tail -100f file.log | grep \"关键字\" \n14 \n15 #输出文件的后100行中包含关键字的行和该行的后10行 \n16 tail -n 100 file.log | grep \"关键字\" -A10 \n17 \n18 #输出文件的后100行中包含关键字的行和该行的前10行 \n19 tail -n 100 file.log | grep \"关键字\" -B10 \n20 \n21 #输出文件的后100行中包含关键字的行和该行的前后10行 \n22 tail -n 100 file.log | grep \"关键字\" -B10 -A10 \n23 \n24 #输出文件的后100行中包含关键字的行和该行的前后10行 关键字加上颜色 \n25 tail -n 100 file.log | grep \"关键字\" -B10 -A10 --color=auto\n```\n "
},
{
"alpha_fraction": 0.5574162602424622,
"alphanum_fraction": 0.5837320685386658,
"avg_line_length": 25.125,
"blob_id": "467802005f3f8cfa396f1c50b127c8ad3b426327",
"content_id": "cf830b23f741f5488923307704437617049c7054",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 500,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 16,
"path": "/PythonSummary/网络编程/Socket Learn/Base Demo/BaseServer.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\n\nimport socket # 导入 socket 模块\n\nhost = socket.gethostname() # 获取本地主机名\nport = 12345 # 设置端口\n# 创建 socket 对象\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((host, port)) # 绑定端口\n s.listen(5) # 等待客户端连接\n c, addr = s.accept() # 建立客户端连接\n while True:\n data = c.recv(1024)\n if not data: break\n c.send('send a message')\n c.close() # 关闭连接\n"
},
{
"alpha_fraction": 0.8235294222831726,
"alphanum_fraction": 0.8235294222831726,
"avg_line_length": 20.375,
"blob_id": "48df26f23a36170e269b4b2f5ad65c69b834082e",
"content_id": "7456d917693ab8f19444d2add7bfa10688561a0d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 434,
"license_type": "permissive",
"max_line_length": 37,
"num_lines": 8,
"path": "/PythonSummary/游戏设计/断线重连/断线重连.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# 断线重连\n## 问题背景\n断线使客户端与服务器双方状态不再一致,断线重连就是重新建立状态一致性的过程\n##解决方法\n* 全量恢复状态,相当于重新建立连接\n* 分模块恢复:重连时计算双方各模块的特征值,只同步特征不匹配模块\n* 双方缓存最近的若干条RPC,在重连时重传对方没收到过的RPC\n* 客户端cache 最后一条RPC, 断线重发"
},
{
"alpha_fraction": 0.7342233061790466,
"alphanum_fraction": 0.7366504669189453,
"avg_line_length": 26.46666717529297,
"blob_id": "ef0a46b15827509e00423265b75cdbc0456fac69",
"content_id": "3698a9d9d9baa38bfce44db0bf17689f8e6ee785",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1850,
"license_type": "permissive",
"max_line_length": 110,
"num_lines": 30,
"path": "/C++Summary/虚继承/虚继承.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "GB18030",
"text": "# 虚继承\n虚继承是解决 C++ 多重继承问题的一种手段,从不同途径继承来的同一基类,会在子类中存在多份拷贝。这将存在两个问题:第一,浪费存储空间;第二,存在二义性问题。\n\n针对这种情况,C++ 提供虚基类(virtual base class)的方法,使得在继承间接共同基类时只保留一份成员。方法如下:\n\n```\nclass A // 声明基类A\n{\n // 代码\n};\nclass B: virtual public A // 声明类 B 是类 A 的公有派生类,A 是 B 的虚基类\n{\n // 代码\n};\nclass C: virtual public A // 声明类 C 是类 A 的公有派生类,A 是 C 的虚基类\n{\n // 代码\n};\nclass D: public B, public C // 类 D 中只有一份 A 的数据\n{\n // 代码\n};\n```\n【注意】虚基类并不是在声明基类时声明的,而是在声明派生类时,指定继承方式时声明的。因为一个基类可以在生成一个派生类时作为虚基类,而在生成另一个派生类时不作为虚基类。\n\n问题:类 D 的构造函数通过初始化表调了虚基类的构造函数 A,而类 B 和类 C 的构造函数也通过初始化表调用了虚基类的构造函数 A,这样虚基类的构造函数岂非被调用了 3 次?\nC++ 编译系统只执行最后的派生类对虚基类的构造函数的调用,而忽略虚基类的其他派生类(如类 B 和类 C)对虚基类的构造函数的调用,这就保证了虚基类的数据成员不会被多次初始化。\n\n每个虚继承的子类都有一个虚基类表指针(占用一个指针的存储空间,4字节)和虚基类表(不占用类对象的存储空间)。虚基类表指针(virtual base table pointer)指向虚基类表(virtual table),\n虚表中记录了虚基类与本类的偏移地址,通过偏移地址,就找到了虚基类成员。\n"
},
{
"alpha_fraction": 0.7019498348236084,
"alphanum_fraction": 0.7284122705459595,
"avg_line_length": 36.842105865478516,
"blob_id": "b783a631caa2cc44664cd742c3bd7964575f9d86",
"content_id": "3999f0665b32e6d8e7d6b7b6e16ff50a8081938e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1296,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 19,
"path": "/PythonSummary/python原理及特性/新式类和经典类(旧式类)的区别/新式类和经典类(旧式类)的区别.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python \n# -- coding: utf-8 -- \n# Time : 2022/4/27 14:52\n# Author : zhou pengcheng\n# ProjectName: PythonSummary\n\n# Python2.x中,默认都是经典类,只有显式继承了object的才是新式类,即:\nclass Person(object):pass #新式类\nclass Person():pass # 经典类\n\n# 新式类和经典类(旧式类)的区别的在于子类多继承的情况下,经典类多继承搜索顺序是深度优先,新式类多继承搜索顺序是广度优先。\n# 新式类相同父类只执行一次构造函数,经典类重复执行多次。\n\n# 如果x是一个旧式类,那么x.__class__定义了x的类名,但是type(x)总是返回<type ‘instance’>。\n# 这反映了所有的旧式类的实例是通过一个单一的叫做instance的内建类型来实现的,这是它和类不同的地方。\n# 为什么要在2.2中引进new style class呢?官方给的解释是:\n# 为了统一类(class)和类型(type)。\n# 在2.2之前,比如2.1版本中,类和类型是不同的,如a是ClassA的一个实例,那么a.__class__返回 ‘ class __main__.ClassA‘ ,type(a)返回总是<type 'instance'>。\n# 而引入新类后,比如ClassB是个新类,b是ClassB的实例,b.__class__和type(b)都是返回‘class '__main__.ClassB' ,这样就统一了。"
},
{
"alpha_fraction": 0.5575539469718933,
"alphanum_fraction": 0.5827338099479675,
"avg_line_length": 14.885714530944824,
"blob_id": "9f31c3bda5ab0d138b6b32524e5bc80b1ecdd21d",
"content_id": "ef7017d2a118d323b4442d434311106d033f1d46",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 556,
"license_type": "permissive",
"max_line_length": 44,
"num_lines": 35,
"path": "/JavaSummary/src/Stream/WikiPage.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package Stream;\n\n/**\n * @Program: JavaSummary\n * @Author: zhoupengcheng03\n * @Package: Stream\n * @ClassName: WikiPage\n * @Description:\n * @Create: 2020-11-06 16:38\n **/\npublic class WikiPage {\n\n\n private long id;\n private long wikiId;\n\n public WikiPage setId(long id) {\n this.id = id;\n return this;\n }\n\n public WikiPage setWikiId(long wikiId) {\n this.wikiId = wikiId;\n return this;\n }\n\n public long getId() {\n return this.id;\n }\n\n public long getWikiId() {\n return this.wikiId;\n }\n\n}\n"
},
{
"alpha_fraction": 0.5305081009864807,
"alphanum_fraction": 0.5424894690513611,
"avg_line_length": 39.98181915283203,
"blob_id": "cdddada93cf8b5f1b4847b67fc65f867f193f0a6",
"content_id": "61193ebb6bb0cf77b71c687179956f2bee8a56b2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4921,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 110,
"path": "/JavaSummary/src/Stream/Stream性能隐患注意点.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-Stream性能隐患注意点\n## 处理N+1查询\n```\n /*************************************************************************\n * 【需求:查询所有Wiki站点下的全部词条,并打印所有词条及其所属Wiki站点】\n *************************************************************************/\n \n List<Wiki> wikis = dependenceWikiDomainService.selectByExample(\n Example.builder(Wiki.class).andWhere(\n Sqls.custom().andIn(\"id\", Arrays.asList(58L, 49L, 76L, 91L, 81L))\n ).build()\n );\n\n /******************************** old ********************************/\n long to1 = Instant.now().toEpochMilli();\n wikis.forEach(wiki -> {\n List<WikiPage> wikiPages = dependenceWikiPageDomainService.select(\n new WikiPage().setWikiId(wiki.getId())\n );\n wikiPages.forEach(wikiPage -> {\n // System.out.println(\n // String.format(\"%s, page from ==> %s\", wikiPage.getName(), wiki.getName())\n // );\n });\n });\n System.out.println(\"old method complete in ==> {}\", Instant.now().toEpochMilli() - to1);\n // old method complete in ==> 627\n\n /******************************** new ********************************/\n long tn1 = Instant.now().toEpochMilli();\n // 批量查询所有词条\n List<Long> wikiIds = wikis.stream().map(Wiki::getId).collect(Collectors.toList());\n List<WikiPage> wikiPages = dependenceWikiPageDomainService.selectByExample(\n Example.builder(WikiPage.class).andWhere(Sqls.custom().andIn(\"id\", wikiIds)).build()\n );\n\n // 构造Wiki站点映射集\n Map<Long, Wiki> wikiMap = wikis.stream().collect(\n Collectors.toMap(Wiki::getId, Function.identity())\n );\n\n // 根据Wiki站点映射集查找词条所属站点\n wikiPages.forEach(wikiPage -> {\n Wiki wiki = wikiMap.getOrDefault(wikiPage.getWikiId(), new Wiki().setName(\"-\"));\n // System.out.println(\n // String.format(\"%s, page from ==> %s\", wikiPage.getName(), wiki.getName())\n // );\n });\n System.out.println(\"new method complete in ==> {}\", Instant.now().toEpochMilli() - tn1);\n // new method complete in ==> 86\n```\n结果显示,老方法耗时627ms, 使用IN查询+映射集只需要86ms \n\n## 树形结构建立\n```\n/*************************************************************************\n * 【需求:将某篇文章的所有评论整理成树形结构(root 10个元素,2层树形)】\n *************************************************************************/\n/******************************** old ********************************/\nlong to2 = Instant.now().toEpochMilli();\n// 查询一级评论\nList<Comment> parentComments = dependenceCommentDomainService.selectByExample(\n Example.builder(Comment.class).andWhere(\n Sqls.custom().andEqualTo(\"sourceType\", \"Article\").andEqualTo(\"sourceId\", 53963L).andIsNull(\"childOfId\")\n ).orderByDesc(\"createdAt\").build()\n);\n\n// 遍历一级评论构造子评论列表\nList<List<Comment>> resultOld = parentComments.stream().map(parentComment -> {\n List<Comment> childs = dependenceCommentDomainService.select(\n new Comment().setSourceType(parentComment.getSourceType())\n .setSourceId(parentComment.getSourceId()).setChildOfId(parentComment.getId())\n );\n // do something\n return childs;\n}).collect(Collectors.toList());\nlog.info(\"old tree build in ==> {}\", Instant.now().toEpochMilli() - to2);\n// old tree build in ==> 1219\n\n/******************************** new ********************************/\nlong tn2 = Instant.now().toEpochMilli();\n// 查询所有评论\nList<Comment> comments = dependenceCommentDomainService.selectByExample(\n Example.builder(Comment.class).andWhere(\n Sqls.custom().andEqualTo(\"sourceType\", \"Article\").andEqualTo(\"sourceId\", 53963L)\n ).orderByDesc(\"createdAt\").build()\n);\n\n// 根据评论父ID分组\nMap<Long, List<Comment>> commentsMap = comments.stream().filter(\n e -> null != e.getChildOfId()\n).collect(\n Collectors.groupingBy(Comment::getChildOfId, Collectors.toList())\n);\n\n// 筛选一级评论\nList<Comment> rootComments = comments.stream().filter(\n e -> null == e.getChildOfId()\n).collect(Collectors.toList());\n\n// 遍历一级评论,查找映射集中的子评论列表\nList<List<Comment>> resultNew = rootComments.stream().map(e -> {\n List<Comment> childs = commentsMap.getOrDefault(e.getId(), Collections.emptyList());\n // do something\n return childs;\n}).collect(Collectors.toList());\nlog.info(\"new tree build in ==> {}\", Instant.now().toEpochMilli() - tn2);\n// new tree build in ==> 98\n```\n结果显示,老方法耗时1219ms, 使用新方法构造树只需要98ms"
},
{
"alpha_fraction": 0.4690265357494354,
"alphanum_fraction": 0.5238938331604004,
"avg_line_length": 21.639999389648438,
"blob_id": "acd4985d1e429c0f5fb8ba288c6a22007659e8a0",
"content_id": "cd165c382a0713383be9dc83cd5b6ebef9cde388",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 615,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 25,
"path": "/PythonSummary/python原理及特性/python简洁编程总结/Dict/DictKey/DictKey相关操作.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : DictKey相关操作.py\n@Time : 2020/10/12 15:46\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nif __name__ == '__main__':\n mylist = [{'k1': 'v1', 'k2': 'v2'}, {'k3': 'v3', 'k4': 'v4'}]\n dict = []\n\n for mydict in mylist:\n for k in mydict.keys():\n dict.append(k)\n print \"dict:\".format(dict)\n\n dict = []\n # 对字典的默认操作就是看做列表,内容是字典的Key\n for mydict in mylist:\n dict.extend(mydict)\n print \"dict:\".format(dict)"
},
{
"alpha_fraction": 0.7947368621826172,
"alphanum_fraction": 0.7973684072494507,
"avg_line_length": 33.59090805053711,
"blob_id": "acc2ad6725be1f9d2bc929fc89015b9be5df6722",
"content_id": "295aeb570143e5954c36a4d994282dc48f14a900",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1818,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 22,
"path": "/PythonSummary/游戏设计/行为树/行为树.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#行为树\n\n一颗行为树,首先,可以看到这是一个树形结构的图,有根节点,有分支,而且子节点个数可以任意.\n然后有三个分支,分别是巡逻(Patrol),攻击(Attack),逃跑(Retreat).\n这个三个分支可以看成是我们为这个士兵定义的三个大的行为(Behavior).当然,如果有更多的行为,我们可以继续在根节点中添加新的分支。\n当我们要决策当前这个士兵要做什么样的行为的时候,我们就会自顶向下的,通过一些条件来搜索这颗树.\n最终确定需要做的行为(叶节点),并且执行它,这就是行为树的基本原理。 \n\n我们标识的三大行为其实并不是真正的决策的结果,它只是一个类型,来帮助我们了解这个分支的一些行为是属于这类的,真正的行为树的行为都是在叶节点上,一般称之为行为节点(Action Node)\n\n行为节点一般分为两种运行状态:\n* 运行中(Executing):该行为还在处理中\n* 完成(Completed):该行为处理完成,成功或者失败\n\n除了行为节点,其余一般称之为控制节点(Control Node),用树的“学名”的话,就是那些父节点,如下图绿圈表示\n\n## 控制节点\n可以为行为树定义各种各样的控制节点(这也是行为树有意思的地方之一),一般来说,常用的控制节点有以下三种\n\n* 选择(Selector):选择其子节点的某一个执行\n* 序列(Sequence):将其所有子节点依次执行,也就是说当前一个返回“完成”状态后,再运行先一个子节点\n* 并行(Parallel):将其所有子节点都运行一遍"
},
{
"alpha_fraction": 0.8693069219589233,
"alphanum_fraction": 0.8732673525810242,
"avg_line_length": 47.095237731933594,
"blob_id": "61725f9897186a77793e2d5e147a68dd5ba34e96",
"content_id": "565e3438cd9bcf795896f31df693809c70da6b8c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1704,
"license_type": "permissive",
"max_line_length": 171,
"num_lines": 21,
"path": "/JavaSummary/src/List/List删除值/ListRemove.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-List/Map Remove\n总结List/Map Remove相关问题\n\n## List.remove(index) or List.remove(OBJ)\n当LIST删除.remove(int)时int作为index删除,当List.remove(Integer),Integer做为包装类可以直接被删除掉\n\n## java.util.ConcurrentModificationException产生\n当我们迭代一个ArrayList或者HashMap时,如果尝试对集合做一些修改操作(例如删除元素),可能会抛出java.util.ConcurrentModificationException的异常。\n### 异常原因\nArrayList的父类AbstarctList中有一个域modCount,每次对集合进行修改(增添元素,删除元素……)时都会modCount++\n而foreach的背后实现原理其实就是Iterator(关于Iterator可以看Java Design Pattern: Iterator),等同于注释部分代码。\n在这里,迭代ArrayList的Iterator中有一个变量expectedModCount,该变量会初始化和modCount相等,但如果接下来如果集合进行修改modCount改变,就会造成expectedModCount!=modCount,此时就会抛出java.util.ConcurrentModificationException异常\n###异常的解决\n1. 单线程环境:Itr中的也有一个remove方法,实质也是调用了ArrayList中的remove,但增加了expectedModCount = modCount;保证了不会抛出java.util.ConcurrentModificationException异常。 \n这个办法的有两个弊端 \n1.只能进行remove操作,add、clear等Itr中没有。 \n2.而且只适用单线程环境。 \n \n2. 多线程环境\nCopyOnWriteArrayList,解决了多线程问题,同时可以add、clear等操作 \nCopyOnWriteArrayList也是一个线程安全的ArrayList,其实现原理在于,每次add,remove等所有的操作都是重新创建一个新的数组,再把引用指向新的数组\n"
},
{
"alpha_fraction": 0.32305246591567993,
"alphanum_fraction": 0.35071542859077454,
"avg_line_length": 24.778688430786133,
"blob_id": "d3e2ffe09180628d5dd789a99afb8db8dbfd923c",
"content_id": "244e63e5cc400b6cd407f5a4a059ffcadacc8710",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3433,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 122,
"path": "/JavaSummary/src/凸包问题的五种解法/Graham.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 凸包问题的五种解法;/**\n * @program: javatest\n * @author: zpc\n * @create: 2019-09-16 16:09\n **/\n\nimport java.util.Scanner;\n\n/**\n * @Author: zpc\n * @Description:\n * @Create: 2019-09-16 16:09\n **/\n\n\npublic class Graham {\n\n\n\n\n Point[] ch; //点集p的凸包\n Point[] p ; //给出的点集\n int n;\n int l;\n int len=0;\n\n public Graham(Point[] p,int n,int l){\n this.p=p;\n this.n=n;\n this.l=l;\n ch= new Point[n];\n }\n\n //小于0,说明向量p0p1的极角大于p0p2的极角\n public double multiply(Point p1, Point p2, Point p0) {\n return ((p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y));\n }\n\n //求距离\n public double distance(Point p1, Point p2) {\n return (Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y)\n * (p1.y - p2.y)));\n }\n\n public void answer(){\n double sum = 0;\n for (int i = 0; i < len - 1; i++) {\n sum += distance(ch[i], ch[i + 1]);\n }\n if (len > 1) {\n sum += distance(ch[len - 1], ch[0]);\n }\n sum += 2 * l * Math.PI;\n System.out.println(Math.round(sum));\n }\n\n public int Graham_scan() {\n int k = 0, top = 2;\n Point tmp;\n\n //找到最下且偏左的那个点\n for (int i = 1; i < n; i++)\n if ((p[i].y < p[k].y)\n || ((p[i].y == p[k].y) && (p[i].x < p[k].x)))\n k = i;\n //将这个点指定为pts[0],交换pts[0]与pts[k]\n tmp = p[0];\n p[0] = p[k];\n p[k] = tmp;\n\n //按极角从小到大,距离偏短进行排序\n for (int i = 1; i < n - 1; i++) {\n k = i;\n for (int j = i + 1; j < n; j++)\n if ((multiply(p[j], p[k], p[0]) > 0)\n || ((multiply(p[j], p[k], p[0]) == 0) && (distance(\n p[0], p[j]) < distance(\n p[0], p[k]))))\n k = j; //k保存极角最小的那个点,或者相同距离原点最近\n tmp = p[i];\n p[i] = p[k];\n p[k] = tmp;\n }\n\n //前三个点先入栈\n ch[0] = p[0];\n ch[1] = p[1];\n ch[2] = p[2];\n\n //判断与其余所有点的关系\n for (int i = 3; i < n; i++) {\n //不满足向左转的关系,栈顶元素出栈\n while (top > 0 && multiply(p[i], ch[top], ch[top - 1]) >= 0)\n top--;\n\n //当前点与栈内所有点满足向左关系,因此入栈.\n ch[++top] = p[i];\n }\n len=top+1;\n return len;\n }\n\n public static void main(String[] args) {\n\n Scanner in=new Scanner(System.in);\n int n = in.nextInt();\n int l = in.nextInt();\n int x, y;\n Point[] p = new Point[n];\n for (int i = 0; i < n; i++) {\n x = in.nextInt();\n y = in.nextInt();\n p[i] = new Point(x, y);\n }\n\n Graham graham=new Graham(p,n,l);\n graham.Graham_scan();\n graham.answer();\n }\n\n\n}\n"
},
{
"alpha_fraction": 0.6437810659408569,
"alphanum_fraction": 0.6676616668701172,
"avg_line_length": 26.91666603088379,
"blob_id": "992f7408462359cf1b34d5cb0998d88a4a71a773",
"content_id": "c9ca0532ba9ff1c8395ea64721594d7e4c92dfde",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1341,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 36,
"path": "/JavaSummary/src/泛型/泛型.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 泛型;\n\n/**\n * @Program: JavaSummary\n * @Author: zhoupengcheng03\n * @Package: 泛型\n * @ClassName: 泛型\n * @Description:\n * @Create: 2022-02-15 11:35\n **/\npublic class 泛型 {\n}\n//BasicHolder<T>泛型类的类型参数并没有什么边界,在继承它的时候,你本可以class A extends BasicHolder<B> {}这样普普通通的用。\n//但class Subtype extends BasicHolder<Subtype> {}这样用,就构成自限定了。从定义上来说,它继承的父类的类型参数是它自己。\n// 从使用上来说,Subtype对象本身的类型是Subtype,且Subtype对象继承而来的成员(element)、方法的形参(set方法)、方\n// 法的返回值(get方法)也是Subtype了(这就是自限定的重要作用)。这样Subtype对象就只允许和Subtype对象(而不是别的类型的对象)交互了。\nclass BasicHolder<T> {\n T element;\n void set(T arg) { element = arg; }\n T get() { return element; }\n void f() {\n System.out.println(element.getClass().getSimpleName());\n }\n}\n\nclass Subtype extends BasicHolder<Subtype> {}\n\nclass CRGWithBasicHolder {\n public static void main(String[] args) {\n Subtype st1 = new Subtype(), st2 = new Subtype(), st3 = new Subtype();\n st1.set(st2);\n st2.set(st3);\n Subtype st4 = st1.get().get();\n st1.f();\n }\n}\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.77173912525177,
"avg_line_length": 53.79999923706055,
"blob_id": "18209f10710689f5a4301b2cb3e098ee75925571",
"content_id": "b3c8037ecc3c5bd3346532a31dbb9b4a24a045f9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 366,
"license_type": "permissive",
"max_line_length": 141,
"num_lines": 5,
"path": "/BatSummary/输出颜色/颜色输出.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Bat批处理输出带颜色\n[颜色输出](颜色输出.bat) \n[stack overflow](https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line/38617204#38617204)\n[单行输出彩色字符](批处理colstr函数---单行输出彩色字符.bat) \n[单行输出彩色字符bbs](http://bbs.bathome.net/thread-1852-1-1.html)\n\n\n"
},
{
"alpha_fraction": 0.8019375801086426,
"alphanum_fraction": 0.8105489611625671,
"avg_line_length": 24.83333396911621,
"blob_id": "2222d7f38b557bdeae150020cc7a3f944209c939",
"content_id": "f343b458d624760777eb1ea8e052e45cecdaa4be",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2181,
"license_type": "permissive",
"max_line_length": 130,
"num_lines": 36,
"path": "/JavaSummary/out/production/JavaSummary/设计模式DesignPatterns/designPattern.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-DesignPattern\n自己学习设计模式的时候做的总结 参考:https://github.com/Snailclimb/JavaGuide/blob/master/docs/system-design/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F.md\n## 创建型模式\n创建型模式(Creational Pattern)对类的实例化过程进行了抽象,能够将软件模块中对象的创建和对象的使用分离。为了使软件的结构更加清晰,外界对于这些对象只需要知道它们共同的接口,而不清楚其具体的实现细节,使整个系统的设计更加符合单一职责原则。\n创建型模式在创建什么(What),由谁创建(Who),何时创建(When)等方面都为软件设计者提供了尽可能大的灵活性。创建型模式隐藏了类的实例的创建细节,通过隐藏对象如何被创建和组合在一起达到使整个系统独立的目的。\n## 常见创建型模式详解\n* 单例模式: 深入理解单例模式——只有一个实例\n* 工厂模式: 深入理解工厂模式——由对象工厂生成对象\n* 建造者模式: 深入理解建造者模式 ——组装复杂的实例\n* 原型模式: 深入理解原型模式 ——通过复制生成实例\n\n##结构型模式\n结构型模式(Structural Pattern): 描述如何将类或者对象结合在一起形成更大的结构,就像搭积木,可以通过简单积木的组合形成复杂的、功能更为强大的结构\n\n* 适配器模式\n* 桥接模式\n* 组合模式\n* 装饰模式\n* 外观模式\n* 享元模式\n* 代理模式\n\n## 行为型模式\n行为型模式(Behavioral Pattern)是对在不同的对象之间划分责任和算法的抽象化。\n行为型模式不仅仅关注类和对象的结构,而且重点关注它们之间的相互作用。\n通过行为型模式,可以更加清晰地划分类与对象的职责,并研究系统在运行时实例对象之间的交互。在系统运行时,对象并不是孤立的,它们可以通过相互通信与协作完成某些复杂功能,一个对象在运行时也将影响到其他对象的运行。\n\n* 职责链模式\n* 命令模式\n* 解释器模式\n* 迭代器模式\n* 中介者模式\n* 备忘录模式\n* 观察者模式\n* 状态模式\n* 策略模式"
},
{
"alpha_fraction": 0.8254344463348389,
"alphanum_fraction": 0.8515008091926575,
"avg_line_length": 31.487178802490234,
"blob_id": "d873834a903b366be781ebc8a5bf157f7375a912",
"content_id": "cd196c236e03ec5337f829bf386b6cb6afa2d025",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3142,
"license_type": "permissive",
"max_line_length": 170,
"num_lines": 39,
"path": "/PythonSummary/python原理及特性/Python内存管理和垃圾回收机制/Python内存管理和垃圾回收机制.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Python内存管理和垃圾回收机制 \nPython中主要依靠gc(garbage collector)模块的引用计数技术来进行垃圾回收。\npython的内存管理机制有三种\n\n##引用计数\n引用计数是一种非常高效的内存管理手段,当一个pyhton对象被引用时其引用计数增加1,当其不再被引用时引用计数减1,当引用计数等于0的时候,对象就被删除了。\n\n优点:引用计数有一个最大的优点,即“实时性”,任何内存,一旦没有指向它的引用,就会立即被回收。\n \n缺点: \n1.循环引用 (“标记-清除”,“分代回收”两种收集技术。)\n2.引用计数机制所带来的维护引用计数的额外操作与 Python 运行中所进行的内存分配和释放,赋值的次数是成正比的。\n##垃圾回收\n###标记清除\n循环引用一般在容器对象才会产生,比如字典,元祖,列表等。首先为了追踪对象,需要每个容器对象维护两个额外的指针,用来将容器对象组成一个链表,指针分别指向前后两个容器对象,这样可以将对象的循环引用摘除,就可以得出两个对象的有效计数。\n \n首先将现在的内存链表一分为二,一条链表中维护 root object 集合,成为 root 链表,而另外一条链表中维护剩下的对象,成为 unreachable 链表。 \n\n现在的unreachable可能存在被root链表中的对象,直接或间接引用的对象,这些对象是不能被回收的,一旦在标记的过程中,发现这样的对象,就将其从unreachable链表中移到root链表中;当完成标记后,unreachable链表中剩下的所有对象就是名副其实的垃圾对象了,接下来的垃圾回收只需限制在unreachable链表中即可。\n###分代回收\n**从理论上说,创建==释放数量应该是这样子。但是如果存在循环引用的话,肯定是创建>释放数量,当创建数与释放数量的差值达到规定的阈值的时候**\n新生的对象被放入0代,如果该对象在第0代的一次gc垃圾回收中活了下来,那么它就被放到第1代里面(它就升级了)。如果第1代里面的对象在第1代的一次gc垃圾回收中活了下来,它就被放到第2代里面。 \n\n从上一次第0代gc后,如果分配对象的个数减去释放对象的个数大于threshold0,那么就会对第0代中的对象进行gc垃圾回收检查。\n## 内存池\n第3层:最上层,用户对Python对象的直接操作\n\n第1层和第2层:内存池,有Python的接口函数PyMem_Malloc实现-----若请求分配的内存在1~256字节之间就使用内存池管理系统进行分配,调用malloc函数分配内存,但是每次只会分配一块大小为256K的大块内存,不会调用free函数释放内存,将该内存块留在内存池中以便下次使用。\n\n第0层:大内存-----若请求分配的内存大于256K,malloc函数分配内存,free函数释放内存。\n\n第-1,-2层:操作系统进行操作\n\n##性能改进\n1.手动垃圾回收\n\n2.避免循环引用(手动解循环引用和使用弱引用)\n\n3.调高垃圾回收阈值"
},
{
"alpha_fraction": 0.5075818300247192,
"alphanum_fraction": 0.5291301012039185,
"avg_line_length": 24.059999465942383,
"blob_id": "7d4f559e2d513cb45ea239facbf6201e151e5ad8",
"content_id": "b85b789cb8176323c2f6266f198551772547267c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1263,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 50,
"path": "/PythonSummary/并发编程/阻塞主线程.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 阻塞主线程.py\n@Time : 2020/11/20 14:35\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nimport os\nimport random\n\nfrom concurrent.futures._base import wait, ALL_COMPLETED\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\n\n\ndef sayhello(k, v):\n x = \"hello: \"\n for i in xrange(2):\n if i:\n x += ' v:' + v\n else:\n x += 'k:' + k\n time.sleep(random.randint(1, 3))\n\n print('result {} in thread:{}'.format(x, os.getpid()))\n\n return x\n\n\ndef main():\n start3 = time.time()\n seed = {\"a\": \"a\", \"b\": \"a\", \"q\": \"a\", \"w\": \"a\", \"e\": \"a\", \"r\": \"a\", \"t\": \"a\", \"y\": \"a\", \"u\": \"a\", \"i\": \"a\",\n \"o\": \"a\", \"p\": \"a\", \"s\": \"a\", \"d\": \"f\", \"g\": \"a\", \"h\": \"l\"}\n with ProcessPoolExecutor() as pool:\n futures = [pool.submit(sayhello, k, v) for k, v in seed.iteritems()]\n wait(futures, return_when=ALL_COMPLETED)\n print 'wait all'\n pool.map(sayhello, seed.keys(), seed.values())\n pool.shutdown()\n print 'shutdown pool'\n\n\nif __name__ == '__main__':\n main()\n print 'end'\n"
},
{
"alpha_fraction": 0.5024795532226562,
"alphanum_fraction": 0.5144398808479309,
"avg_line_length": 26.753036499023438,
"blob_id": "eca76c5342d215b511c09965d7640b6fb43b9f15",
"content_id": "eb0e9247faa84302935d343a0f1daf4d62a85d05",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7566,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 247,
"path": "/JavaSummary/src/凸包问题的五种解法/Jarvis步进法.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 凸包问题的五种解法;/**\n * @program: javatest\n * @author: zpc\n * @create: 2019-09-16 15:32\n **/\n\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\n\nimport static java.lang.Math.abs;\n\n/**\n * @Author: zpc\n * @Description:\n * @Create: 2019-09-16 15:32\n **/\n\n\npublic class Jarvis步进法 {\n //Jarvis步进法\n //时间复杂度:O(nH)。(其中 n 是点的总个数,H 是凸包上的点的个数) \n //思路:\n //\n //纵坐标最小的那个点一定是凸包上的点,例如图上的 P0。\n //从 P0 开始,按逆时针的方向,逐个找凸包上的点,每前进一步找到一个点,所以叫作步进法。\n //怎么找下一个点呢?利用夹角。假设现在已经找到 {P0,P1,P2} 了,要找下一个点:\n // 剩下的点分别和 P2 组成向量,设这个向量与向量P1P2的夹角为 β 。当 β 最小时就是所要求的下一个点了,此处为 P3 。\n //\n //注意:\n //找第二个点 P1 时,因为已经找到的只有 P0 一个点,所以向量只能和水平线作夹角 α,当 α 最小时求得第二个点。\n //共线情况:如果直线 P2P3 上还有一个点 P4,即三个点共线,此时由向量P2P3 和向量P2P4 产生的两个 β 是相同的。\n // 我们应该把 P3、P4 都当做凸包上的点,并且把距离 P2 最远的那个点(即图中的P4)作为最后搜索到的点,继续找它的下一个连接点。\n\n}\n\n\nclass JarvisMarch {\n private int count;\n\n public int getCount() {\n return count;\n }\n\n public void setCount(int count) {\n this.count = count;\n }\n\n private static int MAX_ANGLE = 4;\n private double currentMinAngle = 0;\n private List<Point> hullPointList;\n private List<Integer> indexList;\n private PointFactory pf;\n private Point[] ps;\n\n public Point[] getPs() {\n return ps;\n }\n\n private int firstIndex;\n\n public int getFirstIndex() {\n return firstIndex;\n }\n\n public JarvisMarch() {\n this(10);\n }\n\n public JarvisMarch(int count) {\n pf = PointFactory.getInstance(count);\n initialize();\n }\n\n public JarvisMarch(int[] x, int[] y) {\n pf = PointFactory.getInstance(x, y);\n initialize();\n }\n\n private void initialize() {\n hullPointList = new LinkedList<Point>();\n indexList = new LinkedList<Integer>();\n firstIndex = pf.getFirstIndex();\n ps = pf.getPoints();\n addToHull(firstIndex);\n }\n\n private void addToHull(int index) {\n indexList.add(index);\n hullPointList.add(ps[index]);\n }\n\n public int calculateHull() {\n for (int i = getNextIndex(firstIndex); i != firstIndex; i = getNextIndex(i)) {\n addToHull(i);\n }\n showHullPoints();\n return 0;\n }\n\n private void showHullPoints() {\n Iterator<Point> itPoint = hullPointList.iterator();\n Iterator<Integer> itIndex = indexList.iterator();\n Point p;\n int i;\n int index = 0;\n System.out.println(\"The hull points is: -> \");\n while (itPoint.hasNext()) {\n i = itIndex.next();\n p = itPoint.next();\n System.out.print(i + \":(\" + p.getX() + \",\" + p.getY() + \") \");\n index++;\n if (index % 10 == 0)\n System.out.println();\n }\n System.out.println();\n System.out.println(\"****************************************************************\");\n System.out.println(\"The count of all hull points is \" + index);\n }\n\n public int getNextIndex(int currentIndex) {\n double minAngle = MAX_ANGLE;\n double pseudoAngle;\n int minIndex = 0;\n for (int i = 0; i < ps.length; i++) {\n if (i != currentIndex) {\n pseudoAngle = getPseudoAngle(ps[i].getX() - ps[currentIndex].getX(),\n ps[i].getY() - ps[currentIndex].getY());\n if (pseudoAngle >= currentMinAngle && pseudoAngle < minAngle) {\n minAngle = pseudoAngle;\n minIndex = i;\n } else if (pseudoAngle == minAngle){\n if((abs(ps[i].getX() - ps[currentIndex].getX()) >\n abs(ps[minIndex].getX() - ps[currentIndex].getX()))\n || (abs(ps[i].getY() - ps[currentIndex].getY()) >\n abs(ps[minIndex].getY() - ps[currentIndex].getY()))){\n minIndex = i;\n }\n }\n }\n\n }\n currentMinAngle = minAngle;\n return minIndex;\n }\n\n public double getPseudoAngle(double dx, double dy) {//计算极角\n if (dx > 0 && dy >= 0)\n return dy / (dx + dy);\n if (dx <= 0 && dy > 0)\n return 1 + (abs(dx) / (abs(dx) + dy));\n if (dx < 0 && dy <= 0)\n return 2 + (dy / (dx + dy));\n if (dx >= 0 && dy < 0)\n return 3 + (dx / (dx + abs(dy)));\n throw new Error(\"Impossible\");\n }\n\n\n public static void main(String[] args) {\n long start = System.currentTimeMillis();\n JarvisMarch j = new JarvisMarch(100000);\n Point[] points = j.getPs();\n int firstIndex = j.getFirstIndex();\n\n System.out.println(\"the first point is: \" + firstIndex + \":(\" +\n points[firstIndex].getX() + \",\" + points[firstIndex].getY() + \")\");\n System.out.println(\"*****************************************************************\");\n j.calculateHull();\n System.out.println(\"The total running time is \" + (System.currentTimeMillis() - start) + \" millis.\");\n }\n}\n\n\nclass PointFactory {\n /**\n * 单例模式,大批量产生Point,也可以手动产生Point\n */\n private Point[] points = null;\n private int newIndex;\n private int firstIndex = 0;\n\n public Point[] getPoints() {\n return points;\n }\n\n public int getFirstIndex() {\n return firstIndex;\n }\n\n public static PointFactory getInstance() {\n return new PointFactory();\n }\n\n public static PointFactory getInstance(int count) {\n return new PointFactory(count);\n }\n\n public static PointFactory getInstance(int[] x, int[] y) {\n return new PointFactory(x, y);\n }\n\n private PointFactory() {\n this(10);\n }\n\n private PointFactory(int count) {\n points = new Point[count];\n for (int i = 0; i < count; i++) {\n points[i] = new Point();\n newIndex = i;\n validatePoints();\n }\n firstIndex = getFirstPoint();\n }\n\n public PointFactory(int[] x, int[] y) {\n points = new Point[y.length];\n for (int i = 0; i < y.length; i++) {\n points[i] = new Point(x[i], y[i]);\n }\n firstIndex = getFirstPoint();\n }\n\n private void validatePoints() {\n for(int i = 0; i < newIndex; i++) {\n if(points[i].equals(points[newIndex])) {\n points[newIndex] = new Point();\n validatePoints();\n }\n }\n }\n\n public int getFirstPoint() {\n int minIndex = 0;\n for (int i = 1; i < points.length; i++) {\n if (points[i].getY() < points[minIndex].getY()) {\n minIndex = i;\n } else if ((points[i].getY() == points[minIndex].getY())\n && (points[i].getX() < points[minIndex].getX())) {\n minIndex = i;\n }\n }\n return minIndex;\n }\n\n}\n\n"
},
{
"alpha_fraction": 0.6867772936820984,
"alphanum_fraction": 0.6988436579704285,
"avg_line_length": 28.264705657958984,
"blob_id": "4b6d0d1d92698462d7fd98d2c0b3aabe5fe6ce66",
"content_id": "4507c1fd6b98d7505e0e46b5576eef5ac206b5d9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2799,
"license_type": "permissive",
"max_line_length": 125,
"num_lines": 68,
"path": "/JavaSummary/src/MapOperation/MapOperation.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-MapOperation\n总结Map java8 getOrDefault(),putIfAbsent() 和 computeIfAbsent() 三个方法\n\n## computeIfAbsent\nMap<String, List<String>> map = new HashMap<>(); \n如果我们要放一个元素进去,很多人会这么写:\n```java\nList<String> list = map.get(\"list1\");\nif (list == null) {\n list = new ArrayList<>();\n map.put(\"list1\", list);\n}\nlist.add(\"A\");\n```\n\n实际上从 Java 8 开始,Map 提供了 computeIfAbsent() 方法,我们可以写成一行即可:\n```java\nmap.computeIfAbsent(\"list1\", k -> new ArrayList<>()).add(\"A\");\n```\n其中变量 k 是 Map 的 key。Map定义的时候注意使用<anything,List<>>(List)定义不然无法使用lamada的k\n\n## computeIfPresent\n如果指定的key存在,则根据旧的key和value计算新的值newValue, 如果newValue不为null,则设置key新的值为newValue, 如果newValue为null, 则删除该key的值\n```java\nmap.computeIfPresent(1, (key, value) -> (key + 1) + value);\n// 存在key为1, 则根据旧的key和value计算新的值,输出 2a\nSystem.out.println(map.get(1));\n\nmap.computeIfPresent(2, (key, value) -> null);\n// 存在key为2, 根据旧的key和value计算得到null,删除该值,输出 null\nSystem.out.println(map.get(2));\n```\n## putIfAbsent\n这个方法的逻辑完全不同,注意它不是一个 get() 方法,而是 put() 方法的变种!这个方法的逻辑是,如果 Key 不存在或者对应的值是 null,则将 Value 设置进去,然后返回 null;否则只返回 Map 当中对应的值,而不做其他操作。\nput与putIfAbsent区别,put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据,而putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。\n不会覆盖\nput\n```java\nMap<Integer, String> map = new HashMap<>();\nmap.put(1, \"张三\");\nmap.put(2, \"李四\");\nmap.put(1, \"王五\");\nmap.forEach((key,value)->{\n System.out.println(\"key = \" + key + \", value = \" + value);\n});\nkey = 1, value = 王五\nkey = 2, value = 李四\n```\nputIfAbsent\n```java\nMap<Integer, String> putIfAbsent = new HashMap<>();\nputIfAbsent.putIfAbsent(1, \"张三\");\nputIfAbsent.putIfAbsent(2, \"李四\");\nputIfAbsent.putIfAbsent(1, \"王五\");\nputIfAbsent.forEach((key,value)->{\n\tSystem.out.println(\"key = \" + key + \", value = \" + value);\n});\nkey = 1, value = 张三\nkey = 2, value = 李四\n```\n## getOrDefault\n这个方法同样检查 Map 中的 Key,如果发现 Key 不存在或者对应的值是 null,则返回第二个参数即默认值。要注意,这个默认值不会放入 Map。所以如果你这样写:\n ```java\nMap<String, List<String>> map = new HashMap<>();\nmap.getOrDefault(\"list1\", new ArrayList<>()).add(\"A\");\n```\n \n执行完之后 map 仍然是空的!"
},
{
"alpha_fraction": 0.6090750694274902,
"alphanum_fraction": 0.6474694609642029,
"avg_line_length": 17.483871459960938,
"blob_id": "b3db0f792d2d9bc66ec3f6837f3cb1e8008e1d2a",
"content_id": "b264d70098fc98400177d8e8ed93e58c1711a307",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 763,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 31,
"path": "/PythonSummary/游戏设计/Reload热更新/import机制.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : import机制.py\n@Time : 2020/11/5 15:15\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n# 第一次测试很容易理解:import 的模块会存放在 sys.modules 里面。\n#\n# 但第二次测试就很出乎意料:从 sys.modules 中 pop 掉 \"a.b\",再次import,竟然没有再次放入 sys.modules。也没有报任何异常,一切看起来都是OK的。\n#\n# 从第三次测试来看,a 模块中引用了 b 模块。\nimport sys\n\nprint \"a.b\" in sys.modules\n# True\n\n\nsys.modules.pop(\"a.b\")\nprint \"a.b\" in sys.modules\n# False\n\nprint \"a.b\" in sys.modules\n# True\n\nprint 游戏设计.Reload热更新.a.b\n# <module 'a.b' from 'a\\b.py'>\n"
},
{
"alpha_fraction": 0.5384126901626587,
"alphanum_fraction": 0.5657142996788025,
"avg_line_length": 22.522388458251953,
"blob_id": "76be9e589139cc71332d1a6fbb082e9b384be9ba",
"content_id": "ae00680ae17afdab208b9a2957e7238ee804d15a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2083,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 67,
"path": "/PythonSummary/设计模式/装饰器模式/函数装饰器-装饰类.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 函数装饰器-装饰类.py\n@Time : 2020/12/3 17:42\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n# ================================例子1================================\ndef Singleton(cls): # 这是第一层函数,相当于模板中的Decorator.目的是要实现一个“装饰器”,而且是对类型的装饰器\n '''\n cls:表示一个类名,即所要设计的单例类名称,\n 因为python一切皆对象,故而类名同样可以作为参数传递\n '''\n instance = {}\n\n def singleton(*args, **kargs): # 这是第二层,相当于wrapper,要匹配参数\n if cls not in instance:\n instance[cls] = cls(*args, **kargs) # 如果没有cls这个类,则创建,并且将这个cls所创建的实例,保存在一个字典中\n return instance[cls] # 返回创建的对象\n\n return singleton\n\n\n@Singleton\nclass Student(object):\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n\ns1 = Student('张三', 23)\ns2 = Student('李四', 24)\nprint((s1 == s2))\nprint(s1 is s2)\nprint(id(s1), \" \", id(s2))\n\n# ================================例子2================================\ndef ClassDecorator(cls): # 第一层函数decorator\n height = 170\n weight = 65\n\n def wrapper(name, age): # 第二层函数wrapper,参数要和类的构造函数匹配\n s = cls(name, age)\n s.height = height # 添加两个额外属性\n s.weight = weight\n return s # 返回创建的对象,因为类的构造函数是要返回实例的,即有返回值\n\n return wrapper\n\n\n@ClassDecorator\nclass Student:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n\nstu = Student('张三', 25)\nprint(stu.name)\nprint(stu.age)\nprint(stu.height) # 在 IDE中可能会有提示此处错误,学生没有height和weight属性,但是运行之后没错\nprint(stu.weight) # 这就是python的魅力,动态添加属性"
},
{
"alpha_fraction": 0.5460636615753174,
"alphanum_fraction": 0.589614748954773,
"avg_line_length": 18.225807189941406,
"blob_id": "8001503830edac696e4a09a64b437e679270fe4a",
"content_id": "229624dd2f7402e9bebe433b233a66494d29be67",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 605,
"license_type": "permissive",
"max_line_length": 50,
"num_lines": 31,
"path": "/PythonSummary/并发编程/进程池/ProcessPoolExecutor基础使用.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : ProcessPoolExecutor基础使用.py\n@Time : 2020/11/16 14:40\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\n\n\ndef task(name):\n print(\"name\", name)\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n start = time.time()\n ex = ProcessPoolExecutor(2)\n\n for i in range(5):\n ex.submit(task, \"num:%d\" % i)\n ex.shutdown(wait=True)\n\n print(\"main\")\n end = time.time()\n print('run time:',end - start)\n\n"
},
{
"alpha_fraction": 0.4728682041168213,
"alphanum_fraction": 0.4728682041168213,
"avg_line_length": 22.763158798217773,
"blob_id": "631bdbc75a896a41aae6cf7beec80b3f5800bfb0",
"content_id": "2c184cf4c5da299802e9ecfdfaec2de915da8127",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 925,
"license_type": "permissive",
"max_line_length": 52,
"num_lines": 38,
"path": "/JavaSummary/src/List/List删除值/AddRemoveListElement.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package List.List删除值;\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class AddRemoveListElement {\n public static void main(String args[]) {\n List<String> list = new ArrayList<String>();\n list.add(\"A\");\n list.add(\"B\");\n\n for (String s : list) {\n if (s.equals(\"B\")) {\n list.add(s);\n list.remove(s);\n }\n }\n\n //foreach循环等效于迭代器\n Iterator<String> iterator=list.iterator();\n while(iterator.hasNext()){\n String s=iterator.next();\n if (s.equals(\"B\")) {\n list.remove(s);\n }\n }\n\n Iterator<String> iter = list.iterator();\n while(iter.hasNext()){\n String str = iter.next();\n if( str.equals(\"B\") )\n {\n iter.remove();\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.8274211883544922,
"alphanum_fraction": 0.8558558821678162,
"avg_line_length": 31.299999237060547,
"blob_id": "13171701266d52e66ba127e85d0a4385b56431e4",
"content_id": "31259155e017db23768764ec1de7a0d5e95d098c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 9572,
"license_type": "permissive",
"max_line_length": 203,
"num_lines": 110,
"path": "/PythonSummary/游戏设计/Timer设计/Timer设计.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Timer设计\n时间轮算法\n1. 基于队列的定时任务执行模型缺陷\n在计算机世界中,只有待解决的问题变得大规模后,算法的价值才能够最大化的体现。时间轮算法可以将插入和删除操作的时间复杂度都降为 O(1),在大规模问题下还能够达到非常好的运行效果。\n\n如果我们要实现一个定时任务该如何实现呢?\n\n最简单的方式就是使用一个任务队列来完成定时任务。具体实现细节下面详细展开。\n\n1.线程模型\n\n用户线程:负责定时任务的注册;\n定时任务队列轮询线程:负责扫描任务队列上符合要求的任务,如果任务的时间戳达到规定的时刻,首先从队列中取走此任务,然后将其交给异步线程池来处理;\n异步线程池:负责定时任务的执行;\n2.定时任务\n\n定时任务分为一次性执行的定时任务以及重复执行任务。\n\n一次性执行的定时任务:任务在规定的某一个时刻就会被执行,但是仅仅会被执行一次。这好比大学时你告诉学霸室友:明天考试前提醒我去考试。因为该考试只会组织一次,因此学霸提醒你一次就够了。\n重复执行的定时任务:任务在规定的某一个时刻会被执行后,将来的相同时刻需要被重复执行。这好比你上小学时告诉妈妈我每天 8:00 上学,你每天 7 点叫我起床。我们仅仅需要为每一个定时任务提供一个是否为定时任务的标签,定时任务队列轮询线程在发现此任务是需要重复执行的定时任务时,重新把定时任务注册到定时任务队列上。\n3.任务队列数据结构\n\n为了方便向任务队列中增减任务,通常会选择双向链表作为数据结构来实现任务队列。\n\n这种方式不过是基于异步队列,然后为每一个任务提供一个时间戳字段。这种实现策略的问题在哪里?\n\n如果有 1k 个任务,那么定时任务队列轮询线程每次都需要扫描 1k 个任务来确定哪一个任务达到规定时刻,这种轮询效率非常差,尤其是在大部分任务并没有达到规定执行时刻的情况下。\n\n为了解决上述问题,我们可以使用如下两种方式:\n\n有序任务队列;\n任务分类+多队列+并发线程;\n在计算机算法中,有序性通常能够显著提高遍历效率。我们现在将一个普通任务队列升级为一个按照任务执行的时间戳递增的有序任务队列。这样一来,定时任务队列轮询线程从头向尾遍历时,在发现任意线程未达到规定执行时间戳后,就可以停止遍历。此时,定时任务队列轮询线程甚至可以进行休眠操作,避免空轮询。\n\n但是,有序性并非没有代价。插入一个定时任务的事件复杂度为 O(nlogn),普通任务队列的插入仅仅是 O(1)。\n\n我们再来看看另一种实现策略:任务分类+多队列+并发线程。这种方式主要是试图利用现代 CPU 的多核并发性来解决遍历效率低的问题。例如我们将 10k 大小的任务队列分为 10 个任务队列,此时每一个任务队列的大小仅仅是 1k。在线程完全并发执行的情况下,将 10k 规模的问题简化为 1k 规模的问题。\n\n不过,多并发线程轮询的副作用非常大:线程是一种宝贵资源,如果一个系统有大量的定时调度任务,那么 CPU 会因为多条并发轮询线程而有着非常低的执行效率。\n\n现在我们知道一个定时任务框架需要如下几个要素:\n\n严格的数据结构:并不能基于简单的(有序或无序)的定时任务队列来存储定时任务,否则轮询线程的执行效率永远无法提高;\n简单的并发模型:CPU 线程是非常宝贵的资源,轮询线程并不能太多;\n时间轮算法解决了基于队列的定时任务执行模型的缺陷,下一节将详细介绍时间轮算法思想。\n\n2. 时间轮算法思想\n无论通过何种方式实现定时任务队列,最终需要向上层提供如下接口:\n\n添加定时任务;\n删除(取走)定时任务;\n执行定时任务;\n2.1 简单时间轮算法\n时间轮算法的核心是:轮询线程不再负责遍历所有任务,而是仅仅遍历时间刻度。时间轮算法好比指针不断在时钟上旋转、遍历,如果一个发现某一时刻上有任务(任务队列),那么就会将任务队列上的所有任务都执行一遍。\n\n时间轮算法不再将任务队列作为数据结构,其数据结构如下图所示(我们以小时为单位):\n\n\n\n图-1 时间轮数据结构示意图(黄色块为时间刻度,绿色块为任务)\n\n显而易见,时间轮算法解决了遍历效率低的问题。时间轮算法中,轮询线程遍历到某一个时间刻度后,总是执行对应刻度上任务队列中的所有任务(通常是将任务扔给异步线程池来处理),而不再需要遍历检查所有任务的时间戳是否达到要求。\n\n现在,即使有 10k 个任务,轮询线程也不必每轮遍历 10 k 个任务,而仅仅需要遍历 24 个时间刻度。\n\n一个以小时为单位的时间轮算法就这么简单地实现了。不过,小时作为时间单位粒度太大,我们有时候会希望基于分钟作为时间刻度。最直接的方式是增加时间刻度,每一天有 24 * 60 = 1440。此时时间轮的数据结构如下:\n\n\n\n图-2 时间精度为分钟的时间轮数据结构\n\n通过增加时间刻度,我们可以基于更精细的时间单位(分钟)来进行定时任务的执行。但是,这种实现方式有如下的缺陷:\n\n轮询线程遍历效率低问题:当时间刻度增多,而任务数较少时,轮询线程的遍历效率会下降,例如如果只有 50 个时间刻度上有任务,但却需要遍历 1440 个时间刻度。这违背了我们提出时间轮算法的初衷:解决遍历轮询线程遍历效率低的问题;\n浪费内存空间问题:在时间刻度密集,任务数少的情况下,大部分时间刻度所占用的内存空间是没有任何意义的。\n如果要将时间精度设为秒,那么整个时间轮将需要 86400 个单位的时间刻度,此时时间轮算法的遍历线程将遇到更大的运行效率低的问题。下面两个小节将着力解决此问题。\n\n2.2 带有 round 的时间轮算法\n我们发现,时间轮的时间刻度随着时间精度而增加并不是一个好的问题解决思路。现在,我们将时间轮的精度设置为秒,时间刻度个数固定为 60。每一个任务拥有一个 round 字段。\n\n轮询线程的执行逻辑是:每隔一秒处理一个时间刻度上任务队列中的所有任务,任务的 round 字段减 1,接着判断如果 round 字段的值变为 0,那么将任务移出任务队列,交给异步线程池来执行对应任务。如果是重复执行任务,那么再将任务添加到任务队列中。\n\n轮询线程遍历一次时间轮需要 60 秒。如果一个任务需要间隔 x 秒执行一次,那么其 round 字段的值为 x/60(整除),任务位于第 (x%60)(取余)个刻度对应的任务队列中。例如任务需要间隔 130 秒执行一次,那么 round 字段的值为 2,此任务位于第 10 号时间刻度的任务队列中。\n\n此时时间轮算法的数据结构如下图所示:\n\n\n\n图-3 时间精度为秒的 round 时间轮数据结构\n\n这种方式虽然简化了时间轮的刻度个数,但是并没有简化轮询线程运行效率不高的问题。时间轮每次处理一个时间刻度,就需要处理其上任务队列的所有任务。其运行效率甚至与基于普通任务队列实现的定时任务框架没有区别。\n\n2.3 分层时间轮算法\n分层的时间轮算法在生活中有对应的模型(艺术来源于生活~),那就是水表:\n\n此时,我们有秒、分钟、小时级别的三个时间轮,每一个时间轮分别有 60、60、24 个刻度。分层时间轮如下图所示:\n\n\n\n图-4 一种分层时间轮数据结构\n\n假设我们的任务需要在每天的 7:30:20 秒执行一次。任务首先添加于秒级别时钟轮的第 20 号刻度上,当其轮询线程访问到第 20 号刻度时,就将此任务转移到分钟级别时钟轮的第 30 号刻度上。当分钟级别的时钟轮线程访问到第 30 号刻度,就将此任务转移到小时级别时钟轮的第 7 号刻度上。当小时级别时钟轮线程访问到第 7 号刻度时,最终会将任务交给异步线程负责执行,然后将任务再次注册到秒级别的时间轮中。\n\n这种分层时钟轮算法设计具有如下的优点:\n\n轮询线程效率变高:首先不再需要计算 round 值,其次任务队列中的任务一旦被遍历,就是需要被处理的(没有空轮询问题);\n线程并发性好:虽然引入了并发线程,但是线程数仅仅和时钟轮的级数有关,并不随着任务数的增多而改变;\n如果任务按照分钟级别来定时执行,那么当分钟时间轮达到对应刻度时,就会将任务交给异步线程来处理,然后将任务再次注册到秒级别的时钟轮上。\n\n分层时间轮中的任务从一个时间轮转移到另一个时间轮,这类似于水表中小单位的表转弯一圈会导致高单位的表前进一个单位一样。"
},
{
"alpha_fraction": 0.7234042286872864,
"alphanum_fraction": 0.7248467206954956,
"avg_line_length": 30.16853904724121,
"blob_id": "475abdb38f30d09781b5a66643245136ec2d1562",
"content_id": "fd8af48e26b141c3f3c5bbf807fba08a16d49df1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3509,
"license_type": "permissive",
"max_line_length": 95,
"num_lines": 89,
"path": "/PythonSummary/python原理及特性/元类metaclass/元类metaclass.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#元类metaclass\n在wiki上面,metaclass是这样定义的:In object-oriented programming,\na metaclass is a class whose instances are classes.\nJust as an ordinary class defines the behavior of certain objects,\na metaclass defines the behavior of certain classes and their instances.\n\n也就是说metaclass的实例化结果是类,而class实例化的结果是instance。可以这么理解的:\nmetaclass是类似创建类的模板,所有的类都是通过他来create的(调用__new__),这使得你可以自由的控制\n创建类的那个过程,实现你所需要的功能。\n\n```\n#当定义class的时候,我们可以使用__metaclass__ attribute来指定用来初始化当前class的metaclass。如下面的例子所示:\nclass Foo(object):\n __metaclass__ = something\n [other statements...]\n#当Python试图创建class Foo的时候,Python会首先在class的定义中寻找__metaclass__ attribute。如果存在__metaclass__,\n#Python将会使用指定的__metaclass__来创建class Foo。如果没有指定的话,Python就会使用默认的type作为metaclas创建Foo。\n#如果class定义中不存在__metaclass__的话,Python将会寻找MODULE级别的__metaclass__。\n```\n\n__metaclass__可以是任何Python的callable,不必一定是一个正式的class。\n```python\n# the metaclass will automatically get passed the same argument \n# that is passed to `type()`\ndef upper_attr(class_name, class_parents, class_attr):\n '''Return a class object, with the list of its attribute turned into \n uppercase.\n '''\n # pick up any attribute that doesn't start with '__' and turn it into uppercase.\n uppercase_attr = {}\n for name, val in class_attr.items():\n if name.startswith('__'):\n uppercase_attr[name] = val\n else:\n uppercase_attr[name.upper()] = val\n \n # let `type` do the class creation\n return type(class_name, class_parents, uppercase_attr)\n\n\nclass Foo(object):\n # this __metaclass__ will affect the creation of this new style class\n __metaclass__ = upper_attr\n bar = 'bar'\n\n\nprint(hasattr(Foo, 'bar'))\n# False\n\nprint(hasattr(Foo, 'BAR'))\n# True\n\nf = Foo()\nprint(f.BAR)\n# 'bar'\n\n```\n接下来我们通过继承type的方式实现一个真正的class形式的metaclass。\n\n```python\nclass UpperAttrMetaclass(type):\n\tdef __new__(mcs, class_name, class_parents, class_attr):\n\t\tuppercase_attr = {}\n\t\tfor name, val in class_attr.items():\n\t\t\tif name.startswith('__'):\n\t\t\t\tuppercase_attr[name] = val\n\t\t\telse:\n\t\t\t\tuppercase_attr[name.upper()] = val\n\t\t# basic OOP. Reuse the parent's `__new__()`\n\t\t# == type.__new__(mcs, class_name, class_parents, uppercase_attr)\n\t\treturn super(UpperAttrMetaclass, mcs).__new__(mcs, class_name, class_parents, uppercase_attr)\n\nclass Foo(object):\n\t# this __metaclass__ will affect the creation of this new style class\n\t__metaclass__ = UpperAttrMetaclass\n\tbar = 'bar'\n```\n\nmetaclass主要的使用情况就是用来创建API。使用metaclass的一个典型的例子是Django ORM。\n```python\nclass Person(models.Model):\n name = models.CharField(max_length=30)\n age = models.IntegerField()\nguy = Person(name='bob', age='35')\nprint(guy.age)\n```\n其并不会返回一个IntegerField对象,而是会返回一个int,甚至可以直接从数据库中调用这个值。\n\n正是因为models.Model定义了__metaclass__,并使用了一些操作来将我们使用简单的语句定义的Person转化成了与数据库相应的域相联系的类,这种逻辑才成为可能。"
},
{
"alpha_fraction": 0.6970943212509155,
"alphanum_fraction": 0.7212170958518982,
"avg_line_length": 32.16363525390625,
"blob_id": "9f11a3bd5df8b0192fd07ebb2b00354c97231a78",
"content_id": "066d11dce216d33f48cef3a3d77ab6ccc25ec5ca",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6274,
"license_type": "permissive",
"max_line_length": 200,
"num_lines": 110,
"path": "/PythonSummary/python原理及特性/py2绑定方法对象和未绑定方法对象/py2绑定方法对象和未绑定方法对象.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# py2绑定方法对象和未绑定方法对象\n本篇主要总结Python2中绑定方法对象(Bound method object)和未绑定方法对象(Unboud method object)的区别和联系。 \n在Python 3.x中,unbound method的概念已经被取消了。取而代之的是 function对象。\n但是不妨碍它让我窥探到了Python语言动态特性的一角\n\n\n## 遇到的实际问题\n是由于公司特有的组合类,导致在继承的子类通过super()调用父类方法的时候,由于绑定方法对象(Bound method object)\n和未绑定方法对象(Unboud method object)的区别,***导致遇到 TypeError: unbound method xxx() must be called with Foo instance as \nfirst argument (got nothing instead)的问题。*** \n因此特此查找资料,总结学习相关的~~姿势~~知识。\n\nerror重现见[py2绑定方法对象和未绑定方法对象.py](py2绑定方法对象和未绑定方法对象.py)\n实际上\n```\n>>> type(Foo.foo)\n<type 'instancemethod'>\n>>> type(Foo().foo)\n<type 'instancemethod'>\n```\n为什么同样是实例方法(instancemethod),获取方式的不同,会导致获得不同的对象呢?\n\n## bound/unbound method 由来\n通过查看Foo.__dict__\n```\n>>> Foo.__dict__\n{'__dict__': <attribute '__dict__' of 'Foo' objects>, '__module__': '__main__', 'foo': <function foo at 0x00000000032CF4A8>, '__weakref__': <attribute '__weakref__' of 'Foo' objects>, '__doc__': None}\n>>> Foo.__dict__['foo']\n<function foo at 0x7ff33b42a5f0>\n```\n在Python中使用描述器(有翻译的链接)来表示具有“绑定”行为的对象属性,使用描述器协议方法来控制对具有绑定行为属性的访问,这些描述器协议方法包括:\n__get__()、__set__()和__delete__()。根据上面这段难以让人理解的描述,我们可以大胆的猜测,Foo的属性foo是一个描述器,它通过__get__()方法来控制对foo的访问。\n根据描述器协议方法descr.__get__(self, obj, type=None) --> value,我们尝试如下:\n```\n>>> Foo.__dict__['foo'].__get__(None,Foo)\n<unbound method Foo.foo>\n```\n也就是,调用Foo.foo时,Python会根据查找链从Foo.__dict__['foo']开始,然后查找type(Foo).__dict__['foo'],一路向上查找type(Foo)的所有基类。Foo.foo会被转换为Foo.__dict__['foo'].__get__(None,Foo)。 \n***也就是说,我们在代码中使用Foo.foo实际上会被转化成 Foo.__dict__['foo'].__get__(None,Foo)*** \ndescr.__get__(self, obj, type=None)其中,self参数在这里被赋予了None,所以没有给定实例,因此认为是未绑定(unbound) \n那么一个很简单的推理就是:如果self参数给定了实例对象,那么,得到的就是bound method,如下。\n```\n>>> Foo.__dict__['foo'].__get__(Foo(),Foo)\n<bound method Foo.foo of <__main__.Foo object at 0x7ff33b424d50>>\n\nFoo.foo.im_self # None\nFoo().foo.im_self # <__main__.Foo object at 0x0241E070>\n```\n因此在[py2绑定方法对象和未绑定方法对象.py](py2绑定方法对象和未绑定方法对象.py)中\n同样使用类名.方法名()调用时,所报的错误相同。但是可以可以通过Foo.foo(Foo())这种方式来进行手动的绑定\n但是在使用实例名.方法名()调用时,foo_one是可以调用成功的。 \n原因在于当使用Foo().foo_one()调用时,Python做了如下修改: \n```\n>>> Foo.foo_one(Foo())\ncall foo_one\n```\n \n所以 有的人把foo()这种参数列表中没有self的方法称为类方法,而把带有self的方法称为实例方法,根据上面的描述可以发现,这种划分是错误的。 \n\n## Pyhon 类方法\n例子见[py类方法.py](py类方法.py)\n看到这里会发现,在Python中定义方法,总要带两个参数self或者cls。其中通过self限定的method必须使用实例才能调用。\n\n## Python 静态方法\n除了类方法,还有静态方法,请看下面这个例子:\n```\n>>> class Foo(object):\n... @staticmethod\n... def foo():\n... print 'call foo'\n... \n>>> Foo.foo()\ncall foo\n>>> Foo().foo()\ncall foo\n```\n静态方法可以通过类名.方法名()和实例.方法名()的形式调用。\n查看type结果如下:\n```\n>>> type(Foo.foo)\n<type 'function'>\n```\n可以看到,静态方法的类型是function,而类方法的类型是instancemethod。\n\n## Python语言的动态特性\n这么设计其实是为了实现Python的动态特性,我们来看一个例子:\n```\nclass A(object):\n def foo(self):\n return 'A'\n\ndef foo(self):\n return 'B'\n\na = A()\n\nprint foo, A.foo.im_func, a.foo.im_func # <function foo at 0x0230A2B0> <function foo at 0x0239A4B0> <function foo at 0x0239A4B0>\nA.foo = foo\nprint foo, A.foo.im_func, a.foo.im_func # <function foo at 0x0230A2B0> <function foo at 0x0230A2B0> <function foo at 0x0230A2B0>\nprint a.foo() # B\nprint A.foo(a) # B\n```\n这段代码其实是游戏中常用的hotfix的一种实现原来的demo。所谓hotfix,是指在玩家不知情的情况下,替换掉客户端脚本代码中的部分逻辑,实现修复bug的目的。 \n对于静态语言,进行这种运行时修改代码比较麻烦,而且像ios这样的平台禁止了在数据段执行代码,也就是你无法动态替换dll,使用native的语言或者C#的几乎不能方便地进行hotfix,这也是脚本语言在游戏行业里(尤其国内)面非常常用的原因。 \n上述例子中,A.foo = foo这句代码替换了A的__dict__中的foo对象,由于方法对象都是在使用时动态生成的,因此无论是新创建的对象还是已经在内存中存在的对象,都会在调用方法的时候重新生成方法对象,它们的im_func属性就指向了类中的新的属性对象。 \n\n### 动态的代价,就是慢。\nC++静态语言的方法调用,即使考虑继承的情况,也不过是一次虚表的查询操作,而python中不但有各种__dict__检索,而且要通过__mro__属性向继承的父类进行搜索,这块具体的过程在后面进行分析。然后加上对象的创建过程,影响效率可想而知。 \n因此,我们在代码中常用的一种优化是: \n***如果在一段代码中有对于对象属性的频繁访问,在不会修改其内容的前提下,通常会使用一个局部变量保存属性的应用供后面的代码逻辑使用。***\n"
},
{
"alpha_fraction": 0.7532956600189209,
"alphanum_fraction": 0.7589454054832458,
"avg_line_length": 24.285715103149414,
"blob_id": "5a8acde32efe6ecf67860db172833a0fa74782b8",
"content_id": "6d6ed9f82956978ab258baa6da9cf1f8b6d53730",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 909,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 21,
"path": "/JavaSummary/src/单例模式/EnumSingleton.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 单例模式;\n\n//在effective java(这本书真的很棒)中说道,最佳的单例实现模式就是枚举模式。利用枚举的特性,让JVM来帮我们保证线程安全和单一实例的问题。\n//1默认枚举实例的创建是线程安全的\n//2以往的单例实现了序列化接口,那么就再也不能保持单例的状态了.因为readObject()方法一直返回一个\n//新的对象.使用radResolve()来避免此情况发生.枚举单例 对序列化有保证\n//3采用反射来创建实例时.可通过AccessibleObject.setAccessible(),通过反射机制来调用私有\n//构造器.那么枚举可以防止这种创建第二个实例的情况发生.\npublic enum EnumSingleton {\n INSTANCE;\n\n public EnumSingleton getInstance() {\n return INSTANCE;\n }\n}\n\nclass run{\n public static void main(String[] args) {\n EnumSingleton.INSTANCE.getInstance();\n }\n}\n"
},
{
"alpha_fraction": 0.7636932730674744,
"alphanum_fraction": 0.773082971572876,
"avg_line_length": 29.452381134033203,
"blob_id": "a2be57b4d9b6dd73125f578eb14745728a253d9a",
"content_id": "b53e72b6b9ac4fbe6676edb8ff77559b0b529c94",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2274,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 42,
"path": "/PythonSummary/python原理及特性/import/import原理.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# import原理\n## 包(package)和模块(module)\n包是指带__init__.py的目录,模块是指单个.py文件。\n## import xxx\n1.首先看sys.modules(sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules将自动记录该模块。\n当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法.)里是否已经存在xxx,\n是则直接返回,否则遍历sys.path,查找加载名为xxx的python包或模块。 \n2.加载可以认为就是执行对应的.py文件(对包来说就是__init__.py),并以执行的结果填充xxx的__dict__ 。\n3.执行一个局部变量赋值。这样在import xxx的上下文里就能以xxx这个变量名来使用它了。\nps:注意xxx可以是com.org.cn这种复合形式,会按序加载。顺利的话com、com.org、com.org.cn都会放到sys.modules里,但是,注意,这种情况下上面最后的那个局部变量引用到的是com,也正因此com.org.cn这么写才不会报错。\n## from xxx import yyy\n先对xxx执行上述1,然后在xxx的__dict__ 里查找yyy,找到则跟上述1最后一步一样,执行一个局部变量赋值。 \n如果没找到,而xxx又是一个package,则尝试在xxx的__path__下加载yyy模块,加载成功的话会把yyy加到xxx的__dict__ ,\n但是,**注意,加到sys.modules里的key不是yyy,而是xxx.yyy。** \n## 错误例子\n1.循环import\n加载模块是先在sys.modules里占了个坑,再执行.py文件来填充这个模块的__dict__,所以在b.py里import a的时候,\n其实直接从sys.modules里返回了一个a的半成品,那个半成品只走到了from b import b_var那一步,还没设置a_var,所以就报错了。\n```python\n#a.py\nfrom b import b_v\na_v='1'\n# b.py\nfrom a import a_v\nb_v='2'\n\n```\n2.同一个module存在两份不同的实例\nfrom xxx import yyy,并不是把yyy放到sys.modules里。胡乱修改sys.path 就可能导致这个错误\n```python\n#com/sub/a.py\nfrom com.sub import a\n>>>a\n<moudule 'com.sub.a' from 'com/sub/a,py'>\nimport sys\nsys.path.append('./com/sub')\nimport a as a2\n>>>a2\n<moudule 'a' from './com/sub/a,pyc'>\na==a2\n>>>False\n```"
},
{
"alpha_fraction": 0.5254237055778503,
"alphanum_fraction": 0.6271186470985413,
"avg_line_length": 22.600000381469727,
"blob_id": "fd2117645e480b98a4e76b6610de2702247f579a",
"content_id": "60ad385bcd8c1ce055960ca8663d2b6cbce3a644",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 118,
"license_type": "permissive",
"max_line_length": 28,
"num_lines": 5,
"path": "/PythonSummary/python原理及特性/新式类和经典类(旧式类)的区别/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python \n# -- coding: utf-8 -- \n# Time : 2022/4/27 14:52\n# Author : zhou pengcheng\n# ProjectName: PythonSummary\n"
},
{
"alpha_fraction": 0.6100746393203735,
"alphanum_fraction": 0.6194030046463013,
"avg_line_length": 14.199999809265137,
"blob_id": "18c8ce9b50d4691774189681fa4e46e665a2415b",
"content_id": "2fb579c1b252c7e0bcab830d50b263db19331fd4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 664,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 35,
"path": "/JavaSummary/src/List/list带值的初始化/List初始化.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-List.list带值的初始化\n总结list带值的初始化\n\n## 方法1\n使一个匿名的内部类的一个实例初始值设定项\n```java\nArrayList<String> list = new ArrayList<String>() {{\n add(\"A\");\n add(\"B\");\n add(\"C\");\n}}\n\n```\n\n## 方法2\n这样的话这个list的size就固定了,不能再add了,要注意。\n```java\n List<String> test2 = Arrays.asList(\"xxx\",\"yyy\",\"zzz\");\n``` \n用ArraysList报错\n```java\nArrayList<String> test2 = Arrays.asList(\"xxx\",\"yyy\",\"zzz\");\n```\n\n\n## 方法3\n```java\nList<String> name = new ArrayList();\n\nname.add(\"xxx\");\n\nname.add(\"yyy\");\n\nname.add(\"zzz\");\n```\n\n\n\n\n"
},
{
"alpha_fraction": 0.7513043284416199,
"alphanum_fraction": 0.7530434727668762,
"avg_line_length": 25.090909957885742,
"blob_id": "72bfd0447741f750775b6ddfede127bbd9460990",
"content_id": "db158106112fbc144a72d664cfcd4cbde198ab77",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 695,
"license_type": "permissive",
"max_line_length": 132,
"num_lines": 22,
"path": "/JavaSummary/out/production/JavaSummary/非空注解/annotation.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-@NotEmpty、@NotBlank、@NotNull的区别\n总结三种非空注解\n\n## @NotEmpty\n@NotEmpty的String类、Collection、Map、数组,是不能为null或者长度为0的(String、Collection、Map的isEmpty()方法)。\n\n## @NotBlank\n\nValidate that the annotated string is not {@code null} or empty.\nThe difference to {@code NotEmpty} is that trailing whitespaces are getting ignored.\n@author Hardy Ferentschik\n\n\n\"The difference to {@code NotEmpty} is that trailing whitespaces are getting ignored.\"-->>纯空格的String也是不符合规则的。所以才会说@NotBlank用于String。\n\n## @NotNull\n/**\n* The annotated element must not be {@code null}.\n* Accepts any type.\n*\n* @author Emmanuel Bernard\n*/\n\n"
},
{
"alpha_fraction": 0.6346040964126587,
"alphanum_fraction": 0.6469208002090454,
"avg_line_length": 27.41666603088379,
"blob_id": "b65bc9d7b996d0f134c629ffdf4646109b18c1b7",
"content_id": "fbb8eeb93da5c5d24fc726b1d8d361a1dd817003",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1837,
"license_type": "permissive",
"max_line_length": 198,
"num_lines": 60,
"path": "/PythonSummary/python原理及特性/connectHive/connectHive.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Python3 链接Hive填坑\nPython2使用impyla轻松链接Hive,Python3各种错误\n\n## install\n```bash\npip install six\npip install bit_array\npip install thriftpy (##注意: thrift (on Python 2.x) or thriftpy (on Python 3.x))\npip install thrift_sasl \npip install sasl\n```\n\n## error1\n```bash\n'TSocket' object has no attribute 'isOpen'\n```\n控制 thrift_sasl 版本0.2.1 \n\n## error2\n```bash\nthriftpy.transport.TTransportException: TTransportException(message=\"Could not start SASL: b'Error in sasl_client_start (-4) SASL(-4): no mechanism available: Unable to find a callback: 2'\", type=1)\n```\n其中,authMechanism的值取决于hive-site.xml里的配置 \n```xml\n<name>hive.server2.authentication</name> \n<value>NOSASL</value> \n```\nauth_mechanism 这个参数的取值可以是:’NOSASL’, ‘PLAIN’, ‘KERBEROS’, ‘LDAP’. \nconnect加上参数 “auth_mechanism”\n```python\nconn = connect(host='*',port = 10000,auth_mechanism='NONE')\n```\n## error3\n```bash\nThriftParserError: ThriftPy does not support generating module with path in protocol ‘c’\n```\n定位到 \\Lib\\site-packages\\thriftpy\\parser\\parser.py\n```python\nif url_scheme == '':\n with open(path) as fh:\n data = fh.read()\nelif url_scheme in ('http', 'https'):\n data = urlopen(path).read()\nelse:\n raise ThriftParserError('ThriftPy does not support generating module '\n 'with path in protocol \\'{}\\''.format(\n url_scheme))\n```\n修改为\n```python\nif url_scheme == '':\n with open(path) as fh:\n data = fh.read()\nelif url_scheme in ('http', 'https'):\n data = urlopen(path).read()\nelse:\n raise ThriftParserError('ThriftPy does not support generating module '\n 'with path in protocol \\'{}\\''.format(\n url_scheme))\n```\n"
},
{
"alpha_fraction": 0.5838926434516907,
"alphanum_fraction": 0.6174496412277222,
"avg_line_length": 17.625,
"blob_id": "ea703a1a7678e2a35a17fc53ad386db5e00bf288",
"content_id": "7085049f1f486213a2885b9ffc51586a1d8baa1d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 463,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 24,
"path": "/JavaSummary/src/动态代理/JDK动态代理/UserServiceImpl.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 动态代理.JDK动态代理;\n\n/**\n * @Program: test\n * @Author: zhoupengcheng03\n * @Package: PACKAGE_NAME\n * @ClassName: UserServiceImpl\n * @Description:\n * @Create: 2022-02-25 11:06\n **/\npublic class UserServiceImpl implements UserService {\n\n @Override\n public int insert() {\n System.out.println(\"insert\");\n return 0;\n }\n\n @Override\n public String query() {\n System.out.println(\"query\");\n return null;\n }\n}\n"
},
{
"alpha_fraction": 0.767276406288147,
"alphanum_fraction": 0.7764227390289307,
"avg_line_length": 31.83333396911621,
"blob_id": "0458af435a0ead2f0017f9de2229bbf9e5d13eac",
"content_id": "05b7aa5fd4290729ee413012e2b4f8a13765c24a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1868,
"license_type": "permissive",
"max_line_length": 198,
"num_lines": 30,
"path": "/PythonSummary/Mongo/MongoDB和MySQL的区别.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#MongoDB和MySQL的区别\n##mongodb的所有数据实际上是存放在硬盘的,所有要操作的数据通过mmap的方式映射到内存某个区域内\nmmap 系统调用使得进程之间通过映射同一个普通文件实现共享内存。普通文件被映射到进程地址空间后,进程可以像访问普通内存一样对文件进行访问,不必再调用。 read(),write()等操作。mmap 并不分配空间, 只是将文件映射到调用进程的地址空间里, 然后你就可以用 memcpy 等操作写文件, 而不用 write() 了.写完后用 msync() 同步一下, 你所写的内容就保存到文件里了\nmysql硬盘数据库\n## MongoDB的free schema。如果想给一个表结构添加一个字段,会很容易的。终于不会像 MySQL 上 alter table 那样提心吊胆了(因为如果表比较大,会很耗时的哦)。\nMySQL,在表中添加一列时发生了什么(相同处理速度差不多)\n根据指定的算法,该操作可涉及以下步骤: \n\n1.创建表的完整副本 \n2.创建临时表,以处理并发数据操控语言 (DML) 操作 \n3.重建此表的所有索引 \n4.应用并发 DML 更改时应用表锁定 \n5.减慢并发 DML 吞吐量 \nMySQL对两者的操作应该是相同的。消耗可见是很大的。 \n## 单文件支持事务,多文件和分布式事务4.0\nmongo事务和会话(Sessions)关联,一个会话同一时刻只能开启一个事务操作,当一个会话断开,这个会话中的事务也会结束。\n```\nvar session = db.getMongo().startSession();\nsession.startTransaction({readConcern: { level: 'majority' },writeConcern: { w: 'majority' }});\nvar coll = session.getDatabase('test').getCollection('user');\n\ncoll.update({name: 'Jack'}, {$set: {age: 18}})\n\n// 成功提交事务\nsession.commitTransaction();\n\n// 失败事务回滚\nsession.abortTransaction();\n\n```"
},
{
"alpha_fraction": 0.6793193817138672,
"alphanum_fraction": 0.6793193817138672,
"avg_line_length": 23.677419662475586,
"blob_id": "75a6615de23f6c7fb19fabcf845ab25eacb12d52",
"content_id": "851029f088665d5cff8eb234dc513da8480c0989",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1568,
"license_type": "permissive",
"max_line_length": 72,
"num_lines": 31,
"path": "/PythonSummary/设计模式/装饰器模式/装饰器模式.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#装饰器模式\n装饰器本质上是一个 Python 函数或类,它可以让其他函数或类在不需要做任何代码修改的前提下增加额外功能,装饰器的返回值也是一个函数/类对象。\n它经常用于有切面需求的场景,比如:插入日志、性能测试、事务处理、缓存、权限校验等场景,装饰器是解决这类问题的绝佳设计。\n有了装饰器,我们就可以抽离出大量与函数功能本身无关的雷同代码到装饰器中并继续重用。 \n<font color=red>*概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。*</font>\n<font color=red>*不用更改原函数的代码前提下给函数增加新的功能*</font>\n## 装饰器的一般结构\n```python\ndef decorator(function):\n '''\n 第一层函数为装饰器名称\n function:参数,即需要装饰的函数\n return:返回值wrapper,为了保持与原函数参数一致\n '''\n def wrapper(*arg,**args):\n '''\n 内层函数,这个函数实现“添加额外功能”的任务\n *arg,**args:参数保持与需要装饰的函数参数一致,这里用*arg和**args代替\n '''\n #这里就是额外功能代码\n function() #执行原函数\n #这里就是额外功能代码\n return wrapper\n```\n## 函数装饰器\n函数装饰器可以装饰函数,也可以装饰类。\n\n\n\n## 类装饰器\n"
},
{
"alpha_fraction": 0.699386477470398,
"alphanum_fraction": 0.7239263653755188,
"avg_line_length": 30.45161247253418,
"blob_id": "3d5985dc52a14df26704dd3e6a8cfbbe6ca41a13",
"content_id": "7e8978985afb79cd255ee94886245f594f9a1683",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1778,
"license_type": "permissive",
"max_line_length": 145,
"num_lines": 31,
"path": "/JavaSummary/out/production/JavaSummary/TopK/topk.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-topk\n总结三种topK方法以及时间复杂度分析\n\n## 方法1\n先将原始数据排序,然后截取前k个数.\n时间复杂度:O(n*logn)+O(k)=O(n*logn)。\n\n## 方法2\n最小堆.\n\n维护容量为k的最小堆.根据最小堆性质,堆顶一定是最小的,如果小于堆顶,则直接pass,如果大于堆顶,则替换掉堆顶,并heapify整理堆,其中heapify的时间复杂度是logk.\n时间复杂度:O(k+(n-k)*logk)=O(n*logk)\n\n## 方法3\nQuick select算法通常用来在未排序的数组中寻找第k小/第k大的元素。其方法类似于Quick sort。Quick select和Quick sort都是由Tony Hoare发明的,因此Quick select算法也被称为是Hoare's selection algorithm。\nQuick select算法因其高效和良好的average case时间复杂度而被广为应用。Quick select的average case时间复杂度为O(n),然而其worst case时间复杂度为O(n^2)。\n\n## Quick Select 复杂度分析\n一般来说,因为我们才用了随机选取pivot的过程,平均来看,我们可以假设每次pivot都能选在中间位置。设算法时间复杂度为T(n)。在第一层循环中,我们将pivot与n个元素进行了比较,这个时间为cn 。\n所以第一步时间为:T(n) = cnc + T(n/2)。其中T(n/2)为接下来递归搜索其中一半的子数组所需要的时间。\n在递归过程中,我们可以得到如下公式: \nT(n/2) = c(n/2) + T(n/4) \nT(n/4) = c(n/4) + T(n/8) \n... \nT(2) = 2*c + T(1) \nT(1) = 1*c \n将以上公式循环相加消除T项可以得到: \nT(n) = c(n + n/2 + n/4 + n/8 + ... + 2 + 1) = 2n = O(n) \n因此得到Quick Select算法的时间复杂度为O(n)。\n## Quick Select 空间复杂度\n算法没有使用额外空间,swap操作是inplace操作,所以算法的空间复杂度为O(1)。\n\n\n\n"
},
{
"alpha_fraction": 0.3507462739944458,
"alphanum_fraction": 0.3805970251560211,
"avg_line_length": 10.083333015441895,
"blob_id": "fefd1b28364ac91d93b78ffce28261925a65b91f",
"content_id": "077841b0a312613acbafdd92b9efdd19f27f0421",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 230,
"license_type": "permissive",
"max_line_length": 16,
"num_lines": 12,
"path": "/JavaSummary/out/production/JavaSummary/正则表达式/RegularExpression.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-正则表达式\n正则表达式\n\n## 正则表达式\n[] : 字符集合\n() : 分组\n? : 重复 0 ~ 1 次\n+ : 重复 1 ~ n 次\n* : 重复 0 ~ n 次\n. : 任意字符\n\\\\. : 转义后的 .\n\\\\d : 数字\n\n"
},
{
"alpha_fraction": 0.7425742745399475,
"alphanum_fraction": 0.8075764179229736,
"avg_line_length": 32.18571472167969,
"blob_id": "75847c4e7bb800dddab5f215348d303e56cdcee1",
"content_id": "80c2c6f7f69d8ec3d43e6bae55b721484ffa7393",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4837,
"license_type": "permissive",
"max_line_length": 172,
"num_lines": 70,
"path": "/PythonSummary/网络编程/Protobuf/ProtoBufTheory.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Learn Google.ProtoBuf Theory Summary\nprotobuf会对proto协议文件进行序列化,最终转换成二进制数据,在这个转换过程中,protobuf做了一些优化,使得转换出来的二进制数据尽可能的小,同时也具有安全,编解码快等特点。\n## 消息类型编码\nprotobuf会把message转成一系列的key-value,key就是字段号,value就是字段值\n```\n[tag1][value1][tag2][value2][tag3][value3]... \n```\n解码时,会从左往右解析每一个key-value,假如遇到某个key-value无法解析了,那么就直接跳过,不会影响到其它key-value的解析,因此如果你加了新字段,生成字节流,然后用旧版本解析,这时它还是能够解析出旧版本的字段的,新字段只是被忽略而已,这就是protobuf的向后兼容。 \n另外注意到,实际上存储的是tag-value,而不是key-value,根据key转换成tag \n```\ntag = (key << 3) | wire_type(数据类型对应的整数值)\n```\n\n## 可变长编码类型\nint32这些类型它并不是固定占用4个字节的 \nprotobuf具体的实现方法,就是把每个字节的最高位做为标志位,1表示当前字节不是最末尾的字节,0表示当前字节是最末尾的字节,举个例子,protobuf将404表示为:\n```\n10010100 00000011\n```\n它只占用两个字节,第一个字节的最高位为1,表示还需要读取下个字节,而第二个字节的最高位为0,表示不需要再读取下个字节了 \nprotobuf的解码是这样的:\n* 去掉最高位,得到每个字节的低7位,也就是0010100 0000011。\n* 然后倒序,得到11 0010100。\n* 转成十进制,也就是404。\n## 负数可变长编码类型\n因为对于比较常用(数值比较大)的负数来说,转成补码后会有很多个1,也就是说占用的字节会比较多,这样如果还采用上面那种方式编码,就得不偿失了,因此Google又新增加了一种数据类型,叫sint,专门用来处理这些负数,其实现原理是采用zigzag编码,zigzag编码的映射函数为:\n```\nZigZag(n) = (n << 1) ^ (n << k),k为31或者63\n```\n最终的效果就是把所有的整数映射为正整数,比如0->0, -1->1, 1->1, -2->3这样子,然后就可以用上面所说的编码方式进行编码了,解码时通过逆函数解析即可\n## 固定字节数类型\n固定字节数,比如fixed32,它固定占用4个字节。而且可以看到,protobuf中float和double也是固定占用4个字节和8个字节,并没有实现压缩。\n### string类型\n按照固定的格式编码,格式为:\n```\nvalue = length(content占用的字节数,采用可变长编码) + content(string的具体内容)\n```\n## Protobuf实例解析\n```\nsyntax=\"proto3\";\n// option java_outer_classname = \"ProtoBufAnimal\"\nmessage Animal {\n\tint32 age = 1;\n\tstring name = 2;\n}\n```\n最终生成的二进制数据为:080C120468616861。\n下面开始分析:\n\n* 首先message是通过tag-value存储的,所以这里其实就是两个tag-value。\n* 第一个tag-value对应的是age字段,其tag按照公式(key << 3) | wire_type计算,key为1,wire_type为0,最终结果为08,而value就是12采用可变长编码的结果,占用一个字节,最终结果为0C,因此第一个tag-value对应的就是前两个字节080C。\n* 第二个tag-value对应的是name字段,其tag同样按照公式计算,key为2,wire_type为2,最终结果为12,value按照string数据类型的编码格式可知,刚开始是长度,后面是内容,因此先看内容,haha的十六进制表示为68616861,占用4个字节,所有长度就是4,也就是04,整个value表示为0468616861。\n* 最后把两个tag-value拼接起来,就是080C120468616861,跟运行程序生成的一致。\n\nprotobuf最终生成的二进制数据有个特点就是紧凑,几乎不包含冗余数据,因此数据也会比较小。\n\n## Protobuf优点:\n* 小:生成的字节流采用了各种压缩方式,相对xml和json这类文件更小。\n\n\n* 快:编解码基本都是位运算,也没有复杂的嵌套关系,速度快。\n\n\n* 安全:这里的安全,是指protobuf没有把字段名写入到字节流里,只是写入了字段号信息。另外,相对于xml和json来说,因为被编码成二进制,破解成本增大。\n\n\n* 向后兼容:解析器遇到无法解析的字段,会自动跳过,不影响其它字段的解析,因此新增字段生成的字节流还是可以用旧版本的proto文件代码解析。\n\n\n* 语言无关和平台无关:把proto文件转成字节流,可以采用不同的语言,比如后台用C++,客户端用Java或者Python等,字节流转具体对象可以根据需要自行选择语言。也就是说整个编解码过程完全不依赖某种语言的特性。\n"
},
{
"alpha_fraction": 0.5868358612060547,
"alphanum_fraction": 0.6122125387191772,
"avg_line_length": 18.86614227294922,
"blob_id": "ee4d20e18eda83e83b9503916d03cf2356b472e7",
"content_id": "99e9d8b1bab316ed6caba16a17bf1d443102132e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2848,
"license_type": "permissive",
"max_line_length": 108,
"num_lines": 127,
"path": "/PythonSummary/并发编程/进程池/ProcessPool.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Python 并发编程\n最简单的进程池\n```python\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\ndef task(name):\n print(\"name\",name)\n time.sleep(1)\n\nif __name__ == \"__main__\":\n start = time.time()\n ex = ProcessPoolExecutor(2)\n\n for i in range(5):\n ex.submit(task,\"safly%d\"%i)\n ex.shutdown(wait=True)\n\n print(\"main\")\n end = time.time()\n print(end - start)\n```\n```\nE:\\python\\python_sdk\\python.exe \"E:/python/py_pro/4 进程池.py\"\nname safly0\nname safly1\nname safly2\nname safly3\nname safly4\nmain\nrun time:3.212218999862671\n```\nProcessPoolExecutor(2)创建一个进程池,容量为2,循环submit出5个进程,然后就在线程池队列里面,执行多个进程,\nex.shutdown(wait=True)意思是进程都执行完毕,在执行主进程的内容\n## shutdown\n进程都执行完毕,在执行主进程的内容\n上述如果改为ex.shutdown(wait=False)\n```\nmain\n0.01500844955444336\nname safly0\nname safly1\nname safly2\nname safly3\nname safly4\n```\n## 使用submit异步调用\n异步调用: 提交/调用一个任务,不在原地等着,直接执行下一行代码\n```python\n\n# from multiprocessing import Process,Pool\nfrom concurrent.futures import ProcessPoolExecutor\nimport time, random, os\n\ndef piao(name, n):\n print('%s is piaoing %s' % (name, os.getpid()))\n time.sleep(1)\n return n ** 2\n\n\nif __name__ == '__main__':\n p = ProcessPoolExecutor(2)\n objs = []\n start = time.time()\n for i in range(5):\n obj = p.submit(piao, 'safly %s' % i, i) # 异步调用\n objs.append(obj)\n\n p.shutdown(wait=True)\n print('main', os.getpid())\n for obj in objs:\n print(obj.result())\n\n stop = time.time()\n print(stop - start)\n```\n## result\nresult()是阻塞式的,所以返回结果的到来以后才继续进行下面的代码\n```python\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\nimport random\n# executor = ThreadPoolExecutor()\nexecutor = ProcessPoolExecutor()\n\n\ndef sayhello(k, v):\n\tx = \"hello: \"\n\tfor i in xrange(2):\n\t\tif i:\n\t\t\tx += ' v:' + v\n\t\telse:\n\t\t\tx += 'k:'+k\n\t\ttime.sleep(random.randint(1, 3))\n\n\tprint('result {} in thread:{}'.format(x , os.getpid()))\n\n\treturn x\n\n\ndef main():\n\tstart3 = time.time()\n\tseed = {\"a\": \"a\", \"b\": \"a\", \"q\": \"a\", \"w\": \"a\", \"e\": \"a\", \"r\": \"a\", \"t\": \"a\", \"y\": \"a\", \"u\": \"a\", \"i\": \"a\",\n\t \"o\": \"a\", \"p\": \"a\", \"s\": \"a\", \"d\": \"f\", \"g\": \"a\", \"h\": \"l\"}\n\n\tfutures = [executor.submit(sayhello, k, v) for k, v in seed.iteritems()]\n\n\tfor i in futures:\n\t\tprint('i', i.done())\n\t\tprint i.result()\n\n\n# cnt = len(futures)\n# for future in futures:\n# \tdata = future.result()\n# \tprint('data:', data)\n# \tcnt -= 1\n# \tprint('cnt:', cnt)\n# \tif cnt == 0:\n# \t\tprint('all compeleted')\n# \t\tend3 = time.time()\n# \t\tprint(\"run_time: \" + str(end3 - start3))\n\n\nif __name__ == '__main__':\n\tmain()\n\tprint 'end'\n```"
},
{
"alpha_fraction": 0.4447852671146393,
"alphanum_fraction": 0.44631901383399963,
"avg_line_length": 12.893616676330566,
"blob_id": "e70e0aa87a69f142582fba4e8fd36c5623bb3dd4",
"content_id": "9a120a5e9f9d09fab87e9287ac2732f27167bd5d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 658,
"license_type": "permissive",
"max_line_length": 36,
"num_lines": 47,
"path": "/C++Summary/虚继承/虚继承.cpp",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n\nusing namespace std;\n//基类\n\nclass D\n{\npublic:\n D() { cout << \"D()\" << endl; }\n ~D() { cout << \"~D()\" << endl; }\nprotected:\n int d;\n};\n\nclass B :virtual public D\n{\npublic:\n B() { cout << \"B()\" << endl; }\n ~B() { cout << \"~B()\" << endl; }\nprotected:\n int b;\n};\n\nclass A :virtual public D\n{\npublic:\n A() { cout << \"A()\" << endl; }\n ~A() { cout << \"~A()\" << endl; }\nprotected:\n int a;\n};\n\nclass C :public B, public A\n{\npublic:\n C() { cout << \"C()\" << endl; }\n ~C() { cout << \"~C()\" << endl; }\nprotected:\n int c;\n};\n\nint main()\n{\n C c; //D, B, A ,C\n cout << sizeof(c) << endl;\n return 0;\n}"
},
{
"alpha_fraction": 0.47714948654174805,
"alphanum_fraction": 0.5019364953041077,
"avg_line_length": 20.516666412353516,
"blob_id": "9949ce7402452e1df0823f869715294d2e02ea54",
"content_id": "36256900d47f5060470f75966770caabc832303b",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1295,
"license_type": "permissive",
"max_line_length": 111,
"num_lines": 60,
"path": "/PythonSummary/并发编程/进程池/result阻塞.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : result阻塞.py\n@Time : 2020/11/20 14:31\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nimport random\nfrom concurrent.futures import ProcessPoolExecutor\nimport time\n\n# executor = ThreadPoolExecutor()\nexecutor = ProcessPoolExecutor()\n\n\ndef sayhello(k, v):\n x = \"hello: \"\n for i in xrange(2):\n if i:\n x += ' v:' + v\n else:\n x += 'k:' + k\n time.sleep(random.randint(1, 3))\n\n print('result {} in thread:{}'.format(x, os.getpid()))\n\n return x\n\n\ndef main():\n start3 = time.time()\n seed = {\"a\": \"a\", \"b\": \"a\", \"q\": \"a\", \"w\": \"a\", \"e\": \"a\", \"r\": \"a\", \"t\": \"a\", \"y\": \"a\", \"u\": \"a\", \"i\": \"a\",\n \"o\": \"a\", \"p\": \"a\", \"s\": \"a\", \"d\": \"f\", \"g\": \"a\", \"h\": \"l\"}\n\n futures = [executor.submit(sayhello, k, v) for k, v in seed.iteritems()]\n\n for i in futures:\n print('i', i.done())\n print i.result()\n\n\n# cnt = len(futures)\n# for future in futures:\n# \tdata = future.result()\n# \tprint('data:', data)\n# \tcnt -= 1\n# \tprint('cnt:', cnt)\n# \tif cnt == 0:\n# \t\tprint('all compeleted')\n# \t\tend3 = time.time()\n# \t\tprint(\"run_time: \" + str(end3 - start3))\n\n\nif __name__ == '__main__':\n main()\n print 'end'\n"
},
{
"alpha_fraction": 0.5958904027938843,
"alphanum_fraction": 0.6183953285217285,
"avg_line_length": 34.2068977355957,
"blob_id": "9e84e021392886189ca278d1043e7e0125e3d452",
"content_id": "ff845ff4bb41682a2bfc2f1e7168e05adbd06161",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1334,
"license_type": "permissive",
"max_line_length": 144,
"num_lines": 29,
"path": "/BatSummary/多进程/多进程.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Bat批处理文件中用于计时的一个小工具\n[stackoverflow](https://stackoverflow.com/questions/43754374/execute-multiple-batch-files-concurrently-and-monitor-if-their-process-is-comple) \n[多进程](多进程.bat)\n```commandline\n@echo off\n setlocal enableextensions disabledelayedexpansion\n\n for %%t in (\"%temp%\\%~nx0.%random%%random%%random%.tmp\") do (\n\n echo Starting subprocesses\n 9> \"%%~ft\" (\n start \"\" cmd /c subprocess1.bat ^>log1.log\n start \"\" cmd /c subprocess2.bat ^>log2.log\n start \"\" cmd /c subprocess3.bat ^>log3.log\n start \"\" cmd /c subprocess4.bat ^>log4.log\n start \"\" cmd /c subprocess5.bat ^>log5.log\n )\n\n echo Waiting for subprocesses to end\n break | >nul 2>nul (\n for /l %%a in (0) do @(ren \"%%~ft\" \"%%~nxt\" && exit || ping -n 2 \"\")\n )\n echo Done \n\n ) & del \"%%~ft\"\n```\n这将生成一个临时文件,并通过创建到该文件的重定向来锁定它,并在此重定向中启动批处理子进程。 当所有子进程结束时,重定向将关闭,并且临时文件将被删除。\n\n子进程运行时,文件被锁定,我们可以测试一下尝试重命名文件。 如果我们可以重命名文件,则子进程已经结束,否则某些进程仍在运行。\n\n"
},
{
"alpha_fraction": 0.6604413986206055,
"alphanum_fraction": 0.6604413986206055,
"avg_line_length": 25.81818199157715,
"blob_id": "ffbf8ac834e5ab9043e945f22c923644f6e77d3f",
"content_id": "13d95fd91c3fe00ab4067c069036e45c51db61c6",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 693,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 22,
"path": "/JavaSummary/out/production/JavaSummary/Optional/useOptional.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-使用 Optional 处理 null\n开头拿数据的时候可能会忘记写 if (Obj != null) —— 可能会导致后面一系列的判断都需要判断null NullPointerException\n\n## Optional.ofNullable\n\n```bash\n/**\n * Returns an {@code Optional} describing the specified value, if non-null,\n * otherwise returns an empty {@code Optional}.\n *\n*/\n```\n##Optional Stream\n\n```java\npublic List<User> getUsers(Collection<Integer> userIds) {\n return userIds.Stream()\n .map(this::getUserById) // 获得 Stream<Optional<User>>\n .flatMap(Optional::Stream) // Stream 的 flatMap 方法将多个流合成一个流\n .collect(Collectors.toList());\n}\n```"
},
{
"alpha_fraction": 0.832335352897644,
"alphanum_fraction": 0.8443113565444946,
"avg_line_length": 32.599998474121094,
"blob_id": "e810500da7636703041bc9d6e5e294bea8d24024",
"content_id": "1a000ed6b28ba1b342ce193a59a9c2601cc5c922",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 427,
"license_type": "permissive",
"max_line_length": 58,
"num_lines": 5,
"path": "/PythonSummary/设计模式/委托模式/委托模式.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#委托模式\n通过一个类来调用另一个类里的方法来处理请求,即这两个类对象参与处理同一个请求对象,只不过一个是委托者,一个是处理者。\npython中需要以下两步处理:\n1. 重写__getattr__方法,使得委托者获得处理者的属性。\n2. 判断该属性是否为可调用函数,如果不是则直接返回,如果是,则用 wrapper 封装为可调用对象。"
},
{
"alpha_fraction": 0.7011494040489197,
"alphanum_fraction": 0.7528735399246216,
"avg_line_length": 13.416666984558105,
"blob_id": "a5f2430ab1640d6741e0d7b3fbe45653c68b5a5a",
"content_id": "235b54c25e41157c568d29842466aececa7ca4fc",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 304,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 12,
"path": "/PythonSummary/编码问题/系统cmd编码.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# 系统cmd编码 Blog\n坑:系统编码问题有可能会导致log或者print 的中文乱码,导致相关的模块有可能报错 \n系统cmd默认编码,使用\n```commandline\nchcp\n```\n查看936(GBK) \n需要将其转换为项目的encoding编码 \n例如 utf-8\n```commandline\nchcp 65001\n```\n "
},
{
"alpha_fraction": 0.874015748500824,
"alphanum_fraction": 0.8779527544975281,
"avg_line_length": 38.07692337036133,
"blob_id": "798bcf30a683e8ef21140443f629b3c0d492b268",
"content_id": "d9f9e82204605392e917d9008cfacde143da7769",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1330,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 13,
"path": "/JavaSummary/src/Class继承/ClassExtends.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-继承中的属性和方法\n总结继承中的属性和方法以及super相关问题\n\n## 继承了什么\n在一个子类被创建的时候,首先会在内存中创建一个父类对象,然后在父类对象外部放上子类独有的属性,两者合起来形成一个子类的对象。 \n子类对象确实拥有父类对象中所有的属性和方法,但是父类对象中的私有属性和方法,子类是无法访问到的,只是拥有,但不能使用。\n### 关于私有成员变量\n无论父类中的成员变量是pirvate、public还是其它类型的,子类都会拥有(继承)父类中的这些成员变量。但是父类中的私有成员变量,无法在子类中直接访问,可以通过从父类中继承得到的protected、public方法(如getter、setter方法)来访问。\n个人认为这更好的提现了JAVA特性中的封装,而且符合软件工程的设计思想:低耦合。\n##子类继承父类的属性和继承方法的方式上有所差别:\n1.父类属性不可被重写,只会被调用,父类方法可以被重写,也可以被调用\n\n2.当子类中存在和父类同名属性,父类属性会隐藏起来,在多态的情况下属性被调用时会激活父类属性子类属性隐藏起来,而方法不会隐藏,一旦被重写,只能使用super来在子类调用\n"
},
{
"alpha_fraction": 0.5940860509872437,
"alphanum_fraction": 0.6397849321365356,
"avg_line_length": 17.170732498168945,
"blob_id": "27748206a599abc1a614e916cfcd0811bcaebf08",
"content_id": "1a67b79d6ec5cf8b881ae6637ad8d9f7ac26c030",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 978,
"license_type": "permissive",
"max_line_length": 91,
"num_lines": 41,
"path": "/PythonSummary/设计模式/装饰器模式/函数装饰器-装饰函数.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 函数装饰器-装饰函数.py\n@Time : 2020/12/3 17:38\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n\n\"\"\"\n两个点需要注意的,\n\n第一:wrapper需要保证与add_function参数一致。因为返回的wrapper就是add_function,所以要统一,我们可以使用*arg,和**args去匹配任何参数;\n\n第二:wrapper一定要返回值。因为add_function函数是需要返回值的。\n\"\"\"\n\n\ndef MethodDecoration(function): # 外层decorator\n c = 150\n d = 200\n\n def wrapper(a, b): # 内层wrapper。和add_function参数要一样\n result = function(a, b)\n result = result * c / d # 加密,相当于添加额外功能\n return result # 此处一定要返回值\n\n return wrapper\n\n\n@MethodDecoration\ndef add_function(a, b):\n return a + b\n\n\nresult = add_function(100, 300) # 函数调用\nprint(result)"
},
{
"alpha_fraction": 0.616797924041748,
"alphanum_fraction": 0.6745406985282898,
"avg_line_length": 14.279999732971191,
"blob_id": "281842c06e651d32c90db1a1df0ef7a86e86eacc",
"content_id": "ebaaecfe857ca93bc06c27675dc6d3f8debf5715",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 645,
"license_type": "permissive",
"max_line_length": 51,
"num_lines": 25,
"path": "/PythonSummary/python原理及特性/字典dict/Python3 dict优化/Python3 dict优化.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# coding=utf-8\n\n# 计算下标,通过&运算取模\n# 为什么和(len - 1)&运算呢?\n# 容器大小是2的次幂,(newCap - 1)转化成二进制后,后面位数全是1,\n# 这样可以进行取模了,与运算速度快\n# 设计确实非常的巧妙,既省去了重新计算hash值的时间,\n# 而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,\n# 均匀的把之前的冲突的节点分散到新的bucket了\n\nlist_length = 8\nfor i in xrange(10):\n\tstri = str(i)\n\tstr_in_list_index = hash(stri) & (list_length - 1)\n\tprint str_in_list_index\n# 1\n# 0\n# 3\n# 2\n# 5\n# 4\n# 7\n# 6\n# 1\n# 0"
},
{
"alpha_fraction": 0.484375,
"alphanum_fraction": 0.49609375,
"avg_line_length": 27.44444465637207,
"blob_id": "da60c50284f05c4a368cfd127043c45c88bf2139",
"content_id": "f348761067efda113eb654e05dfd0e0cc7d6b0ee",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 256,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 9,
"path": "/PythonSummary/正则匹配/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "import re\n\nif __name__ == '__main__':\n s = \"afas/*afdshdafhda*/hasdfas/*afdshdafhda*/ // data2 2.5f\"\n m = re.compile(r'//.*')\n outtmp = re.sub(m, ' ', s)\n m = re.compile(r'/\\*.*?\\*/', re.S)\n result = re.sub(m, ' ', outtmp)\n print(result)\n"
},
{
"alpha_fraction": 0.7142857313156128,
"alphanum_fraction": 0.7142857313156128,
"avg_line_length": 17.153846740722656,
"blob_id": "c265df22b124b0ce63ab707c9301e86eefae8bf9",
"content_id": "379fd616394c6e5464a5cc90e392730791f0b240",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 444,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 13,
"path": "/PythonSummary/python原理及特性/列表list/list.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# list的一些操作\n\n## enumerate\n```python\nfor index, i in enumerate(列表list)\n```\n使用 enumerate 函数 可以返回下标。\n\n## 切片操作的一般方式\n```\n切片操作基本表达式:object[start_index:end_index:step]\n```\nstep:正负数均可,其绝对值大小决定了切取数据时的‘‘步长”,而正负号决定了“切取方向”,正表示“从左往右”取值,负表示“从右往左”取值。\n\n\n"
},
{
"alpha_fraction": 0.6390410661697388,
"alphanum_fraction": 0.6472602486610413,
"avg_line_length": 38.4594612121582,
"blob_id": "03ad0fc2cdde7c71e3cc58bfe55c6241f0b1592a",
"content_id": "d9621073f3a98aca887949da60a108466e9be5ee",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1460,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 37,
"path": "/PythonSummary/python原理及特性/connectHive/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# coding=UTF-8\nimport numpy as np\nimport pandas as pd\nimport env\nimport MySQLdb\nfrom normalized import *\nfrom classification import *\n\nif __name__ == '__main__':\n connect = MySQLdb.Connect(host=env.host, port=env.port, user=env.user, passwd=env.password, db=env.db)\n cur = connect.cursor()\n cur.execute(\"SELECT download,view,size,subsets,created,updated FROM \" + env.db + '.' + env.tableName)\n data = []\n data = np.array(cur.fetchall())\n cur.close()\n colName = np.array([\"download\", \"view\", \"size\", \"subsets\", \"created\", \"updated\"])\n decision = 'lin'\n # target = data[:, 0]\n # structuredData = data[:, 1: 4]\n # timeData =data[:, [4, 5]]\n # target = formatTarget(data[:, 0])\n # structuredData = formatStructuredData(data[:, 1: 4])\n # timeData = formatTime(data[:, [4, 5]])\n # formatData = np.concatenate((structuredData, timeData), axis=1)\n # if decision == 'dt':\n # skDecisionTreeTraining(data, formatData, structuredData, timeData, target, colName)\n # elif decision == 'dnn':\n # tfDNNClassiferTraining(data, formatData, structuredData, timeData, target, colName)\n # elif decision == 'lin':\n # tfLinearClassifierTraing(data, formatData, structuredData, timeData, target, colName)\n\n data = list(cur.fetchall())\n data=pd.DataFrame(data)\n print(data.isnull().sum())\n cur.execute(\" DESC \" + env.db + '.' + env.tableName)\n description = cur.fetchall()\n print(description)\n"
},
{
"alpha_fraction": 0.43062201142311096,
"alphanum_fraction": 0.5358851552009583,
"avg_line_length": 18.090909957885742,
"blob_id": "ece9cf932b64f39b83b3a49e7beaabaef74e9425",
"content_id": "c62886b6ee9b2d823c16d0e3b0dc4247a2800c8c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 209,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 11,
"path": "/PythonSummary/设计模式/黑板模式/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : __init__.py.py\n@Time : 2020/12/3 16:23\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\""
},
{
"alpha_fraction": 0.36304837465286255,
"alphanum_fraction": 0.39848142862319946,
"avg_line_length": 27.677419662475586,
"blob_id": "61406cea649b6cf45b01478f4b208c4c9294f5a4",
"content_id": "56cab72c78a3f7e6dac24e4bfcafa00dc5942456",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4465,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 124,
"path": "/JavaSummary/src/凸包问题的五种解法/分治法.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 凸包问题的五种解法;/**\n * @program: javatest\n * @author: zpc\n * @create: 2019-09-16 15:30\n **/\n\nimport java.util.Arrays;\nimport java.util.Comparator;\n\n/**\n * @Author: zpc\n * @Description:\n * 分治法\n * 时间复杂度:O(n㏒n)。\n * @Create: 2019-09-16 15:30\n **/\n\n\npublic class 分治法 {\n\n //分治法\n //时间复杂度:O(n㏒n)。 \n //思路:应用分治法思想,把一个大问题分成几个结构相同的子问题,把子问题再分成几个更小的子问题……。\n // 然后我们就能用递归的方法,分别求这些子问题的解。最后把每个子问题的解“组装”成原来大问题的解。 \n //步骤:\n //\n //把所有的点都放在二维坐标系里面。那么横坐标最小和最大的两个点 P1 和 Pn 一定是凸包上的点(为什么呢?用反证法很容易证明,这里不详讲)。\n // 直线 P1Pn 把点集分成了两部分,即 X 轴上面和下面两部分,分别叫做上包和下包。\n //对上包:求距离直线 P1Pn 最远的点,即下图中的点 Pmax 。\n //作直线 P1Pmax 、PnPmax,把直线 P1Pmax 左侧的点当成是上包,把直线 PnPmax 右侧的点也当成是上包。\n //重复步骤 2、3。\n //对下包也作类似操作。\n //然而怎么求距离某直线最远的点呢?我们还是用到解一中的公式: \n //|x1 y1 1|\n //|x2 y2 1|=x1y2+x3y1+x2y3-x3y2-x2y1-x1y3\n //|x3 y3 1| \n //设有一个点 P3 和直线 P1P2 。(坐标:p1(x1,y1),p2(x2,y2),p3(x3,y3)) \n //对上式的结果取绝对值,绝对值越大,则距离直线越远。\n //注意:在步骤一,如果横坐标最小的点不止一个,那么这几个点都是凸包上的点,此时上包和下包的划分就有点不同了,需要注意。\n static Point[] point;\n static double[] s = new double[6];\n\n public static void main(String[] args) {\n int n = 6;\n point = new Point[n];\n// for (int i = 0; i < n; i++) {\n// int a = in.nextInt();\n// int b = in.nextInt();\n// point[i] = new Point(a, b);\n// }\n point[0] = new Point(1,3);\n point[1] = new Point(2,1);\n point[2] = new Point(3,5);\n point[3] = new Point(4,4);\n point[4] = new Point(5,2);\n point[5] = new Point(3,2);\n Arrays.sort(point,0, n, new Comparator<Point>() {\n @Override\n public int compare(Point o1, Point o2) {\n if (o1.x - o2.x == 0) {\n return (int) (o1.y - o2.y);\n }\n return (int) (o1.x - o2.x);\n }\n });\n System.out.println(point[0].x + \",\" + point[0].y);\n hull(1, n-1,point[0],point[0]);\n }\n\n private static void hull(int l,int r,Point p1,Point p2){\n int x=l;\n int i=l-1,j=r+1;\n /**\n * 找出距离直线p1-p2最远的点p3\n * */\n for (int k = l; k <= r; k++){\n if (s[x] - s[k] <= 0) {\n x=k;\n }\n }\n Point p3 = point[x];\n /**\n * p1-p3左侧的点\n * */\n for (int k = l; k <= r; k++) {\n\n s[++i] = cross(point[k], p1, p3);\n if (s[i] > 0) {\n Point temp = point[i];\n point[i] = point[k];\n point[k] = temp;\n } else {\n i--;\n }\n }\n /**\n * 直线p3-p2右侧的点\n * */\n for (int k=r;k>=l;k--) {\n s[--j]=cross(point[k], p3, p2);\n if (s[j] > 0) {\n Point temp = point[j];\n point[j] = point[k];\n point[k] = temp;\n } else {\n j++;\n }\n }\n /**\n * 分治,并中序输出\n * */\n if (l <= i) {\n hull(l, i, p1, p3);\n }\n System.out.println(p3.x + \",\" + p3.y);\n if (j <= r) {\n hull(j, r, p3, p2);\n }\n }\n private static double cross (Point a, Point b, Point c) {\n return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);\n }\n\n}\n"
},
{
"alpha_fraction": 0.5678595304489136,
"alphanum_fraction": 0.5705604553222656,
"avg_line_length": 29.85416603088379,
"blob_id": "5a153c1194cf20bcd4cab153d0995180c631bd60",
"content_id": "36ee0bfa98a12b5adcf3aca5d13950002b2754ce",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1883,
"license_type": "permissive",
"max_line_length": 105,
"num_lines": 48,
"path": "/JavaSummary/src/单例模式/DCLSingleton.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 单例模式;\n\n//double checked locking模式\npublic class DCLSingleton {\n\n private volatile static DCLSingleton DCLSingleton;//将 instance 变量声明成 volatile 保证JVM 的即时编译器中不会指令重排序的优化\n\n private DCLSingleton() {};\n\n public static DCLSingleton getDCLSingleton() {\n if (DCLSingleton == null) {\n synchronized (DCLSingleton.class) {\n// 同步块内还要再检验一次?因为可能会有多个线程一起进入同步块外的 if,\n// 如果在同步块内不进行二次检验的话就会生成多个实例了。\n if (DCLSingleton == null) {\n// instance = new 设计模式.单例模式.DCLSingleton()这句,这并非是一个原子操作,事实上在 JVM 中这句话大概做了下面 3 件事情:\n// 1.给 instance 分配内存\n// 2.调用 设计模式.单例模式.DCLSingleton 的构造函数来初始化成员变量\n// 3.将instance对象指向分配的内存空间(执行完这步 instance 就为非 null 了)。\n\n DCLSingleton = new DCLSingleton();\n }\n }\n }\n return DCLSingleton;\n }\n}\n\nclass DCLOptimizeSingleton {\n\n private static volatile DCLOptimizeSingleton instance = null;\n\n private DCLOptimizeSingleton() {}\n\n public static DCLOptimizeSingleton getInstance () {\n DCLOptimizeSingleton inst = instance; // <<< 在这里创建临时变量\n if (inst == null) {\n synchronized (DCLOptimizeSingleton.class) {\n inst = instance;\n if (inst == null) {\n inst = new DCLOptimizeSingleton();\n instance = inst;\n }\n }\n }\n return inst; // <<< 注意这里返回的是临时变量\n }\n}\n"
},
{
"alpha_fraction": 0.5077605247497559,
"alphanum_fraction": 0.5565410256385803,
"avg_line_length": 14.586206436157227,
"blob_id": "34be84d8797c483823eff416ae5b8f03556808b4",
"content_id": "8a57e153c12fd9bf99e6a34048a78b2838e7307f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 475,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 29,
"path": "/PythonSummary/设计模式/装饰器模式/类装饰器.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : 类装饰器.py\n@Time : 2020/12/3 17:45\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\n\nclass MethodDecorator:\n def __init__(self, function):\n self.function = function\n\n def __call__(self):\n print('开始')\n self.function()\n print('结束')\n\n\n@MethodDecorator\ndef myfunc():\n print('我是函数myfunc')\n\n\nmyfunc()"
},
{
"alpha_fraction": 0.867972195148468,
"alphanum_fraction": 0.8698673248291016,
"avg_line_length": 71,
"blob_id": "7abf378274ab5d776bb15b6fd55808d4c60ac556",
"content_id": "35f03cb8e82697cb28f5b13b45d396eec2687f23",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4223,
"license_type": "permissive",
"max_line_length": 325,
"num_lines": 22,
"path": "/PythonSummary/游戏设计/行为树/行为树(Behavior Tree)中使用黑板(BlackBoard).md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#行为树\n黑板非常适合作为行为树的辅助模块来使用,这次就来谈谈如何在行为树中使用黑板。行为树的决策一般要依赖于外部的输入,如下图所示。\n\n输入内容的来源取决于行为树用在整个AI架构的哪一层,可以是游戏世界的信息,或者是上层模块的输出。输入的形式,可以是分散的(Decentralized),也可以是集中的(Centralized)。举个例子来说,如果我们做一个战士是移动,还是攻击的决策,这是决策层的行为,所以输入内容就是游戏世界的信息,它可能包括战士自身状态(在模块A中),敌人状态(在模块B中),装备物品情况(在模块C),地图场景情况(在模块D中)等等,所以,当我们搜索和执行行为树时,我们需要从4个模块中获取信息来帮助决策,这样的方式就是我上面说的分散的方式,它的好处是调用非常直接(可能是用多个Singleton提供的接口),没有数据冗余,缺点是使得行为树对于数据的依赖度太分散。\n\n集中的方式的话,就是我们可以定义一个数据结构专门用于行为树的输入,将上面提到的需要用到的数据,在进行行为树决策前,先从各个模块中收集到这个数据结构里,然后再递交给行为树使用。集中式的输入减少了输入和行为树之间的接口数量(只和预定义的数据结构通信),但缺点是,存在数据冗余。不过,我们可以看到集中式的数据输入使得行为树的表现更像一个黑盒了(可以伪造数据来测试行为树),这也是我们一直以来想要的。可以参看下面对于两种方式的示意图:\n\n基于上面的原因,黑板(Blackboard)这样一个概念正好符合我们的需要,所以我们就可以用黑板从各个模块中来收集行为树决策和执行的过程中需要用到的数据,然后提交给行为树使用。值得注意的是,这块黑板对于行为树来说是只读(Readonly)的,行为树不允许修改和添加任何信息到这块黑板上面。因为很难从程序上去限制(就算用const,有时为了方便还能强转成非const),所以限制只能是一种规则,或者说约定。\n\n说完了外部世界的黑板,我们再说说另一块可能会被用到的黑板。这也可以看成是对上面这块只读黑板的补偿吧,:)\n\n在行为树的使用过程中,发现有时候节点和节点间,行为树和行为树之间确实需要有数据共享,比如对于序列(Sequence)节点来说,它的执行行为是依次执行每一个子节点,直白一点说的话,就是执行完一个再执行下一个。一般用到序列的行为,其子节点间总会有一些联系,这里就可能存在节点间通信的问题。再比如,在一些团队AI的决策过程中,当前AI的行为树决策可能需要参考其他AI的决策结果,所以这样就存在了行为树之间需要通信的情况。\n\n所以,在实践过程中,我们还会定义另一块黑板来负责行为树间和节点间的通信需求,示意图如下:\n\n可以看到这块黑板是又可以读又可以写的,为了防止黑板混乱的问题(可以参看我以前对于共享数据的文章),我们必须在使用时规定一些限制,可以称之为黑板数据的“作用域”,\n我们知道很多编程语言里,变量都是存在作用域的概念的,有全局,有局部等等,借鉴于此,我也在这块黑板上规定了作用域,由上面的分析我们可以将黑板上的数据分成如下几种作用域:\n\n* 全局域(G):此数据可以给其他行为树访问 \n* 行为树域(T):此数据可以给行为树内的任意节点访问 \n* 指定节点域(N):此数据可以给指定的行为树内的某节点(可以是多个)访问 \n这样的话,黑板的混乱程度就会好很多了,我们可以提供相关的接口来帮助操作黑板上的这些变量。"
},
{
"alpha_fraction": 0.7398648858070374,
"alphanum_fraction": 0.7398648858070374,
"avg_line_length": 16.47058868408203,
"blob_id": "234ac5263867299c7f25778306409ae889c6a3e8",
"content_id": "7ca6c5fad939512514fa066bc612f75d3ec292a3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 442,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 17,
"path": "/JavaSummary/out/production/JavaSummary/时间戳TimeStamp/TimeStamp.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-Time\n总结三种JAVA获取时间戳\n\n## 方法 一 \nSystem.currentTimeMillis(); \n \n## 方法 二 \nCalendar.getInstance().getTimeInMillis(); \n\n## 方法 三 \nnew Date().getTime(); \n\nSystem.currentTimeMillis() 这种方式速度最快\n\nCalendar.getInstance().getTimeInMillis() 这种方式速度最慢,看看源码会发现,Canlendar因为要处理时区问题会耗费很多的时间。\n\n所以建议多使用第一种方式。"
},
{
"alpha_fraction": 0.7872806787490845,
"alphanum_fraction": 0.8135964870452881,
"avg_line_length": 31.571428298950195,
"blob_id": "49ee38d1711f2f796eedb723df0c69aed88c0b87",
"content_id": "130b59033f00cadd2987757cddd8f8b0762c78fb",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 794,
"license_type": "permissive",
"max_line_length": 63,
"num_lines": 14,
"path": "/JavaSummary/src/多线程/CountDownLatch和CyclicBarrier和Semaphore/JUC辅助类.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-JUC辅助类\nCountDownLatch和CyclicBarrier和Semaphore使用和应用场景总结\n\n## CountDownLatch\n比如某个任务依赖于其他的两个任务,只有那两个任务执行结束后,它才能执行。\n\n## CyclicBarrier\n用来挂起当前线程,直至所有线程都到达barrier状态再同时执行后续任务;\n比如线程1,2,3运行,线程1达到barrier.awit()阻塞接着等待线程2、3达到阻塞状态,\n当1,2,3都达到awit则1,2,3继续执行接下来的操作\n\n## Semaphore\n同时让多个线程同时访问共享资源,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。\n\n"
},
{
"alpha_fraction": 0.49056604504585266,
"alphanum_fraction": 0.6037735939025879,
"avg_line_length": 20.200000762939453,
"blob_id": "2a0d9ea9e6179029a5b888460b509e3a8bc635a3",
"content_id": "7fefbb7d7c89025e22455b792055c23bb5eb100c",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 106,
"license_type": "permissive",
"max_line_length": 24,
"num_lines": 5,
"path": "/PythonSummary/游戏设计/Reload热更新/a/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python \n# -- coding: utf-8 -- \n# Time : 2020/11/5 15:07\n# Author : zpc\n# ProjectName: test\n"
},
{
"alpha_fraction": 0.631369948387146,
"alphanum_fraction": 0.6412971615791321,
"avg_line_length": 34.97618865966797,
"blob_id": "aedef14ab06456e86fcc510ca678dcb5aa116e97",
"content_id": "d688edadae926ea11860d182b807e10abe8061f1",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1825,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 42,
"path": "/JavaSummary/src/设计模式DesignPatterns/proxy/cglibProxy.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "//package 设计模式DesignPatterns.proxy;\n//import net.sf.cglib.设计模式DesignPatterns.proxy.Enhancer;\n//import net.sf.cglib.设计模式DesignPatterns.proxy.MethodInterceptor;\n//import net.sf.cglib.设计模式DesignPatterns.proxy.MethodProxy;\n//\n///**\n// * @program: TechSummary\n// * @author: zpc\n// * @create: 2019-07-10 22:10\n// **/\n////使用cglib需要引入cglib的jar包,如果你已经有spring-core的jar包,则无需引入,因为spring中包含了cglib。\n//public class cglibProxy implements MethodInterceptor{\n// private Enhancer enhancer = new Enhancer();\n// @Override\n// /**\n// *\n// * @param o 是被代理对象\n// * @param method 调用方法的Method对象\n// * @param args 方法参数\n// * @param methodProxy\n// * @return cglib生成用来代替Method对象的一个对象,使用MethodProxy比调用JDK自身的Method直接执行方法效率会有提升\n// * @throws Throwable\n// */\n// public Object intercept(Object o, Method method, Object[] args,\n// MethodProxy methodProxy) throws Throwable {\n// System.out.println(\"before \" + methodProxy.getSuperName());\n// System.out.println(method.getName());\n// Object o1 = methodProxy.invokeSuper(o, args);\n// //Object o2 = method.invoke(o, args); 使用这种方式会发生死循环,因为方法会被拦截\n// System.out.println(\"after \" + methodProxy.getSuperName());\n// return o1;\n// }\n//\n// public Object newProxyInstance(Class<?> c) {\n// //设置产生的代理对象的父类。\n// enhancer.setSuperclass(c);\n// //设置CallBack接口的实例\n// enhancer.setCallback(this);\n// //使用默认无参数的构造函数创建目标对象\n// return enhancer.create();\n// }\n//}\n"
},
{
"alpha_fraction": 0.6105263233184814,
"alphanum_fraction": 0.6610526442527771,
"avg_line_length": 18,
"blob_id": "73f0a6c466a4c9d95bb2fb3aa0f58bbc420292e0",
"content_id": "8072b2e03df098d5c9271f73de01d59e77f59513",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 523,
"license_type": "permissive",
"max_line_length": 56,
"num_lines": 25,
"path": "/JavaSummary/src/多线程/一主多从多线程协作/Check/RemoteBankThread.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "/**\n * @program: TechSummary\n * @author: zpc\n * @create: 2019-08-18 21:13\n **/\npackage 多线程.一主多从多线程协作.Check;\nimport 多线程.一主多从多线程协作.Service.RemoteBankService;\n\n/**\n * @Author: zpc\n * @Description:\n * @Create: 2019-08-18 21:13\n **/\n\n\npublic class RemoteBankThread extends BaseCheckThread{\n public RemoteBankThread(int uid) {\n super(uid);\n }\n\n @Override\n public Boolean call() throws Exception {\n return new RemoteBankService().checkCredit(uid);\n }\n}\n"
},
{
"alpha_fraction": 0.6926308870315552,
"alphanum_fraction": 0.7159017324447632,
"avg_line_length": 21.742647171020508,
"blob_id": "e0c1af6efc1e2d6da943097420ebe6f1a836290a",
"content_id": "a4d24b3965162e1ddea1682e23ab014c1cef83d4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4528,
"license_type": "permissive",
"max_line_length": 100,
"num_lines": 136,
"path": "/PythonSummary/并发编程/线程池/线程池.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#Pyhton 线程池\n从Python3.2开始,标准库为我们提供了 concurrent.futures 模块. \n它提供了 ThreadPoolExecutor (线程池)和ProcessPoolExecutor (进程池)两个类。 \n相比 threading 等模块,该模块通过 submit 返回的是一个 future 对象\n它是一个未来可期的对象,通过它可以获悉线程的状态主线程(或进程)中可以获取某一个线程(进程)执行的状态或者某一个任务执行的状态及返回值\n\n1.主线程可以获取某一个线程(或者任务的)的状态,以及返回值。 \n2.当一个线程完成的时候,主线程能够立即知道。 \n3.让多线程和多进程的编码接口一致。 \n\n```python\n# coding: utf-8\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\n\ndef spider(page):\n time.sleep(page)\n print(f\"crawl task{page} finished\")\n return page\n\nwith ThreadPoolExecutor(max_workers=5) as t: # 创建一个最大容纳数量为5的线程池\n task1 = t.submit(spider, 1)\n task2 = t.submit(spider, 2) # 通过submit提交执行的函数到线程池中\n task3 = t.submit(spider, 3)\n\n print(f\"task1: {task1.done()}\") # 通过done来判断线程是否完成\n print(f\"task2: {task2.done()}\")\n print(f\"task3: {task3.done()}\")\n\n time.sleep(2.5)\n print(f\"task1: {task1.done()}\")\n print(f\"task2: {task2.done()}\")\n print(f\"task3: {task3.done()}\")\n print(task1.result()) # 通过result来获取返回值\n\n```\n执行结果如下:\n```commandline\ntask1: False\ntask2: False\ntask3: False\ncrawl task1 finished\ncrawl task2 finished\ntask1: True\ntask2: True\ntask3: False\n1\ncrawl task3 finished\n\n```\n通过使用 done() 方法判断该任务是否结束。上面的例子可以看出,提交任务后立即判断任务状态,显示四个任务都未完成。在延时2.5后,task1 和 task2 执行完毕,task3 仍在执行中。\n\n使用 result() 方法可以获取任务的返回值。\n\n## 主要方法:\n###wait \n```python\n wait(fs, timeout=None, return_when=ALL_COMPLETED)\n```\nwait 接受三个参数: \nfs: 表示需要执行的序列 \ntimeout: 等待的最大时间,如果超过这个时间即使线程未执行完成也将返回 \nreturn_when:表示wait返回结果的条件,默认为 ALL_COMPLETED 全部执行完成再返回\n\n### as_completed\n上面虽然提供了判断任务是否结束的方法,但是不能在主线程中一直判断啊。最好的方法是当某个任务结束了,就给主线程返回结果,而不是一直判断每个任务是否结束。\nThreadPoolExecutorThreadPoolExecutor 中 的 as_completed() 就是这样一个方法,当子线程中的任务执行完后,直接用 result() 获取返回结果\n```python\n# coding: utf-8\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport time\n\n\ndef spider(page):\n time.sleep(page)\n print(f\"crawl task{page} finished\")\n return page\n\ndef main():\n with ThreadPoolExecutor(max_workers=5) as t:\n obj_list = []\n for page in range(1, 5):\n obj = t.submit(spider, page)\n obj_list.append(obj)\n\n for future in as_completed(obj_list):\n data = future.result()\n print(f\"main: {data}\")\n\n# 执行结果\ncrawl task1 finished\nmain: 1\ncrawl task2 finished\nmain: 2\ncrawl task3 finished\nmain: 3\ncrawl task4 finished\nmain: 4\n\n```\n###map\n```python\nmap(fn, *iterables, timeout=None)\n```\nfn: 第一个参数 fn 是需要线程执行的函数; \niterables:第二个参数接受一个可迭代对象; \ntimeout: 第三个参数 timeout 跟 wait() 的 timeout 一样,但由于 map 是返回线程执行的结果,如果 timeout小于线程执行时间会抛异常 TimeoutError。\n\n```python\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef spider(page):\n time.sleep(page)\n return page\n\nstart = time.time()\nexecutor = ThreadPoolExecutor(max_workers=4)\n\ni = 1\nfor result in executor.map(spider, [2, 3, 1, 4]):\n print(\"task{}:{}\".format(i, result))\n i += 1\n\n# 运行结果\ntask1:2\ntask2:3\ntask3:1\ntask4:4\n\n```\n使用 map 方法,无需提前使用 submit 方法,map 方法与 python 高阶函数 map 的含义相同,都是将序列中的每个元素都执行同一个函数。\n上面的代码对列表中的每个元素都执行 spider() 函数,并分配各线程池。\n可以看到执行结果与上面的 as_completed() 方法的结果不同,输出顺序和列表的顺序相同,就算 1s 的任务先执行完成,\n也会先打印前面提交的任务返回的结果。\n\n"
},
{
"alpha_fraction": 0.6204081773757935,
"alphanum_fraction": 0.6693877577781677,
"avg_line_length": 18.600000381469727,
"blob_id": "8a8da93932d5508bc8ca15d3c89a4dd0dda4e285",
"content_id": "0b33043dd5231a9dd08c126bd65aaf6b6e6b6073",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 538,
"license_type": "permissive",
"max_line_length": 59,
"num_lines": 25,
"path": "/JavaSummary/src/多线程/一主多从多线程协作/Check/RemotePassportThread.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "/**\n * @program: TechSummary\n * @author: zpc\n * @create: 2019-08-18 21:13\n **/\npackage 多线程.一主多从多线程协作.Check;\nimport 多线程.一主多从多线程协作.Service.RemotePassportService;\n\n/**\n * @Author: zpc\n * @Description:\n * @Create: 2019-08-18 21:13\n **/\n\n\npublic class RemotePassportThread extends BaseCheckThread {\n public RemotePassportThread(int uid) {\n super(uid);\n }\n\n @Override\n public Boolean call() throws Exception {\n return new RemotePassportService().checkAuth(uid);\n }\n}\n"
},
{
"alpha_fraction": 0.6955775022506714,
"alphanum_fraction": 0.6968656182289124,
"avg_line_length": 22.525253295898438,
"blob_id": "5b470a5ece27d659a9fad2b945879923c6ddd374",
"content_id": "87ea6b5d247f7847fb8f31265696f8d9ad13f6ce",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3555,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 99,
"path": "/JavaSummary/out/production/JavaSummary/单例模式/单例模式.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# Blog-单例模式总结\n总结单例模式\n\n## 枚举单例\n```java\npublic enum EnumSingleton {\n INSTANCE;\n\n public EnumSingleton getInstance() {\n return INSTANCE;\n }\n}\n\nclass run{\n public static void main(String[] args) {\n EnumSingleton.INSTANCE.getInstance();\n }\n}\n```\n优点:\neffective java(这本书真的很棒)中说道,最佳的单例实现模式就是枚举模式。 \n利用枚举的特性,让JVM来帮我们保证线程安全和单一实例的问题。(创建enum时,编译器会自动为我们生成一个继承自java.lang.Enum的类) \n1、默认枚举实例的创建是线程安全的 \n2、以往的单例实现了序列化接口,那么就再也不能保持单例的状态了.因为readObject()方法一直返回一个新的对象.使用radResolve()来避免此情况发生.枚举单例 对序列化有保证 \n3、采用反射来创建实例时.可通过AccessibleObject.setAccessible(),通过反射机制来调用私有构造器.那么枚举可以防止这种创建第二个实例的情况发生.\n\n## 静态内部类(static nested class)\n```\npublic class Singleton {\n public static class SingletonHolder {\n private static final Singleton INSTANCE = new Singleton();\n }\n\n private Singleton() {}\n\n public static final Singleton getInstance() {\n return SingletonHolder.INSTANCE;\n }\n}\n```\n优点:外部类加载时并不需要立即加载内部类,内部类不被加载则不去初始化INSTANCE,故而不占内存。\n即当SingleTon第一次被加载时,并不需要去加载SingleTonHoler,只有当getInstance()方法第一次被调用时,\n才会去初始化INSTANCE,第一次调用getInstance()方法会导致虚拟机加载SingleTonHoler类,\n 这种方法不仅能确保线程安全,也能保证单例的唯一性,同时也延迟了单例的实例化。\n\n## Double Check Lock 式单例\n```\npublic class Singleton {\n\n private static Singleton instance ;\n\n private Singleton() {}\n\n public static synchronized Singleton getInstance() {\n if (instance == null) {\n synchronized (Singleton.class) {\n if(instance == null) {\n instance = new Singleton();\n }\n }\n }\n return instance;\n }\n}\n\n```\n这种模式的资源利用率高,第一次执行getInstance()时单例对象才会被实例化,效率高。缺点是第一次加载反应慢,也由于Java内存模型的原因偶尔会失败,在高并发下也有一定的缺陷,虽然发生的概率较小。\n\n## 懒汉式单例\n```\npublic class Singleton {\n\n private static Singleton instance ;\n\n private Singleton () {}\n\n public static synchronized Singleton getInstance() {\n if (instance == null) {\n instance = new Singleton();\n }\n return instance;\n }\n}\n```\n注意代码种的getInstance()函数使用了synchronized关键字,这个关键字确保了代码在多线程情况下单例对象的唯一性。\n\n## 饿汉模式\n```\npublic class Singleton {\n private static Singleton instance = new Singleton();\n\n private Singleton(){}\n\n public static Singleton getInstance() {\n return instance;\n }\n}\n```\n这种方式在类加载时就完成了初始化,所以类加载较慢,但获取对象的速度快。 这种方式基于类加载机制避免了多线程的同步问题,但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance显然没有达到懒加载的效果。\n"
},
{
"alpha_fraction": 0.4319066107273102,
"alphanum_fraction": 0.4805447459220886,
"avg_line_length": 18.80769157409668,
"blob_id": "7593e576c42e8927e7c55199522c3183976ade2f",
"content_id": "0a8f1f1107f574e78e10e0088c4cd9d8d637712a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 542,
"license_type": "permissive",
"max_line_length": 34,
"num_lines": 26,
"path": "/PythonSummary/python原理及特性/python简洁编程总结/Dict/Dict赋值/Dict赋值.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : Dict赋值.py\n@Time : 2020/10/12 16:35\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\nif __name__ == '__main__':\n cond = {}\n gid = '1'\n oid = '2'\n if gid:\n cond[\"gid\"] = gid\n if oid:\n cond[\"oid\"] = oid\n\n # 使用内置函数locals() 获取局部变量\n vardict = locals()\n for key in [\"gid\", \"oid\"]:\n value = vardict.get(key)\n if value:\n cond[key] = value"
},
{
"alpha_fraction": 0.5116279125213623,
"alphanum_fraction": 0.5674418807029724,
"avg_line_length": 14.357142448425293,
"blob_id": "3bf4c7880aa46ef2299a1e5dc475ab6956f4b6ad",
"content_id": "2739902cabbc6b21bb1836ead67e3108962f4dac",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 446,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 28,
"path": "/JavaSummary/src/单例模式/懒汉.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package 单例模式;/**\n * @program: javatest\n * @author: zpc\n * @create: 2019-07-19 22:50\n **/\n\n/**\n * @Author: zpc\n * @Description: 单例\n * @Create: 2019-07-19 22:50\n **/\n\n\npublic class 懒汉 {\n}\n\nclass Sinleton{\n private static Sinleton sinleton;\n Sinleton(){\n }\n\n public static synchronized Sinleton getInstance() {\n if (sinleton == null) {\n return new Sinleton();\n }\n return sinleton;\n }\n}\n"
},
{
"alpha_fraction": 0.7566844820976257,
"alphanum_fraction": 0.7786096334457397,
"avg_line_length": 38.72340393066406,
"blob_id": "3967fa723a3929ac7538d1a63ebb749fe8507733",
"content_id": "79d61b32ef1cd02789a855e818692d45f27cb27a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3308,
"license_type": "permissive",
"max_line_length": 136,
"num_lines": 47,
"path": "/PythonSummary/Mongo/MongoDB事务.md",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "#MongoDB事务(Transactions)\nhttps://docs.mongodb.com/manual/core/transactions/\nhttps://www.jianshu.com/p/21565744ada6\n# 事务\n事务成功提交之前,所有的数据变更在事务之外不可见;\n\n* 事务中的任何一项操作失败后,所有的变更会被丢弃,事务回滚;\n\n* 支持事务,需要保证使用的是 MongoDB 4.0 或以上版本,并且 featureCompatibilityVersion 需要设置为 4.0。从旧版本升级上来的复本集群可能为 3.6,需要特别注意。可以通过如下命令检查:\ndb.adminCommand( { getParameter: 1, featureCompatibilityVersion: 1 } )\n\n* 只有 wiredTiger 引擎支持事务。同时请留意,4.0 已经标记 MMAPv1 为 Deprecated,并且将会在未来的某一版本移除对 MMAPv1 引擎的支持;\n## 单文件支持事务,多文件和分布式事务4.0\nmongo事务和会话(Sessions)关联,一个会话同一时刻只能开启一个事务操作,当一个会话断开,这个会话中的事务也会结束。\n```\nvar session = db.getMongo().startSession();\nsession.startTransaction({\n readConcern: { level: <level> },\n writeConcern: { w: <value>, j: <boolean>, wtimeout: <number> }\n});\nvar coll = session.getDatabase('test').getCollection('user');\n\ncoll.update({name: 'Jack'}, {$set: {age: 18}})\n\n// 成功提交事务\nsession.commitTransaction();\n\n// 失败事务回滚\nsession.abortTransaction();\n\n```\n# readConcern(读关注)\n多文档事务支持 local、majority、snapshot 三个 read concern 设置,其中 snapshot 主要是在 majority 的基础上实现了对因果一致性的保证; \n请留意: \n1.readConcern 的设置是事务级别的,不能对事务内的操作单独设置 readConcern; \n2.snapshot 设置只在多文档事务中支持,如:session 并不支持设置 readConcern 为 snapshot; \n# Transactions and Write Concern(写关注)\n```writeConcern: { w: <value>, j: <boolean>, wtimeout: <number> }``` \n您可以在事务开始时设置事务级写关注: \n* 如果事务级写关注未设置,则事务级写关注默认为提交的会话级写关注。\n* 如果事务级写关注和会话级写关注未设置,事务级写关注默认为客户端级写关注\nWrite conern支持以下值: \n0|1|N|majority \n* 当w:0为Unacknowledged(无回执),会出现的数据丢失情况。(因为{writeConcern:{w:0}}导致出现异常时并没有返回错误信息给客户端。) \n* 当w:1为Acknowledged。在日志写完之后返回确定信息,虽然解决了w:0出现的数据丢失问题,但是w:1时如果出现系统崩溃也会导致数据丢失,那就是在日志信息还没有刷新到磁盘的那一刻发生系统宕机,此时内存日志的确是写入成功了于是mongodb就会返回确定信息。 \n* 当j:1为Journal。当j:1时可以解决w:1数据丢失的问题(journal刷盘以后在写回执),但是随之而来的是Mongodb的性能会下降。虽然解决了服务器宕机时数据丢失问题(会丢失60s左右的数据,就是一次间隔没有刷新到磁盘的数据)。 \n* 当w:2/N/majority replica Acknowledged。等待数据复制到n个节点再发送回执。majority是“多数”在提交已应用于多数 (M) 投票成员后返回确认; 即提交已应用于主要和(M-1)投票次要。 \n\n"
},
{
"alpha_fraction": 0.52182537317276,
"alphanum_fraction": 0.601190447807312,
"avg_line_length": 18.423076629638672,
"blob_id": "f0fe53a046197e3c9f63fb8f65ff6789bb66bdc7",
"content_id": "8b15bf51e02fd9157505305bbc907039ffbdba4d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 662,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 26,
"path": "/PythonSummary/python原理及特性/lambda匿名函数/__init__.py",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n@File : __init__.py.py\n@Time : 2020/11/3 10:35\n@Author : ZPC\n@Version : 1.0\n@Contact : [email protected]\n@License : (C)Copyright 2019-2020\n@Desc : None\n\"\"\"\n\nadd = lambda x, y : x+y\nadd(1,2) # 结果为3\n\n# 函数式编程的特性,如:map、reduce、filter、sorted等这些函数都支持函数作为参数,lambda函数就可以应用在函数式编程中。\n# 需求:将列表中的元素按照绝对值大小进行升序排列\nlist1 = [3,5,-4,-1,0,-2,-6]\nsorted(list1, key=lambda x: abs(x))\n\n# 应用在闭包中\ndef get_y(a, b):\n return lambda x: a*x + b\n\ny1 = get_y(1, 1)\ny1(1) # 结果为2"
},
{
"alpha_fraction": 0.64861661195755,
"alphanum_fraction": 0.6549407243728638,
"avg_line_length": 28.764705657958984,
"blob_id": "5583630327c57abf68d8d47753abef9fe9e18d5d",
"content_id": "2766bffdba66df3e5ed4dc4013f13c0fae5501e3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2950,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 85,
"path": "/JavaSummary/src/Socket编程/BaseSocketClient.java",
"repo_name": "PENGsBIT/TechSummary",
"src_encoding": "UTF-8",
"text": "package Socket编程;\n\n//import org.apache.poi.util.IOUtils;\n\n//import jdk.internal.module.ModuleInfoExtender;\n\nimport java.io.*;\n\nimport java.net.Socket;\n\n/**\n * The very basic socket client that only send one single message.\n */\n\npublic class BaseSocketClient {\n private String serverHost;\n\n private int serverPort;\n\n private Socket socket;\n\n private OutputStream outputStream;\n\n private InputStream inputStream;\n private static final int MAX_BUFFER_SIZE = 1024;\n\n\n public BaseSocketClient(String host, int port) {\n this.serverHost = host;\n this.serverPort = port;\n }\n\n\n\n public void connectServer() throws IOException {\n this.socket = new Socket(this.serverHost, this.serverPort);\n this.outputStream = socket.getOutputStream();\n // why the output stream?\n }\n\n //从只发送和接收一次消息的socket基础代码开始\n public void sendSingle(String message) throws IOException {\n try {\n this.outputStream.write(message.getBytes(\"UTF-8\"));\n } catch (UnsupportedEncodingException e) {\n System.out.println(e.getMessage());\n }\n this.outputStream.close();\n this.socket.close();\n }\n\n //socket连接支持全双工的双向通信(底层是tcp),下面的例子中,服务端在收到客户端的消息后,将返回给客户端一个回执\n public void sendMessage(String message) throws IOException {\n this.socket = new Socket(this.serverHost, this.serverPort);\n this.outputStream = socket.getOutputStream();\n this.outputStream.write(message.getBytes(\"UTF-8\"));\n this.socket.shutdownOutput(); // 告诉服务器,所有的发送动作已经结束,之后只能接收\n this.inputStream = socket.getInputStream();\n\n DataInputStream in = new DataInputStream(inputStream);\n System.out.println(\"服务器响应: \" + in.readUTF());\n// String receipt = IOUtils.toByteArray(inputStream).toString();\n// System.out.println(\"got receipt: \" + receipt);\n this.inputStream.close();\n this.socket.close();\n //注意这里我们在服务端接受到消息以及客户端发送消息后,分别调用了shutdownInput()和shutdownOutput()而不是直接close对应的stream,这是因为在关闭任何一个stream,都会直接导致socket的关闭,也就无法进行后面回执的发送了。\n //\n //\n //但是注意,调用shutdownInput()和shutdownOutput()之后,对应的流也会被关闭,不能再次向socket发送/写入了。\n //\n\n }\n\n public static void main(String[] args) {\n BaseSocketClient bc = new BaseSocketClient(\"127.0.0.1\", 9799);\n try {\n bc.connectServer();\n// bc.sendSingle(\"Hi from mark.\");\n bc.sendMessage(\"double transfer messge\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n"
}
] | 114 |
hexingmou/jenkins
|
https://github.com/hexingmou/jenkins
|
b0187c21b234edad822b3a7c047bf8b85d7f4c6b
|
541dccc812740087574d8b9f70cba021aa6e2bd9
|
f60879e9063b23dca92cf70cf4d1fec0a1dd294a
|
refs/heads/master
| 2020-09-16T19:14:30.265383 | 2019-12-03T11:40:35 | 2019-12-03T11:40:35 | 223,864,508 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6045576333999634,
"alphanum_fraction": 0.6407506465911865,
"avg_line_length": 26.629629135131836,
"blob_id": "9190039ac5d3f9ee8285967265430ff64028ab7e",
"content_id": "385e9e0a7d5d2f14d6f9a82880ef3b06080b2705",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 850,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 27,
"path": "/README.md",
"repo_name": "hexingmou/jenkins",
"src_encoding": "UTF-8",
"text": "一、 获取本机的IP号centos7\n\n###### ifconfig ens33|awk 'NR==2'|awk -F'[ ]+' 'BEGIN{OFS=\"\\n\"}{print $3,$5,$7}' \n\n二、centos6 获取本机IP\n\nifconfig eth0|awk 'NR>1 {print $2}'|awk -F':' 'NR<2 {print $2}' \n\n###### ifconfig eth0|grep Bcast|awk -F':' '{print $2}'|awk '{print $1}'\n\n###### ifconfig eth0|grep Bcast|awk '{print $2}'|awk -F: '{print $2}'\n\nifconfig eth0|awk NR==2|awk -F '[ :]+' '{print $4RS$6RS$8}'\n\n三、启动nginx\nsbin/nginx -c /usr/local/nginx/conf/nginx.conf\nsbin/nginx -s reload\n四、追加环境变量启动PHP\necho 'export PATH=PATH:/usr/local/php/bin' >> /etc/profile\nservice php-fpm start /systemctl start hph-fpm\n\n五、mysql 密码的设置\nmysql_seurce_installation\n第二个为no 其他都为yes\n\n六、==统计网站访问量==\nss -antp|grep 80|awk '{states[$1]++};END{for(i in states){print i,states[i]}}'\n"
},
{
"alpha_fraction": 0.7727272510528564,
"alphanum_fraction": 0.7727272510528564,
"avg_line_length": 20,
"blob_id": "26e5400e21ddf2e5ca8438011f98d8ce0d55d3dc",
"content_id": "fc3eb07788eb054214aeb5066cc6e214bee4ebc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 44,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 2,
"path": "/1.py",
"repo_name": "hexingmou/jenkins",
"src_encoding": "UTF-8",
"text": "[email protected]:hexingmou/jenkins.git\nhello nihao \n"
}
] | 2 |
maisli/neurolight_experiments
|
https://github.com/maisli/neurolight_experiments
|
3a49563410051c87f50a134d034d4b04b0c6887e
|
d0918f5cca3b9eec4fd9960e7aaee76d725dd910
|
574944f304fee77e264d70275a47d9e1ddf771f2
|
refs/heads/master
| 2020-04-09T10:06:31.959309 | 2019-06-18T16:10:58 | 2019-06-18T16:10:58 | 160,258,530 | 0 | 1 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5456310510635376,
"alphanum_fraction": 0.5747572779655457,
"avg_line_length": 27.61111068725586,
"blob_id": "fa9c676bff5a27a1a4d94669c8068ffc00da62f8",
"content_id": "f1f7ec9046c280a9a568f67648906711a475b64c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2575,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 90,
"path": "/flylight/02_train/setup07/mknet.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "from gunpowder.zoo.tensorflow import unet, conv_pass\nimport tensorflow as tf\nimport json\nimport sys\nimport os\n\ndef create_network(input_shape, name, output_folder):\n\n tf.reset_default_graph()\n \n # c=3, d, h, w\n raw = tf.placeholder(tf.float32, shape=(3,) + input_shape)\n \n # b=1, c=3, d, h, w\n raw_batched = tf.reshape(raw, (1, 3,) + input_shape)\n\n out = unet(raw_batched, 12, 5, [[2,2,2],[2,2,2],[2,2,2]])\n output_batched = conv_pass(\n out,\n kernel_size=1,\n num_fmaps=1,\n num_repetitions=1,\n activation=None)\n output_shape_batched = output_batched.get_shape().as_list()\n print('output shape batched: ', output_shape_batched)\n\n # d, h, w\n output_shape = output_shape_batched[2:]\n print('output_shape: ', output_shape)\n output = tf.reshape(output_batched, output_shape)\n\n pred = tf.sigmoid(output)\n\n gt = tf.placeholder(tf.float32, shape=output_shape)\n loss_weights = tf.placeholder(tf.float32, shape=output_shape)\n\n loss = tf.losses.sigmoid_cross_entropy(\n gt,\n output,\n loss_weights)\n\n opt = tf.train.AdamOptimizer(\n learning_rate=0.5e-4,\n beta1=0.95,\n beta2=0.999,\n epsilon=1e-8)\n optimizer = opt.minimize(loss)\n\n print(\"input shape: %s\"%(input_shape,))\n print(\"output shape: %s\"%(output_shape,))\n\n tf.train.export_meta_graph(filename=os.path.join(output_folder, name + '.meta'))\n\n names = {\n 'raw': raw.name,\n 'pred': pred.name,\n 'gt': gt.name,\n 'loss_weights': loss_weights.name,\n 'loss': loss.name,\n 'optimizer': optimizer.name,\n }\n with open(os.path.join(output_folder, name + '_names.json'), 'w') as f:\n json.dump(names, f)\n\n config = {\n 'input_shape': input_shape,\n 'output_shape': output_shape,\n 'out_dims': 1\n }\n with open(os.path.join(output_folder, name + '_config.json'), 'w') as f:\n json.dump(config, f)\n\nif __name__ == \"__main__\":\n\n root = '/groups/kainmueller/home/maisl/workspace/neurolight/experiments'\n experiment = 'setup07_070419_00'\n\n if len(sys.argv) > 1:\n experiment = sys.argv[1]\n if len(sys.argv) > 2:\n root = sys.argv[2]\n\n output_folder = os.path.join(root, experiment, 'train')\n try:\n os.makedirs(output_folder)\n except OSError:\n pass\n\n create_network((128, 128, 128), 'train_net', output_folder)\n create_network((180, 180, 180), 'test_net', output_folder)\n"
},
{
"alpha_fraction": 0.5297751426696777,
"alphanum_fraction": 0.5419282913208008,
"avg_line_length": 33.76811599731445,
"blob_id": "cbd0793444e2aa86d9f1b3747fdb51e7b20009ec",
"content_id": "5f12c68bc810985c4361b56aca7ceee9f65162ac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9874,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 276,
"path": "/flylight/02_train/setup14/train.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\r\nimport gunpowder as gp\r\nimport neurolight.gunpowder as nl\r\nimport numpy as np\r\nimport json\r\nimport logging\r\nimport os\r\nimport tensorflow as tf\r\nimport h5py\r\nimport sys\r\nimport math\r\nfrom datetime import datetime\r\n\r\ndata_dir = '/home/maisl/data/flylight'\r\ndata_files = [\r\n 'flylight_v1_train.hdf',\r\n]\r\n\r\nclass Convert(gp.BatchFilter):\r\n\r\n def __init__(self, array, dtype):\r\n\r\n self.array = array\r\n self.dtype = dtype\r\n\r\n def process(self, batch, request):\r\n\r\n if self.array not in batch.arrays:\r\n return\r\n\r\n array = batch.arrays[self.array]\r\n\r\n try:\r\n array.data = array.data.astype(self.dtype)\r\n except:\r\n print(\"Cannot convert!\")\r\n\r\n array.spec.dtype = self.dtype\r\n\r\n\r\nclass BinarizeLabels(gp.BatchFilter):\r\n\r\n def __init__(self, labels, labels_binary):\r\n\r\n self.labels = labels\r\n self.labels_binary = labels_binary\r\n\r\n def setup(self):\r\n\r\n spec = self.spec[self.labels].copy()\r\n spec.dtype = np.uint8\r\n self.provides(self.labels_binary, spec)\r\n\r\n def process(self, batch, request):\r\n\r\n spec = batch[self.labels].spec.copy()\r\n spec.dtype = np.uint8\r\n\r\n reduce_channels = np.max(batch[self.labels].data > 0, axis=0).astype(np.uint8)\r\n\r\n binarized = gp.Array(\r\n data=reduce_channels,\r\n spec=spec)\r\n\r\n batch[self.labels_binary] = binarized\r\n\r\n\r\ndef train_until(max_iteration, name='train_net', output_folder='.', clip_max=2000):\r\n\r\n # get the latest checkpoint\r\n if tf.train.latest_checkpoint(output_folder):\r\n trained_until = int(tf.train.latest_checkpoint(output_folder).split('_')[-1])\r\n else:\r\n trained_until = 0\r\n if trained_until >= max_iteration:\r\n return\r\n\r\n with open(os.path.join(output_folder, name + '_config.json'), 'r') as f:\r\n net_config = json.load(f)\r\n with open(os.path.join(output_folder, name + '_names.json'), 'r') as f:\r\n net_names = json.load(f)\r\n\r\n # array keys\r\n raw = gp.ArrayKey('RAW')\r\n gt_instances = gp.ArrayKey('GT_INSTANCES')\r\n gt_mask = gp.ArrayKey('GT_MASK')\r\n pred_mask = gp.ArrayKey('PRED_MASK')\r\n #loss_weights = gp.ArrayKey('LOSS_WEIGHTS')\r\n loss_gradients = gp.ArrayKey('LOSS_GRADIENTS')\r\n\r\n # array keys for base and add volume\r\n raw_base = gp.ArrayKey('RAW_BASE')\r\n gt_instances_base = gp.ArrayKey('GT_INSTANCES_BASE')\r\n gt_mask_base = gp.ArrayKey('GT_MASK_BASE')\r\n raw_add = gp.ArrayKey('RAW_ADD')\r\n gt_instances_add = gp.ArrayKey('GT_INSTANCES_ADD')\r\n gt_mask_add = gp.ArrayKey('GT_MASK_ADD')\r\n\r\n voxel_size = gp.Coordinate((1, 1, 1))\r\n input_shape = gp.Coordinate(net_config['input_shape'])\r\n output_shape = gp.Coordinate(net_config['output_shape'])\r\n context = gp.Coordinate(input_shape - output_shape) / 2\r\n\r\n request = gp.BatchRequest()\r\n request.add(raw, input_shape)\r\n request.add(gt_instances, output_shape)\r\n request.add(gt_mask, output_shape)\r\n #request.add(loss_weights, output_shape)\r\n request.add(raw_base, input_shape)\r\n request.add(raw_add, input_shape)\r\n request.add(gt_mask_base, output_shape)\r\n request.add(gt_mask_add, output_shape)\r\n\r\n snapshot_request = gp.BatchRequest()\r\n snapshot_request.add(raw, input_shape)\r\n #snapshot_request.add(raw_base, input_shape)\r\n #snapshot_request.add(raw_add, input_shape)\r\n snapshot_request.add(gt_mask, output_shape)\r\n #snapshot_request.add(gt_mask_base, output_shape)\r\n #snapshot_request.add(gt_mask_add, output_shape)\r\n snapshot_request.add(pred_mask, output_shape)\r\n snapshot_request.add(loss_gradients, output_shape)\r\n\r\n # specify data source\r\n # data source for base volume\r\n data_sources_base = tuple()\r\n for data_file in data_files:\r\n current_path = os.path.join(data_dir, data_file)\r\n with h5py.File(current_path, 'r') as f:\r\n data_sources_base += tuple(\r\n gp.Hdf5Source(\r\n current_path,\r\n datasets={\r\n raw_base: sample + '/raw',\r\n gt_instances_base: sample + '/gt',\r\n gt_mask_base: sample + '/fg',\r\n },\r\n array_specs={\r\n raw_base: gp.ArraySpec(interpolatable=True, dtype=np.uint16, voxel_size=voxel_size),\r\n gt_instances_base: gp.ArraySpec(interpolatable=False, dtype=np.uint16, voxel_size=voxel_size),\r\n gt_mask_base: gp.ArraySpec(interpolatable=False, dtype=np.bool, voxel_size=voxel_size),\r\n }\r\n ) +\r\n Convert(gt_mask_base, np.uint8) +\r\n gp.Pad(raw_base, context) +\r\n gp.Pad(gt_instances_base, context) +\r\n gp.Pad(gt_mask_base, context) +\r\n gp.RandomLocation(min_masked=0.005, mask=gt_mask_base)\r\n #gp.Reject(gt_mask_base, min_masked=0.005, reject_probability=1.)\r\n for sample in f)\r\n data_sources_base += gp.RandomProvider()\r\n\r\n # data source for add volume\r\n data_sources_add = tuple()\r\n for data_file in data_files:\r\n current_path = os.path.join(data_dir, data_file)\r\n with h5py.File(current_path, 'r') as f:\r\n data_sources_add += tuple(\r\n gp.Hdf5Source(\r\n current_path,\r\n datasets={\r\n raw_add: sample + '/raw',\r\n gt_instances_add: sample + '/gt',\r\n gt_mask_add: sample + '/fg',\r\n },\r\n array_specs={\r\n raw_add: gp.ArraySpec(interpolatable=True, dtype=np.uint16, voxel_size=voxel_size),\r\n gt_instances_add: gp.ArraySpec(interpolatable=False, dtype=np.uint16, voxel_size=voxel_size),\r\n gt_mask_add: gp.ArraySpec(interpolatable=False, dtype=np.bool, voxel_size=voxel_size),\r\n }\r\n ) +\r\n Convert(gt_mask_add, np.uint8) +\r\n gp.Pad(raw_add, context) +\r\n gp.Pad(gt_instances_add, context) +\r\n gp.Pad(gt_mask_add, context) +\r\n gp.RandomLocation() +\r\n gp.Reject(gt_mask_add, min_masked=0.005, reject_probability=0.95)\r\n for sample in f)\r\n data_sources_add += gp.RandomProvider()\r\n data_sources = tuple([data_sources_base, data_sources_add]) + gp.MergeProvider()\r\n\r\n pipeline = (\r\n data_sources +\r\n nl.FusionAugment(\r\n raw_base, raw_add, gt_instances_base, gt_instances_add, raw, gt_instances,\r\n blend_mode='labels_mask', blend_smoothness=5, num_blended_objects=0\r\n ) +\r\n BinarizeLabels(gt_instances, gt_mask) +\r\n nl.Clip(raw, 0, clip_max) +\r\n gp.Normalize(raw, factor=1.0/clip_max) +\r\n gp.ElasticAugment(\r\n control_point_spacing=[20, 20, 20],\r\n jitter_sigma=[1, 1, 1],\r\n rotation_interval=[0, math.pi/2.0],\r\n subsample=4) +\r\n gp.SimpleAugment(mirror_only=[1, 2], transpose_only=[1, 2]) +\r\n\r\n gp.IntensityAugment(raw, 0.9, 1.1, -0.1, 0.1) +\r\n gp.IntensityScaleShift(raw, 2, -1) +\r\n #gp.BalanceLabels(gt_mask, loss_weights) +\r\n\r\n # train\r\n gp.PreCache(\r\n cache_size=40,\r\n num_workers=10) +\r\n gp.tensorflow.Train(\r\n os.path.join(output_folder, name),\r\n optimizer=net_names['optimizer'],\r\n loss=net_names['loss'],\r\n inputs={\r\n net_names['raw']: raw,\r\n net_names['gt']: gt_mask,\r\n #net_names['loss_weights']: loss_weights,\r\n },\r\n outputs={\r\n net_names['pred']: pred_mask,\r\n },\r\n gradients={\r\n net_names['output']: loss_gradients,\r\n },\r\n save_every=5000) +\r\n\r\n # visualize\r\n gp.Snapshot({\r\n raw: 'volumes/raw',\r\n pred_mask: 'volumes/pred_mask',\r\n gt_mask: 'volumes/gt_mask',\r\n #loss_weights: 'volumes/loss_weights',\r\n loss_gradients: 'volumes/loss_gradients',\r\n },\r\n output_filename=os.path.join(output_folder, 'snapshots', 'batch_{iteration}.hdf'),\r\n additional_request=snapshot_request,\r\n every=2500) +\r\n gp.PrintProfilingStats(every=1000)\r\n )\r\n\r\n with gp.build(pipeline):\r\n \r\n print(\"Starting training...\")\r\n for i in range(max_iteration - trained_until):\r\n pipeline.request_batch(request)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\r\n\r\n iteration = 100\r\n root = '/home/maisl/workspace/neurolight/experiments'\r\n experiment = 'setup14_020519_00'\r\n name = 'train_net'\r\n clip_max = 1500\r\n\r\n if len(sys.argv) > 1:\r\n iteration = int(sys.argv[1])\r\n experiment = sys.argv[2]\r\n\r\n if len(sys.argv) > 3:\r\n clip_max = int(sys.argv[3])\r\n\r\n if len(sys.argv) > 4:\r\n root = sys.argv[4]\r\n\r\n output_folder = os.path.join(root, experiment, 'train')\r\n try:\r\n os.makedirs(os.path.join(output_folder, 'snapshots'))\r\n except OSError:\r\n pass\r\n\r\n logging.basicConfig(level=logging.INFO)\r\n start = datetime.now()\r\n \r\n print('start training with: ', experiment, iteration, name, clip_max, output_folder)\r\n train_until(iteration, name, output_folder, clip_max)\r\n\r\n print('time: ', datetime.now() - start)\r\n\r\n"
},
{
"alpha_fraction": 0.6404440402984619,
"alphanum_fraction": 0.6626448035240173,
"avg_line_length": 28.19718360900879,
"blob_id": "adf66d08c5d44233619d30502623035a80d15501",
"content_id": "98c4cfbf6e731e4a3c785b37f6d4755e6638e0f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 2072,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 71,
"path": "/flylight/predict_all.sh",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nif [ $# -eq 0 ]\nthen\n echo \"WARNING: No arguments supplied!\"\n echo \"predict_all.sh <experiment> <iteration> <num_worker> <output_dir>\"\n\n exp=030419_01\n setup=setup01\n iteration=100000\n clipmax=1000\n num_workers=2\n output_folder=/groups/kainmueller/home/maisl/workspace/neurolight/experiments/${setup}_$exp\n data_folder=/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data\n dataset=flylight_270319_val\n cuda_devices=(0 1)\nelse\n exp=$1\n setup=$2\n iteration=$3\n clipmax=$4\n num_workers=$5\n output_folder=$6\n data_folder=$7\n dataset=$8\n echo \"exp:\" $exp $setup $iteration $clipmax\n echo \"num workers:\" $num_workers\n echo \"output folder: \" $output_folder\n echo \"dataset:\" $data_folder $dataset\nfi\n\n# check cuda devices\nif [ -z \"$cuda_devices\" ]\nthen\n if [ -z \"$CUDA_VISIBLE_DEVICES\" ]\n then\n echo \"Please set either $ 5 <cuda_devices> or CUDA_VISIBLE_DEVICES!\"\n exit 1\n else\n IFS=', ' read -r -a cuda_devices <<< \"$CUDA_VISIBLE_DEVICES\"\n fi\nfi\necho \"Using cuda devices:\" ${cuda_devices[@]}\n\n# get samples in validation set from txt file\nsample_list=${data_folder}/${dataset}.txt\nreadarray samples < $sample_list\nnum_samples=${#samples[@]}\nnum_samples_per_worker=$((num_samples / num_workers))\necho \"Total files:\" $num_samples \"/ files per worker:\" $num_samples_per_worker\n\nfor i in $(seq 1 $num_workers);\ndo\n idx=$((i-1))\n start_idx=$((idx * num_samples_per_worker))\n worker_log_file=$output_folder/predict_worker_${i}.out\n\n if [ $i -eq $num_workers ]\n then\n num_samples_per_worker=$((num_samples_per_worker + (num_samples - num_workers * num_samples_per_worker)))\n fi\n\n echo \"Starting worker\" $i \"with start id\" $start_idx\n echo \"log file:\" $worker_log_file\n\n export CUDA_VISIBLE_DEVICES=${cuda_devices[$idx]}\n\n ./predict_single.sh $data_folder $dataset $start_idx $num_samples_per_worker $exp $setup $iteration $clipmax $output_folder > $worker_log_file 2>&1 &\n\ndone\nwait"
},
{
"alpha_fraction": 0.5325196981430054,
"alphanum_fraction": 0.5476152300834656,
"avg_line_length": 31.092782974243164,
"blob_id": "1c3f639592f4ac47744b055b18e9ae1c3c7bb412",
"content_id": "c5de273537972740a478749d4d414ec8ea8d4c57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6227,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 194,
"path": "/flylight/02_train/setup02/train.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport gunpowder as gp\nimport neurolight.gunpowder as nl\nimport numpy as np\nimport json\nimport logging\nimport os\nimport tensorflow as tf\nimport h5py\nimport sys\nimport math\n\n\ndata_dir = '/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data'\ndata_files = [\n 'flylight_270319_train.hdf',\n]\n\nclass Convert(gp.BatchFilter):\n\n def __init__(self, array, dtype):\n\n self.array = array\n self.dtype = dtype\n\n def process(self, batch, request):\n\n if self.array not in batch.arrays:\n return\n\n array = batch.arrays[self.array]\n\n try:\n array.data = array.data.astype(self.dtype)\n except:\n print(\"Cannot convert!\")\n\n array.spec.dtype = self.dtype\n\n\ndef train_until(max_iteration, name='train_net', output_folder='.', clip_max=2000):\n\n # get the latest checkpoint\n if tf.train.latest_checkpoint(output_folder):\n trained_until = int(tf.train.latest_checkpoint(output_folder).split('_')[-1])\n else:\n trained_until = 0\n if trained_until >= max_iteration:\n return\n\n with open(os.path.join(output_folder, name + '_config.json'), 'r') as f:\n net_config = json.load(f)\n with open(os.path.join(output_folder, name + '_names.json'), 'r') as f:\n net_names = json.load(f)\n\n # array keys\n raw = gp.ArrayKey('RAW')\n hls = gp.ArrayKey('HLS')\n gt_mask = gp.ArrayKey('GT_MASK')\n pred_mask = gp.ArrayKey('PRED_MASK')\n loss_weights = gp.ArrayKey('LOSS_WEIGHTS')\n loss_gradient = gp.ArrayKey('LOSS_GRADIENT')\n\n voxel_size = gp.Coordinate((1, 1, 1))\n input_shape = gp.Coordinate(net_config['input_shape'])\n output_shape = gp.Coordinate(net_config['output_shape'])\n context = gp.Coordinate(input_shape - output_shape) / 2\n\n request = gp.BatchRequest()\n request.add(raw, input_shape)\n request.add(hls, input_shape)\n request.add(gt_mask, output_shape)\n request.add(loss_weights, output_shape)\n\n snapshot_request = gp.BatchRequest()\n snapshot_request.add(raw, input_shape)\n snapshot_request.add(hls, input_shape)\n snapshot_request.add(gt_mask, output_shape)\n snapshot_request.add(pred_mask, output_shape)\n snapshot_request.add(loss_gradient, output_shape)\n\n # specify data source\n data_sources = tuple()\n for data_file in data_files:\n current_path = os.path.join(data_dir, data_file)\n with h5py.File(current_path, 'r') as f:\n data_sources += tuple(\n gp.Hdf5Source(\n current_path,\n datasets={\n raw: sample + '/raw',\n gt_mask: sample + '/fg'\n },\n array_specs={\n raw: gp.ArraySpec(interpolatable=True, dtype=np.uint16, voxel_size=voxel_size),\n gt_mask: gp.ArraySpec(interpolatable=False, dtype=np.bool, voxel_size=voxel_size),\n }\n ) +\n Convert(gt_mask, np.uint8) +\n gp.Pad(raw, context) +\n gp.Pad(gt_mask, context) +\n gp.RandomLocation()\n for sample in f)\n\n pipeline = (\n data_sources +\n gp.RandomProvider() +\n gp.Reject(gt_mask, min_masked=0.005, reject_probability=0.98) +\n nl.Clip(raw, 0, clip_max) +\n gp.ElasticAugment(\n control_point_spacing=[20, 20, 20],\n jitter_sigma=[1, 1, 1],\n rotation_interval=[0, math.pi/2.0],\n subsample=4) +\n gp.SimpleAugment(mirror_only=[1,2], transpose_only=[1,2]) +\n gp.Normalize(raw, factor=1.0 / clip_max) +\n #gp.IntensityAugment(raw, 0.9, 1.1, -0.1, 0.1) +\n #gp.IntensityScaleShift(raw, 2,-1) +\n nl.ConvertRgbToHls(raw, hls) +\n\n gp.BalanceLabels(gt_mask, loss_weights) +\n\n # train\n gp.PreCache(\n cache_size=40,\n num_workers=5) +\n gp.tensorflow.Train(\n os.path.join(output_folder, name),\n optimizer=net_names['optimizer'],\n loss=net_names['loss'],\n inputs={\n net_names['raw']: hls,\n net_names['gt']: gt_mask,\n net_names['loss_weights']: loss_weights,\n },\n outputs={\n net_names['pred']: pred_mask,\n },\n gradients={\n net_names['pred']: loss_gradient,\n },\n save_every=5000) +\n\n # visualize\n gp.Snapshot({\n raw: 'volumes/raw',\n pred_mask: 'volumes/pred_mask',\n gt_mask: 'volumes/gt_mask',\n hls: 'volumes/hsl',\n loss_weights: 'volumes/loss_weights',\n loss_gradient: 'volumes/gradient',\n },\n output_filename=os.path.join(output_folder, 'snapshots', 'batch_{iteration}.hdf'),\n additional_request=snapshot_request,\n every=500) +\n gp.PrintProfilingStats(every=500)\n )\n\n with gp.build(pipeline):\n \n print(\"Starting training...\")\n for i in range(max_iteration - trained_until):\n pipeline.request_batch(request)\n\nif __name__ == \"__main__\":\n\n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\n iteration = 200000\n root = '/groups/kainmueller/home/maisl/workspace/neurolight/experiments'\n experiment = 'setup02_iiddmmyy'\n name = 'train_net'\n clip_max = 1000\n\n if len(sys.argv) > 1:\n iteration = int(sys.argv[1])\n experiment = sys.argv[2]\n\n if len(sys.argv) > 3:\n clip_max = int(sys.argv[3])\n\n if len(sys.argv) > 4:\n root = sys.argv[4]\n\n output_folder = os.path.join(root, experiment, 'train')\n print(output_folder)\n\n try:\n os.makedirs(os.path.join(output_folder, 'snapshots'))\n except OSError:\n pass\n\n logging.basicConfig(level=logging.INFO)\n\n train_until(iteration, name, output_folder, clip_max)\n\n"
},
{
"alpha_fraction": 0.7269279360771179,
"alphanum_fraction": 0.745891273021698,
"avg_line_length": 28.296297073364258,
"blob_id": "b728b84c9fe4c77443838d000df0de269cd233be",
"content_id": "84403c2772fb453d3f79eab9aeee2b9db847935b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 791,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 27,
"path": "/flylight/predict.sh",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nexp=$1\nsetup=$2\niteration=$3\nclipmax=$4\nnum_workers=$5\ndataset=$6\n\nroot=/groups/kainmueller/home/maisl/workspace/neurolight/experiments\ndata_folder=/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data\n\necho $exp $setup $iteration $clipmax $num_workers $dataset\n\n# create output folder and copy scripts\nexp_name=${setup}_$exp\noutput_folder=$root/$exp_name/test\nmkdir $output_folder\n\nthis_file=\"$(cd \"$(dirname \"$0\")\"; pwd)\"/`basename \"$0\"`\nsetup_folder=\"$(cd \"$(dirname \"$0\")\"; pwd)\"/03_predict/$setup\n\ncp $this_file $output_folder\ncp $setup_folder/* $output_folder\n\n./predict_all.sh $exp $setup $iteration $clipmax $num_workers $output_folder $data_folder $dataset\npython 04_evaluate/evaluate.py $exp_name $iteration $dataset\n"
},
{
"alpha_fraction": 0.5087538361549377,
"alphanum_fraction": 0.5283213257789612,
"avg_line_length": 23.897436141967773,
"blob_id": "9717d3dc1e53a42d652c66eeccbeaee7c530de1b",
"content_id": "97b00be8ebd181e5fa1a70dfed8bc62b338ae636",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 971,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 39,
"path": "/synthetic/blobs/test_tf_mask.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import tensorflow as tf\nimport numpy as np\n\nif __name__ == \"__main__\":\n\n with tf.Session() as s:\n\n a = tf.Variable(1)\n b = tf.Variable(2)\n c = a + b\n\n g = tf.gradients(c, [a])\n\n s.run(a.initializer)\n s.run(b.initializer)\n r = s.run([g])\n print(r)\n\n with tf.Session() as s:\n\n mask = tf.constant([False, True, True, False], dtype=np.bool)\n embedding = tf.Variable([\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9],\n [10, 11, 12]],\n dtype=np.float32)\n\n total_sum = tf.reduce_sum(embedding)\n gradient = tf.gradients(total_sum, embedding)\n\n filtered = tf.boolean_mask(embedding, mask)\n filtered_sum = tf.reduce_sum(filtered)\n filtered_gradient = tf.gradients(filtered_sum, embedding)\n\n s.run(embedding.initializer)\n\n print(s.run([total_sum, gradient]))\n print(s.run([filtered_sum, filtered_gradient]))\n"
},
{
"alpha_fraction": 0.743842363357544,
"alphanum_fraction": 0.761904776096344,
"avg_line_length": 26.68181800842285,
"blob_id": "c13030ef30fa0521be5314f6ae3aaa6d0dca955b",
"content_id": "ee752b7308337100e3bd2ecb350e5f2bba939060",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 609,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 22,
"path": "/flylight/evaluate.sh",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nexp=$1\nsetup=$2\niteration=$3\ndataset=$4\nsmall_object_size=$5\n\nroot=/groups/kainmueller/home/maisl/workspace/neurolight/experiments\ndata_folder=/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data\n\necho $exp $setup $iteration $clipmax $num_workers $dataset\n\n# create output folder and copy scripts\nexp_name=${setup}_$exp\noutput_folder=$root/$exp_name/test\nmkdir $output_folder\n\nthis_file=\"$(cd \"$(dirname \"$0\")\"; pwd)\"/`basename \"$0\"`\ncp $this_file $output_folder\n\npython 04_evaluate/evaluate.py $exp_name $iteration $small_object_size $dataset\n"
},
{
"alpha_fraction": 0.4947892129421234,
"alphanum_fraction": 0.535291314125061,
"avg_line_length": 25.076923370361328,
"blob_id": "8c8cc023e911b46a8caa6f531d74903112c3a836",
"content_id": "4fdc975a493553332cdeea5ac1c828052abba5cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4222,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 156,
"path": "/flylight/scripts/view_3d_batches.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import neuroglancer\r\nimport h5py\r\nimport daisy\r\nimport os\r\nimport natsort\r\nimport numpy as np\r\nimport sys\r\n\r\nneuroglancer.set_server_bind_address('0.0.0.0')\r\n\r\n\r\ndef add(s, a, name, shader=None, normalize=False, offset=None, voxel_size=None):\r\n\r\n if type(a) == daisy.array.Array:\r\n data = a.to_ndarray()\r\n else:\r\n data = a\r\n\r\n if normalize:\r\n if np.min(data) < 0:\r\n data += np.abs(np.min(data))\r\n data = data.astype(np.float32) / np.max(data)\r\n\r\n if shader == 'rgb':\r\n shader = \"\"\"void main() { \r\n emitRGB(vec3(toNormalized(getDataValue(0)), toNormalized(getDataValue(1)), toNormalized(getDataValue(2)))); \r\n }\"\"\"\r\n\r\n if shader == 'gray':\r\n shader = \"\"\"void main() {\r\n emitGrayscale(toNormalized(getDataValue(0)));\r\n }\"\"\"\r\n\r\n if shader == 'red':\r\n shader = \"\"\"void main() {\r\n float value = toNormalized(getDataValue(0));\r\n if (value <= 0.0) color = vec4(0,0,0,0);\r\n if (value > 0.0) color = vec4(1,0,0,1);\r\n emitRGBA(color);\r\n }\"\"\"\r\n\r\n if shader == 'green':\r\n shader = \"\"\"void main() {\r\n float value = toNormalized(getDataValue(0));\r\n if (value <= 0.0) color = vec4(0,0,0,0);\r\n if (value > 0.0) color = vec4(0.13, 0.48, 0.6, 1);\r\n emitRGBA(color);\r\n }\"\"\"\r\n\r\n kwargs = {}\r\n if shader is not None:\r\n kwargs['shader'] = shader\r\n\r\n if offset is None:\r\n offset = a.roi.get_offset()[::-1]\r\n\r\n if voxel_size is None:\r\n voxel_size = a.voxel_size[::-1]\r\n\r\n s.layers.append(\r\n name=name,\r\n layer=neuroglancer.LocalVolume(\r\n data=data,\r\n offset=offset,\r\n voxel_size=voxel_size\r\n ),\r\n **kwargs)\r\n\r\ndef two_color_coded(a):\r\n\r\n if type(a) == daisy.array.Array:\r\n data = a.to_ndarray()\r\n else:\r\n data = a\r\n\r\n pos = np.zeros_like(data)\r\n neg = np.zeros_like(data)\r\n zero = np.zeros_like(data)\r\n\r\n idx = data > 0\r\n if np.sum(idx) > 0:\r\n pos[idx] = data[idx] #/ float(np.max(data[idx]))\r\n idx = data < 0\r\n if np.sum(idx) > 0:\r\n neg[idx] = data[idx] * (-1) #/ float(np.min(data[idx]))\r\n\r\n color = np.stack([pos, neg, zero], axis=0)\r\n\r\n return color\r\n\r\nroot = '/groups/kainmueller/home/maisl/workspace/neurolight/experiments'\r\nexperiments = [ # 'setup04_070419_00',\r\n # 'setup02_030419_00',\r\n # 'setup05_070419_01',\r\n # 'setup04_00050419',\r\n # 'setup05_01050419',\r\n # 'setup06_070419_00',\r\n # 'setup07_070419_00',\r\n # 'setup08_080419_00',\r\n # 'setup09_090419_00',\r\n 'setup10_090419_00']\r\nexpid = 0\r\nexperiment = experiments[expid]\r\nsn = 'snapshots'\r\n\r\nsn_path = os.path.join(root, experiment, 'train', sn)\r\nsnapshots = os.listdir(sn_path)\r\nsnapshots = natsort.natsorted(snapshots)\r\nsnapshot = snapshots[-1]\r\nprint(sn_path, snapshot)\r\nsnapshot = 'batch_12001.hdf'\r\n\r\nf = os.path.join(sn_path, snapshot)\r\nraw = daisy.open_ds(f, 'volumes/raw')\r\nprint(raw.roi.get_shape(), raw.to_ndarray().shape)\r\n\r\ngt_mask = daisy.open_ds(f, 'volumes/gt_mask')\r\ngt_dt = daisy.open_ds(f, 'volumes/gt_dt')\r\npred_dt = daisy.open_ds(f, 'volumes/pred_dt')\r\ngradient = daisy.open_ds(f, 'volumes/gradient')\r\n\r\nviewer = neuroglancer.Viewer()\r\n\r\nprint(raw.roi.get_offset(),raw.roi.get_offset()[::-1])\r\nprint(gt_mask.roi.get_offset(),gt_mask.roi.get_offset()[::-1])\r\n\r\n\r\n\r\nwith viewer.txn() as s:\r\n\r\n add(s, raw, 'raw', shader='rgb', normalize=True)\r\n #add(s, gt_mask, 'gt_mask')\r\n add(s,\r\n two_color_coded(gt_dt),\r\n 'gt_dt',\r\n shader='rgb',\r\n offset=gt_dt.roi.get_offset()[::-1],\r\n voxel_size=gt_dt.voxel_size[::-1])\r\n\r\n add(s,\r\n two_color_coded(pred_dt),\r\n 'pred_dt',\r\n shader='rgb',\r\n offset=pred_dt.roi.get_offset()[::-1],\r\n voxel_size=pred_dt.voxel_size[::-1])\r\n\r\n add(s,\r\n two_color_coded(gradient),\r\n 'gradient',\r\n shader='rgb',\r\n offset=gradient.roi.get_offset()[::-1],\r\n voxel_size=gradient.voxel_size[::-1])\r\n\r\nprint(viewer)\r\n#pdb.set_trace()\r\nprint('exit')"
},
{
"alpha_fraction": 0.5364667773246765,
"alphanum_fraction": 0.5607779622077942,
"avg_line_length": 20.64912223815918,
"blob_id": "2751e5926e796851f0eb931bde90736e6e2d7bf4",
"content_id": "9b44cc0450962d17bb2e561df1c4a834e4f715ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1234,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 57,
"path": "/mouselight/02_setup/view_snapshot_spimagine.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import spimagine\nimport daisy\nimport sys\nimport numpy as np\n\ndef to_spimagine_coords(coordinate, roi):\n\n # relative to ROI begin\n coordinate -= roi.get_begin()[1:]\n # relative to ROI size in [0, 1]\n coordinate /= np.array(roi.get_shape()[1:], dtype=np.float32)\n # relative to ROI size in [-1, 1]\n coordinate = coordinate*2 - 1\n # to xyz\n return coordinate[::-1]\n\ndef inspect(raw, roi):\n\n print(\"Reading raw data...\")\n\n raw_data = raw.to_ndarray(roi=roi, fill_value=0)\n\n return spimagine.volshow(\n raw_data,\n stackUnits=raw.voxel_size[1:][::-1])\n\nif __name__ == \"__main__\":\n\n filename = sys.argv[1]\n\n\n ch1 = daisy.open_ds(\n filename,\n 'volumes/ch1')\n\n a_ch1 = daisy.open_ds(\n filename,\n 'volumes/a_ch1')\n\n b_ch1 = daisy.open_ds(\n filename,\n 'volumes/b_ch1')\n\n soft_mask = daisy.open_ds(\n filename,\n 'volumes/soft_mask')\n\n fused = daisy.Array(\n data=np.array([x.to_ndarray() for x in [ch1, a_ch1, b_ch1, soft_mask]]),\n roi=daisy.Roi(\n (0,) + ch1.roi.get_begin(),\n (4,) + ch1.roi.get_shape()),\n voxel_size=(1,) + ch1.voxel_size)\n\n inspect(fused, fused.roi)\n\n input()\n"
},
{
"alpha_fraction": 0.5291280150413513,
"alphanum_fraction": 0.5468150973320007,
"avg_line_length": 30.337209701538086,
"blob_id": "42d6ce3ca6bc71e872dc8d84fd7808c1d671ed39",
"content_id": "7c219132f3d3e9f3e8d114a9e8298157b3b1480d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8085,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 258,
"path": "/mouselight/02_setup/setup02/train.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "from __future__ import print_function\nimport numpy as np\nimport gunpowder as gp\nfrom neurolight.gunpowder import *\nimport json\nimport logging\nimport tensorflow as tf\nimport sys\nimport math\nimport os\n\nfiles = [\n #'/nrs/funke/mouselight/2017-09-25/swc-carved.h5', todo: check swc arrays\n #'/nrs/funke/mouselight/2017-11-17/swc-carved.h5',\n #'/nrs/funke/mouselight/2018-03-09/swc-carved.h5',\n '/nrs/funke/mouselight/2018-04-25/swc-carved.h5',\n #'/nrs/funke/mouselight/2018-05-23/swc-carved.h5',\n #'/nrs/funke/mouselight/2017-06-14/swc-carved.h5',\n #'/nrs/funke/mouselight/2017-07-02/swc-carved.h5',\n #'/nrs/funke/mouselight/2017-08-01/swc-carved.h5',\n]\n\n\nclass BinarizeGt(gp.BatchFilter):\n\n def __init__(self, gt, gt_binary):\n\n self.gt = gt\n self.gt_binary = gt_binary\n\n def setup(self):\n\n spec = self.spec[self.gt].copy()\n spec.dtype = np.uint8\n self.provides(self.gt_binary, spec)\n\n def prepare(self, request):\n pass\n\n def process(self, batch, request):\n\n spec = batch[self.gt].spec.copy()\n spec.dtype = np.int32\n\n binarized = gp.Array(\n data=(batch[self.gt].data > 0).astype(np.int32),\n spec=spec)\n\n batch[self.gt_binary] = binarized\n\n\nwith open('train_net_config.json', 'r') as f:\n net_config = json.load(f)\nwith open('train_net_names.json', 'r') as f:\n net_names = json.load(f)\n\n\ndef train_until(max_iteration):\n\n # get the latest checkpoint\n if tf.train.latest_checkpoint('.'):\n trained_until = int(tf.train.latest_checkpoint('.').split('_')[-1])\n else:\n trained_until = 0\n if trained_until >= max_iteration:\n return\n\n # array keys for fused volume\n raw = gp.ArrayKey('RAW')\n labels = gp.ArrayKey('LABELS')\n labels_fg = gp.ArrayKey('LABELS_FG')\n\n # array keys for base volume\n raw_base = gp.ArrayKey('RAW_BASE')\n labels_base = gp.ArrayKey('LABELS_BASE')\n swc_base = gp.PointsKey('SWC_BASE')\n swc_center_base = gp.PointsKey('SWC_CENTER_BASE')\n\n # array keys for add volume\n raw_add = gp.ArrayKey('RAW_ADD')\n labels_add = gp.ArrayKey('LABELS_ADD')\n swc_add = gp.PointsKey('SWC_ADD')\n swc_center_add = gp.PointsKey('SWC_CENTER_ADD')\n\n # output data\n fg = gp.ArrayKey('FG')\n gradient_fg = gp.ArrayKey('GRADIENT_FG')\n loss_weights = gp.ArrayKey('LOSS_WEIGHTS')\n\n voxel_size = gp.Coordinate((3, 3, 3))\n input_size = gp.Coordinate(net_config['input_shape']) * voxel_size\n output_size = gp.Coordinate(net_config['output_shape']) * voxel_size\n\n # add request\n request = gp.BatchRequest()\n request.add(raw, input_size)\n request.add(labels, output_size)\n request.add(labels_fg, output_size)\n request.add(loss_weights, output_size)\n\n request.add(swc_center_base, output_size)\n request.add(swc_base, input_size)\n\n request.add(swc_center_add, output_size)\n request.add(swc_add, input_size)\n\n # add snapshot request\n snapshot_request = gp.BatchRequest()\n snapshot_request.add(fg, output_size)\n snapshot_request.add(labels_fg, output_size)\n snapshot_request.add(gradient_fg, output_size)\n snapshot_request.add(raw_base, input_size)\n snapshot_request.add(raw_add, input_size)\n snapshot_request.add(labels_base, input_size)\n snapshot_request.add(labels_add, input_size)\n\n # data source for \"base\" volume\n data_sources_base = tuple()\n data_sources_base += tuple(\n (\n gp.Hdf5Source(\n file,\n datasets={\n raw_base: '/volume',\n },\n array_specs={\n raw_base: gp.ArraySpec(interpolatable=True, voxel_size=voxel_size, dtype=np.uint16),\n },\n channels_first=False\n ),\n SwcSource(\n filename=file,\n dataset='/reconstruction',\n points=(swc_center_base, swc_base),\n scale=voxel_size\n )\n ) +\n gp.MergeProvider() +\n gp.RandomLocation(ensure_nonempty=swc_center_base) +\n RasterizeSkeleton(\n points=swc_base,\n array=labels_base,\n array_spec=gp.ArraySpec(interpolatable=False, voxel_size=voxel_size, dtype=np.uint32),\n iteration=10)\n for file in files\n )\n data_sources_base += gp.RandomProvider()\n\n # data source for \"add\" volume\n data_sources_add = tuple()\n data_sources_add += tuple(\n (\n gp.Hdf5Source(\n file,\n datasets={\n raw_add: '/volume',\n },\n array_specs={\n raw_add: gp.ArraySpec(interpolatable=True, voxel_size=voxel_size, dtype=np.uint16),\n },\n channels_first=False\n ),\n SwcSource(\n filename=file,\n dataset='/reconstruction',\n points=(swc_center_add, swc_add),\n scale=voxel_size\n )\n ) +\n gp.MergeProvider() +\n gp.RandomLocation(ensure_nonempty=swc_center_add) +\n RasterizeSkeleton(points=swc_add,\n array=labels_add,\n array_spec=gp.ArraySpec(interpolatable=False, voxel_size=voxel_size, dtype=np.uint32),\n iteration=1)\n for file in files\n )\n data_sources_add += gp.RandomProvider()\n data_sources = tuple([data_sources_base, data_sources_add]) + gp.MergeProvider()\n\n pipeline = (\n data_sources +\n FusionAugment(raw_base, raw_add, labels_base, labels_add, raw, labels,\n blend_mode='labels_mask', blend_smoothness=10, num_blended_objects=0) +\n\n # augment\n gp.ElasticAugment([10,10,10], [1,1,1], [0,math.pi/2.0], subsample=8) +\n gp.SimpleAugment(mirror_only=[2], transpose_only=[]) +\n gp.Normalize(raw) +\n gp.IntensityAugment(raw, 0.9, 1.1, -0.001, 0.001) +\n\n BinarizeGt(labels, labels_fg) +\n gp.BalanceLabels(labels_fg, loss_weights) +\n\n # train\n gp.PreCache(\n cache_size=40,\n num_workers=10) +\n gp.tensorflow.Train(\n './train_net',\n optimizer=net_names['optimizer'],\n loss=net_names['loss'],\n inputs={\n net_names['raw']: raw,\n net_names['labels_fg']: labels_fg,\n net_names['loss_weights']: loss_weights,\n },\n outputs={\n net_names['fg']: fg,\n },\n gradients={\n net_names['fg']: gradient_fg,\n },\n save_every=100) +\n\n # visualize\n gp.Snapshot(\n output_filename='snapshot_{iteration}.hdf',\n dataset_names={\n raw: 'volumes/raw',\n raw_base: 'volumes/raw_base',\n raw_add: 'volumes/raw_add',\n labels: 'volumes/labels',\n labels_base: 'volumes/labels_base',\n labels_add: 'volumes/labels_add',\n fg: 'volumes/fg',\n labels_fg: 'volumes/labels_fg',\n gradient_fg: 'volumes/gradient_fg',\n },\n additional_request=snapshot_request,\n every=10) +\n\n gp.PrintProfilingStats(every=100)\n )\n\n with gp.build(pipeline):\n\n print(\"Starting training...\")\n for i in range(max_iteration - trained_until):\n pipeline.request_batch(request)\n\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(level=logging.INFO)\n\n if len(sys.argv) <= 1:\n\n iteration = 50\n output_folder = ''\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"7\"\n\n else:\n iteration = int(sys.argv[1])\n output_folder = sys.argv[2]\n\n train_until(iteration)\n"
},
{
"alpha_fraction": 0.6977124214172363,
"alphanum_fraction": 0.7156862616539001,
"avg_line_length": 22.5,
"blob_id": "450308edc724193f19b4b94810a376bd3b03a672",
"content_id": "fcc7ce80877fd82752adbd42af8b9ab8c4fe6650",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 612,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 26,
"path": "/flylight/02_train/train.sh",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\nexp=$1\nsetup=$2\niteration=$3\nclipmax=$4\nroot=/groups/kainmueller/home/maisl/workspace/neurolight/experiments\n\necho $exp $setup $iteration $clipmax\n\nexpname=${setup}_$exp\noutput_folder=$root/$expname\nmkdir $output_folder\n\ntrain_folder=$output_folder/train\nmkdir $train_folder\n\nthis_file=\"$(cd \"$(dirname \"$0\")\"; pwd)\"/`basename \"$0\"`\nsetup_folder=\"$(cd \"$(dirname \"$0\")\"; pwd)\"/$setup\n\ncp $this_file $output_folder\ncp $setup_folder/* $output_folder\n\npython $setup/mknet.py $expname > $output_folder/mknet.log 2>&1\n\npython $setup/train.py $iteration $expname $clipmax > $output_folder/train.log 2>&1\n\n"
},
{
"alpha_fraction": 0.6510344743728638,
"alphanum_fraction": 0.6662068963050842,
"avg_line_length": 18.594594955444336,
"blob_id": "ce9a0f092756059b1a9aa3adc5f9c776b60b02fc",
"content_id": "a16dc0f8a136549b4552acb7d61ee97a23290e24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 725,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 37,
"path": "/flylight/predict_single.sh",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\ndata_folder=$1\ndataset=$2\nstart_idx=$3\nnum_samples=$4\nexp=$5\nsetup=$6\niteration=$7\nclipmax=$8\noutput_folder=$9\n\nsample_list=${data_folder}/${dataset}.txt\nreadarray samples < $sample_list\nfiles_per_worker=(${samples[@]:start_idx:num_samples})\n\necho \"Taking\" ${#files_per_worker[@]} \"files out of\" ${#samples[@]}\necho \"Using Cuda device:\" $CUDA_VISIBLE_DEVICES\n\nexpname=${setup}_$exp\n\nfor each in \"${files_per_worker[@]}\"\ndo\n echo $each\n output_file=$output_folder/$iteration/\"$each\".zarr\n echo $output_file\n \n if [ -f ${output_file} ]\n\tthen\n echo ${i} \"already created\"\n\t\tcontinue\n fi\n python 03_predict/$setup/predict.py $expname $iteration $clipmax $each\n\ndone\n\necho \"Finish worker\"\n"
},
{
"alpha_fraction": 0.5558596849441528,
"alphanum_fraction": 0.57485032081604,
"avg_line_length": 28.371858596801758,
"blob_id": "83764a5b526026dc6be482b7069bd3eec808f86d",
"content_id": "51e84847da6e2cd1c794cc652ebd56a409826f11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5845,
"license_type": "no_license",
"max_line_length": 145,
"num_lines": 199,
"path": "/flylight/03_predict/setup02/predict.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import gunpowder as gp\nimport numpy as np\nimport neurolight.gunpowder as nl\nimport h5py\nimport sys\nimport glob\nimport os\nimport json\nimport logging\nfrom datetime import datetime\nimport zarr\n\n\nclass Convert(gp.BatchFilter):\n\n def __init__(self, array, dtype):\n\n self.array = array\n self.dtype = dtype\n\n def process(self, batch, request):\n\n if self.array not in batch.arrays:\n return\n\n array = batch.arrays[self.array]\n\n try:\n array.data = array.data.astype(self.dtype)\n except:\n print(\"Cannot convert!\")\n\n array.spec.dtype = self.dtype\n\n\ndef predict(data_dir,\n train_dir,\n iteration,\n sample,\n test_net_name='train_net',\n train_net_name='train_net',\n output_dir='.',\n clip_max=1000\n ):\n\n if \"hdf\" not in data_dir:\n return\n\n print(\"Predicting \", sample)\n print('checkpoint: ', os.path.join(train_dir, train_net_name + '_checkpoint_%d' % iteration))\n\n checkpoint = os.path.join(train_dir, train_net_name + '_checkpoint_%d' % iteration)\n\n with open(os.path.join(train_dir, test_net_name + '_config.json'), 'r') as f:\n net_config = json.load(f)\n\n with open(os.path.join(train_dir, test_net_name + '_names.json'), 'r') as f:\n net_names = json.load(f)\n\n # ArrayKeys\n raw = gp.ArrayKey('RAW')\n pred_mask = gp.ArrayKey('PRED_MASK')\n hls = gp.ArrayKey('HLS')\n\n input_shape = gp.Coordinate(net_config['input_shape'])\n output_shape = gp.Coordinate(net_config['output_shape'])\n\n voxel_size = gp.Coordinate((1, 1, 1))\n context = gp.Coordinate(input_shape - output_shape) / 2\n\n # add ArrayKeys to batch request\n request = gp.BatchRequest()\n request.add(raw, input_shape, voxel_size=voxel_size)\n request.add(pred_mask, output_shape, voxel_size=voxel_size)\n request.add(hls, input_shape, voxel_size=voxel_size)\n\n print(\"chunk request %s\" % request)\n\n source = (\n gp.Hdf5Source(\n data_dir,\n datasets={\n raw: sample + '/raw',\n },\n array_specs={\n raw: gp.ArraySpec(interpolatable=True, dtype=np.uint16, voxel_size=voxel_size),\n },\n ) +\n gp.Pad(raw, context) +\n nl.Clip(raw, 0, clip_max) +\n gp.Normalize(raw, factor=1.0/clip_max) +\n nl.ConvertRgbToHls(raw, hls)\n )\n\n with gp.build(source):\n raw_roi = source.spec[raw].roi\n print(\"raw_roi: %s\" % raw_roi)\n sample_shape = raw_roi.grow(-context, -context).get_shape()\n\n print(sample_shape)\n\n # create zarr file with corresponding chunk size\n zf = zarr.open(os.path.join(output_dir, sample + '.zarr'), mode='w')\n\n #zf.create('volumes/raw', shape=[3,] + list(sample_shape), chunks=[3,] + list(input_shape), dtype=np.float16)\n #zf['volumes/raw'].attrs['offset'] = [0, 0, 0]\n #zf['volumes/raw'].attrs['resolution'] = [1, 1, 1]\n\n zf.create('volumes/pred_mask', shape=sample_shape, chunks=output_shape, dtype=np.float16)\n zf['volumes/pred_mask'].attrs['offset'] = [0, 0, 0]\n zf['volumes/pred_mask'].attrs['resolution'] = [1, 1, 1]\n\n pipeline = (\n source +\n gp.tensorflow.Predict(\n graph=os.path.join(train_dir, test_net_name + '.meta'),\n checkpoint=checkpoint,\n inputs={\n net_names['raw']: raw,\n },\n outputs={\n net_names['pred']: pred_mask,\n },\n array_specs={\n pred_mask: gp.ArraySpec(\n roi=raw_roi.grow(-context, -context),\n voxel_size=voxel_size),\n },\n max_shared_memory=1024*1024*1024\n ) +\n Convert(pred_mask, np.float16) +\n gp.ZarrWrite(\n dataset_names={\n #raw: 'volumes/raw',\n pred_mask: 'volumes/pred_mask',\n },\n output_dir=output_dir,\n output_filename=sample + '.zarr',\n compression_type='gzip',\n dataset_dtypes={\n #raw: np.float16,\n pred_mask: np.float16}\n ) +\n\n # show a summary of time spend in each node every x iterations\n gp.PrintProfilingStats(every=100) +\n gp.Scan(reference=request, num_workers=5, cache_size=50)\n )\n\n with gp.build(pipeline):\n\n pipeline.request_batch(gp.BatchRequest())\n\n\nif __name__ == \"__main__\":\n\n data_dir = \"/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data/flylight_270319_val.hdf\"\n #sample = \"BJD_118D12_AE_01-20171020_66_D2\"\n root = '/groups/kainmueller/home/maisl/workspace/neurolight/experiments'\n experiment = 'setup01_030419_01'\n iteration = 100000\n test_net_name = 'test_net'\n train_net_name = 'train_net'\n clip_max = 1000\n \n #os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n if len(sys.argv) > 1:\n experiment = sys.argv[1]\n iteration = int(sys.argv[2])\n \n if len(sys.argv) > 3:\n clip_max = int(sys.argv[3])\n\n if len(sys.argv) > 4:\n sample = sys.argv[4]\n\n print(\"arguments: \", experiment, iteration, clip_max, sample)\n\n output_dir = os.path.join(root, experiment, 'test', '%d' % iteration)\n train_dir = os.path.join(root, experiment, 'train')\n try:\n os.makedirs(output_dir)\n except:\n pass\n\n logging.basicConfig(level=logging.INFO)\n\n start = datetime.now()\n\n print('call: ', data_dir, train_dir, iteration, sample, test_net_name, train_net_name, output_dir, clip_max)\n\n predict(\n data_dir, train_dir, iteration, sample,\n test_net_name=test_net_name,\n train_net_name=train_net_name,\n output_dir=output_dir, clip_max=clip_max)\n\n print(datetime.now() - start)\n"
},
{
"alpha_fraction": 0.5614985823631287,
"alphanum_fraction": 0.585532546043396,
"avg_line_length": 30.887218475341797,
"blob_id": "51a40cf36a2f98b764cd1b23ed5aea730e73ad74",
"content_id": "8161e2dfa407e2af8478361492c6e54f6e05a5df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4244,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 133,
"path": "/flylight/04_evaluate/evaluate.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport zarr\nimport h5py\nimport voi\nimport rand\nimport iou\nimport sys\nimport glob\nimport os\nfrom skimage import io, morphology, measure\nimport glob\nimport csv\n#from matplotlib import pyplot as plt\nfrom datetime import datetime\n\n\ndef evaluate(pred_folder, data_folder, dataset, output_folder, small_objects_size=20):\n\n #thresholds = [0.9, 0.95, 0.99]\n thresholds = [0.9]\n\n hf = h5py.File(os.path.join(data_folder, dataset + '.hdf'), 'r')\n ds_samples = list(hf.keys())\n pred_samples = glob.glob(os.path.join(pred_folder, \"*.zarr\"))\n print(pred_samples)\n print('output folder: ', output_folder)\n\n cf = open(os.path.join(output_folder, 'iou.csv'), 'w')\n writer = csv.writer(cf, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['sample', ] + thresholds)\n iou_results = {}\n\n for sample in pred_samples:\n\n name = os.path.basename(sample)[:-5]\n\n if name not in ds_samples:\n print(name, \" not in gt dataset! Skipping...\")\n continue\n\n gt = np.asarray(hf[name + '/fg'], dtype=np.uint8)\n raw = np.asarray(hf[name + '/raw'])\n print('raw shape: ', raw.shape, raw.dtype)\n raw = (np.clip(raw, 0, 1000) / 1000. * 255).astype(np.uint8)\n raw_mip = np.moveaxis(np.max(raw, axis=1), 0, 2)\n\n zf = zarr.open(sample)\n pred = np.asarray(zf['volumes/pred_mask'])\n\n mip = np.max(gt, axis=0)\n mip[mip > 0] = 255\n io.imsave(os.path.join(output_folder, name + '_gt.png'), mip)\n io.imsave(os.path.join(output_folder, name + '_raw.png'), raw_mip)\n\n results = []\n\n for thresh in thresholds:\n\n print('sample: ', name)\n\n mask = (pred >= thresh).astype(np.uint8)\n mask = morphology.remove_small_objects(\n measure.label(mask, background=0, connectivity=1),\n min_size=small_objects_size, connectivity=1)\n mask = (mask > 0).astype(np.uint8)\n\n #result = voi.voi(mask, gt)\n #print('threshold: ', thresh, ', result: ', result)\n\n #result = rand.adapted_rand(mask, gt)\n #print('adapted rand for threshold: ', thresh, ', result: ', result)\n\n result = iou.intersection_over_union(np.expand_dims(mask, -1), gt)\n print('iou for threshold: ', thresh, ', result: ', result)\n results.append(result[1])\n\n mip = np.max(mask, axis=0)\n idx = mip > 0\n mip[idx] = 255\n io.imsave(os.path.join(output_folder, name + '_mask_' + str(thresh) + '.png'), mip)\n\n #mip = np.zeros_like(raw_mip, dtype=np.uint8)\n\n raw_mip[idx] = (0.7 * np.array([139, 0, 128]) + 0.3 * raw_mip[idx]).astype(np.uint8)\n #raw_mip = (0.5 * raw_mip + 0.5 * mip).astype(np.uint8)\n io.imsave(os.path.join(output_folder, name + '_overlay_' + str(thresh) + '.png'), raw_mip)\n\n iou_results[name] = results\n print(len(iou_results))\n\n avg = None\n for k,v in iou_results.items():\n writer.writerow([k, ] + v)\n if avg is None:\n avg = np.asarray(v)\n else:\n avg += np.asarray(v)\n\n avg /= len(iou_results)\n writer.writerow(['Average', ] + list(avg))\n\n\nif __name__ == \"__main__\":\n\n data_folder = \"/groups/kainmueller/home/maisl/workspace/patch_instance_segmentation/patch_instance_segmentation/01_data\"\n dataset = \"flylight_060419_val\"\n\n root = '/groups/kainmueller/home/maisl/workspace/neurolight/experiments'\n experiment = 'setup07_070419_00'\n iteration = 100000\n small_objects_size = 300\n\n if len(sys.argv) > 1:\n experiment = sys.argv[1]\n iteration = int(sys.argv[2])\n\n if len(sys.argv) > 3:\n small_objects_size = int(sys.argv[3])\n\n if len(sys.argv) > 4:\n dataset = sys.argv[4]\n\n print('evaluate for ', experiment, iteration, small_objects_size, dataset)\n\n pred_folder = os.path.join(root, experiment, 'test', '%d' % iteration)\n output_folder = os.path.join(root, experiment, 'eval', '%d' % iteration)\n\n try:\n os.makedirs(output_folder)\n except OSError:\n pass\n\n evaluate(pred_folder, data_folder, dataset, output_folder, small_objects_size)\n\n\n\n"
},
{
"alpha_fraction": 0.5832363367080688,
"alphanum_fraction": 0.5975940823554993,
"avg_line_length": 30.814815521240234,
"blob_id": "7da2a53be165b7cbae4443bc1f8b50288b6cd287",
"content_id": "d795e2a97672109ba98d6beadd3992aad917dd2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2577,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 81,
"path": "/synthetic/lines/neuroglancer_snapshot.py",
"repo_name": "maisli/neurolight_experiments",
"src_encoding": "UTF-8",
"text": "import daisy\nimport neuroglancer\nimport numpy as np\nimport sys\nimport itertools\n\nneuroglancer.set_server_bind_address('0.0.0.0')\n\nf = sys.argv[1]\nraw = daisy.open_ds(f, 'volumes/raw')\ngt = daisy.open_ds(f, 'volumes/gt')\ngt_fg = daisy.open_ds(f, 'volumes/gt_fg')\nembedding = daisy.open_ds(f, 'volumes/embedding')\nfg = daisy.open_ds(f, 'volumes/fg')\nmaxima = daisy.open_ds(f, 'volumes/maxima')\ngradient_embedding = daisy.open_ds(f, 'volumes/gradient_embedding')\ngradient_fg = daisy.open_ds(f, 'volumes/gradient_fg')\n\nemst = daisy.open_ds(f, 'emst')\nedges_u = daisy.open_ds(f, 'edges_u')\nedges_v = daisy.open_ds(f, 'edges_v')\n\ndef add(s, a, name, shader=None, visible=True):\n\n if shader == 'rgb':\n shader=\"\"\"void main() { emitRGB(vec3(toNormalized(getDataValue(0)), toNormalized(getDataValue(1)), toNormalized(getDataValue(2)))); }\"\"\"\n\n kwargs = {}\n\n if shader is not None:\n kwargs['shader'] = shader\n\n data = np.expand_dims(a.to_ndarray(), axis=0)\n if len(data.shape) == 4:\n data = np.transpose(data, axes=[1, 0, 2, 3])\n\n s.layers.append(\n name=name,\n layer=neuroglancer.LocalVolume(\n data=data,\n offset=a.roi.get_offset()[::-1] + (0,),\n voxel_size=a.voxel_size[::-1] + (1,)\n ),\n visible=visible,\n **kwargs)\n\nembedding.materialize()\nmi = np.amin(embedding.data)\nma = np.amax(embedding.data)\nembedding.data = (embedding.data - mi)/(ma - mi)\nprint(\"Scaled embedding with %.3f\"%(ma - mi))\n\nviewer = neuroglancer.Viewer()\nwith viewer.txn() as s:\n add(s, raw, 'raw', visible=False)\n add(s, gt, 'gt', visible=False)\n add(s, gt_fg, 'gt_fg', visible=False)\n add(s, embedding, 'embedding', shader='rgb')\n add(s, fg, 'fg', visible=False)\n add(s, maxima, 'maxima')\n add(s, gradient_embedding, 'd_embedding', shader='rgb', visible=False)\n add(s, gradient_fg, 'd_fg', shader='rgb', visible=False)\n\n mst = []\n node_id = itertools.count(start=1)\n for edge, u, v in zip(emst.to_ndarray(), edges_u.to_ndarray(), edges_v.to_ndarray()):\n print(edge[2])\n if edge[2] > 1.0:\n continue\n pos_u = daisy.Coordinate(u[-3:]*100) + ((0,) + gt.roi.get_offset())\n pos_v = daisy.Coordinate(v[-3:]*100) + ((0,) + gt.roi.get_offset())\n mst.append(neuroglancer.LineAnnotation(\n point_a=pos_u[::-1],\n point_b=pos_v[::-1],\n id=next(node_id)))\n\n s.layers.append(\n name='mst',\n layer=neuroglancer.AnnotationLayer(annotations=mst)\n )\nprint(viewer)\n"
}
] | 15 |
nadezhda93/OpenCV
|
https://github.com/nadezhda93/OpenCV
|
f6d3a8370e67f34f7b095427c14b1bc47c4b0f86
|
010201bbe519e06f3ebfad99134975407c46ffa2
|
51e5c727fe2113cc25cc188c9d02492c63d4a98d
|
refs/heads/master
| 2021-03-16T10:02:57.841646 | 2015-11-29T20:28:39 | 2015-11-29T20:28:39 | 46,127,064 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7113526463508606,
"alphanum_fraction": 0.72826087474823,
"avg_line_length": 24.121212005615234,
"blob_id": "f7d71ff2852b63e8f2d806dc440e8c2a0ab25f18",
"content_id": "3542d404b481751a52cd534f3b80023ea3069f04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 828,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 33,
"path": "/VideoTut.py",
"repo_name": "nadezhda93/OpenCV",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport cv2\n\n# create an object for the video, the argument is the number of the \n# camera, in this case only one. Replace with path or file \n# name to play from file\ncap = cv2.VideoCapture(0)\nwin_length = cap.get(3)\nwin_height = cap.get(4) \nprint 'length', win_length\nprint 'height', win_height\n\nwhile(True):\n\t#Capture frame by frame from object\n\t# returns a boolean TRUE if frame is read correctly\n\tret, frame = cap.read()\n\n\t#Operations on a frame - convert to greyscale\n\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n\t# Original RGB feed from webcam\n\tcv2.imshow('original', frame)\n\n\t# Show the resulting frame\n\tcv2.imshow('frame',gray)\n\n\t#close everything when q is pressed\n\tif cv2.waitKey(1) & 0xFF == ord('q'):\n\t\tbreak\n\n#When everything is done, release the capture\ncap.release()\ncv2.destroyAllWindows()"
},
{
"alpha_fraction": 0.7002426981925964,
"alphanum_fraction": 0.7233009934425354,
"avg_line_length": 23.264705657958984,
"blob_id": "fdf9e4dcc3839111cdc6cb4cc47a6aee0bbd698b",
"content_id": "69ce6a3975fe2eab909574f07570676c100b0486",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 824,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 34,
"path": "/simpleGui.py",
"repo_name": "nadezhda93/OpenCV",
"src_encoding": "UTF-8",
"text": "import Tkinter as tk\nimport numpy as np\nimport cv2\n\ndef showCamera():\n filewin = tk.Toplevel(root)\n frame = Frame(root, width=640, height=480)\n frame.pack()\n cap = cv2.VideoCapture(0)\n ret, frame2 = cap.read()\n cv2.imshow('original', frame2)\n #video.attach_window(frame.window_id())\n \nroot = tk.Tk()\nroot.title(\"Simple Gui\")\nroot.geometry(\"850x600\")\n\n#create the menu bar on the window\nmenubar = tk.Menu(root)\n#create first menu in bar - Show\nshowmenu = tk.Menu(menubar, tearoff=0)\n#first submenu in dropdown list and command associated\nshowmenu.add_command(label=\"Capture Video\", command=showCamera)\n\nshowmenu.add_separator()\nshowmenu.add_command(label=\"Exit\", command=root.quit)\n#set File menu in menubar\nmenubar.add_cascade(label=\"File\", menu=showmenu)\n\n\n\n\nroot.config(menu=menubar)\nroot.mainloop()"
}
] | 2 |
ChrisTimperley/Houston
|
https://github.com/ChrisTimperley/Houston
|
78c43df7554b3c8870262b11b4c97fd09023a66f
|
c09e925a0c8082d937dd5e05d237f60929b1d7d2
|
157f6533233f0d48dd0a7a5c72984d8d3d63671c
|
refs/heads/master
| 2020-03-30T21:37:59.921786 | 2019-02-07T19:26:34 | 2019-02-07T19:26:34 | 151,635,546 | 0 | 0 |
MIT
| 2018-10-04T21:03:58 | 2018-10-04T14:26:58 | 2018-10-04T20:43:32 | null |
[
{
"alpha_fraction": 0.5948019027709961,
"alphanum_fraction": 0.6033234000205994,
"avg_line_length": 30.280000686645508,
"blob_id": "6b081276295a3817b5db3c1045b7c18c8f1f969e",
"content_id": "8e54347c7d139deded6033effc3269fc0146f3b6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 2347,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 75,
"path": "/experiments/clustering.R",
"repo_name": "ChrisTimperley/Houston",
"src_encoding": "UTF-8",
"text": "library(\"dtwclust\")\nlibrary(\"optparse\")\n\noption_list = list(\n make_option(\"--data_dir\", type=\"character\", default=NULL, \n help=\"path to the data directory.\"),\n make_option(c(\"-c\", \"--command\"), type=\"character\", default=NULL, \n help=\"desired command.\"),\n make_option(\"--output_dir\", type=\"character\", default=\"\", \n help=\"path to the output directory.\"),\n make_option(\"--list_of_vars\", type=\"character\", default=NULL,\n help=\"comma separated list of variables to consider for clustering\"),\n make_option(c(\"-n\", \"--dp_num\"), type=\"integer\", default=-1,\n help=\"number of datapoints per trace.\"),\n make_option(c(\"-k\", \"--clusters\"), type=\"integer\", default=3, \n help=\"number of clusters (k).\"),\n make_option(\"--fuzzy\", action=\"store_true\", default=FALSE, \n help=\"run the clustering in fuzzy mode.\")\n); \n\nopt_parser = OptionParser(option_list=option_list);\nopt = parse_args(opt_parser);\n\nif(is.null(opt$data_dir) || is.null(opt$command)) {\n print_help(opt_parser)\n stop(\"Required arguments missing!\")\n}\n\nvarlist = NULL\nif(!is.null(opt$list_of_vars)){\n varlist = unlist(strsplit(opt$list_of_vars, split=\",\"))\n}\n\nallfiles <- list.files(path=opt$data_dir, pattern=paste(\"factory.\", opt$command, \".+.csv\", sep=\"\"), full.names=TRUE, recursive=FALSE)\n\nmyData <- list()\nfiles <- vector()\ni <- 1\nn <- opt$dp_num\nfor (f in allfiles) {\n m <- read.csv(f, header=TRUE)\n# m <- as.matrix(m)\n if (is.null(varlist)){\n varlist = colnames(m)\n }\n m <- m[,varlist]\n if (n != -1) {\n l <- floor(length(m[, 1]) / n)\n if (l == 0) {\n next\n }\n m <- m[seq(0, n-1) * l + 1 , ]\n }\n myData[[i]] <- as.matrix(m)\n files[i] <- f\n i <- i+1\n}\n\nwrite(files, file=paste(opt$output_dir, opt$command, \"_files.txt\", sep=\"\"))\n\n#myData2 <- zscore(myData)\n#m <- read.csv(files[1], header=TRUE)\n\nif (!opt$fuzzy) {\n mvc <- tsclust(myData, k = opt$clusters, distance = \"dtw\", seed = 390L)\n} else {\n mvc <- tsclust(myData, k = opt$clusters, type = \"fuzzy\", seed = 390L)\n}\npdf(paste(opt$output_dir, opt$command, \".pdf\", sep=\"\"))\nplot(mvc)\ndev.off()\nwrite(paste(\"Int64\", toString(mvc@cluster), sep = \"\\n\"), file=paste(opt$output_dir, opt$command, \"_labels.txt\", sep=\"\"))\nsave.image(file=paste(opt$output_dir, opt$command, \".RData\", sep=\"\"))\n\nprint(mvc@clusinfo)\n\n"
},
{
"alpha_fraction": 0.49810367822647095,
"alphanum_fraction": 0.4996488392353058,
"avg_line_length": 40.87647247314453,
"blob_id": "6e2cd61b5a6ffccb65959dd037728af03b615abe",
"content_id": "ae179958f3551962f4e1647e02928a3adb08633b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7119,
"license_type": "permissive",
"max_line_length": 152,
"num_lines": 170,
"path": "/experiments/verify_test_data.py",
"repo_name": "ChrisTimperley/Houston",
"src_encoding": "UTF-8",
"text": "import subprocess\nimport tempfile\nimport os\nimport json\nimport csv\n\nimport argparse\nfrom ruamel.yaml import YAML\n\nfrom enum import Enum\n\nclass Status:\n ACCEPTED = 'ACCEPTED'\n REJECTED = 'REJECTED'\n UNSPECIFIED = 'UNSPECIFIED'\n\n\ndef setup_arg_parser():\n parser = argparse.ArgumentParser(description='Validate test traces')\n parser.add_argument('test_database', type=str, action='store',\n help='path to test database yaml file.')\n parser.add_argument('models_dir', type=str, action='store',\n help='path to directory with learned models.')\n parser.add_argument('GBDTs_path', type=str, action='store',\n help='path to GBDTs.')\n parser.add_argument('--threshold', type=float, action='store',\n default=0.4,\n help='threshold for accepting a trace')\n parser.add_argument('--ignore-cat', action='store_true',\n default=False,\n help='ignore categorical fields of the data.')\n parser.add_argument('--separate-params', action='store_true',\n default=False,\n help='put parameters in a separate file')\n parser.add_argument('--output_file', action='store', type=str,\n default='test_res.json',\n help='the file where the results will be stored')\n args = parser.parse_args()\n return args\n\n\ndef parse_data(all_data):\n cmd_based_dict = {}\n result = []\n for i, m in enumerate(all_data):\n result.append({'gt': [], 'mu': []})\n for j in range(len(m[\"gt\"])):\n trace = m[\"gt\"][j]\n result[i]['gt'].append([])\n for k in range(len(trace['commands'])):\n result[i]['gt'][j].append(Status.UNSPECIFIED)\n c = trace['commands'][k]\n c_type = c['command']['type']\n typ = cmd_based_dict.get(c_type)\n if not typ:\n cmd_based_dict[c_type] = [(i, 'gt', j, k),]\n else:\n typ.append((i, 'gt', j, k))\n for j in range(len(m[\"mu\"])):\n trace = m[\"mu\"][j]\n result[i]['mu'].append([])\n for k in range(len(trace['commands'])):\n result[i]['mu'][j].append(Status.UNSPECIFIED)\n c = trace['commands'][k]\n c_type = c['command']['type']\n typ = cmd_based_dict.get(c_type)\n if not typ:\n cmd_based_dict[c_type] = [(i, 'mu', j, k),]\n else:\n typ.append((i, 'mu', j, k))\n return cmd_based_dict, result\n\ndef check_against_model(all_data, cmd_based_dict, result, models_dir, GBDTs_path, ignore_cat, separate_params, threshold=0.4):\n julia_command = 'julia ' + str(os.path.join(GBDTs_path, 'test.jl')) + ' {} {}'\n for cmd in cmd_based_dict.keys():\n model = os.path.join(models_dir, \"{}.jld\".format(cmd[len('factory.'):]))\n if not os.path.isfile(model):\n print(\"Model doesn't exist for command {}\".format(cmd))\n continue\n dirpath = tempfile.mkdtemp()\n print(\"tempdir: {}\".format(dirpath))\n indexes = []\n l = 1\n keys = []\n dict_writer = None\n with open(os.path.join(dirpath, \"data.csv.gz\"), \"w\") as output_file:\n for i, t, j, k in cmd_based_dict[cmd]:\n print(\"{} {} {} {}\".format(i, t, j, k))\n indexes.append(str(l))\n c = all_data[i][t][j]['commands'][k]\n states = c['states']\n if not dict_writer:\n if not ignore_cat:\n keys = list(c['states'][0].keys())\n else:\n keys = [n for n in sorted(c['states'][0]) if type(c['states'][0][n]) == float]\n if not separate_params:\n if not ignore_cat:\n p = {'p_{}'.format(key): v for key, v in c['command']['parameters'].items()}\n else:\n p = {'p_{}'.format(key): v for key, v in c['command']['parameters'].items() if type(v) not in [bool, str]}\n for s in states:\n s.update(p)\n if not ignore_cat:\n for s in states:\n if \"mode\" in s:\n s[\"mode\"] = 0 if s[\"mode\"] == \"AUTO\" else 1 # TODO fix this. There are other modes that AUTO and GUIDED\n for key,v in s.items():\n if type(v) == bool:\n s[key] = int(v)\n if not dict_writer:\n if not separate_params:\n keys.extend(sorted(p.keys()))\n dict_writer = csv.DictWriter(output_file, keys, extrasaction='ignore')\n dict_writer.writeheader()\n dict_writer.writerows(states)\n l += len(states)\n with open(os.path.join(dirpath, \"_meta.txt\"), \"w\") as f:\n f.write(\",\".join(indexes))\n print(\"Data for command {} is ready\".format(cmd))\n jc = julia_command.format(dirpath, model)\n julia_result = subprocess.check_output(jc, shell=True).decode().strip()\n lines = julia_result.splitlines()\n acceptance = eval(lines[-1])\n assert type(acceptance) == list\n assert len(acceptance) == len(cmd_based_dict[cmd])\n print(\"Acceptance: {}\".format(acceptance))\n for index in range(len(acceptance)):\n i, t, j, k = cmd_based_dict[cmd][index]\n result[i][t][j][k] = Status.ACCEPTED if acceptance[index] < threshold else Status.REJECTED\n return result\n\n\ndef write_result(result, output_file):\n with open(output_file, 'w') as f:\n YAML().dump(result, f)\n\nif __name__==\"__main__\":\n args = setup_arg_parser()\n entries = None\n results = []\n with open(args.test_database, 'r') as f:\n entries = YAML().load(f)\n\n all_data = []\n for e in entries['entries']:\n test_data = None\n with open(e['trace'], 'r') as f:\n test_data = json.load(f)\n gt_data = None\n with open(e['oracle'], 'r') as f:\n gt_data = json.load(f)\n all_data.append({'mu': test_data['traces'],\n 'gt': gt_data['traces']})\n print(\"Len all_data: %d\", len(all_data))\n cmd_based_dict, result = parse_data(all_data)\n print(cmd_based_dict)\n res = check_against_model(all_data, cmd_based_dict, result, args.models_dir, args.GBDTs_path, args.ignore_cat, args.separate_params, args.threshold)\n assert len(res) == len(entries['entries'])\n print(\"Final: {}\".format(res))\n\n for i in range(len(res)):\n e = entries['entries'][i]\n results.append({'diff': e['diff'],\n 'trace': e['trace'],\n 'oracle': e['oracle'],\n 'gt': res[i]['gt'],\n 'mu': res[i]['mu']})\n\n write_result(results, args.output_file)\n"
},
{
"alpha_fraction": 0.6781235337257385,
"alphanum_fraction": 0.6785880327224731,
"avg_line_length": 30.202898025512695,
"blob_id": "e42b10067a3c5f41086ed00b4f4f9280f18ebb9b",
"content_id": "503f16acf417b2603c13675d454d8eaf201b96c4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2153,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 69,
"path": "/experiments/filter_truth.py",
"repo_name": "ChrisTimperley/Houston",
"src_encoding": "UTF-8",
"text": "from typing import Iterator, Tuple, Set, List, Dict, Any, Optional, Type\nimport argparse\nimport logging\nimport sys\nimport os\n\nfrom ruamel.yaml import YAML\nimport yaml\nfrom houston.mission import Mission\n\nfrom compare_traces import load_file as load_traces_file\nfrom compare_traces import is_truth_valid\n\nlogger = logging.getLogger('houston') # type: logging.Logger\nlogger.setLevel(logging.DEBUG)\n\nDESCRIPTION = \"Filter out ground truth data.\"\n\nVALID_LIST_OUTPUT = \"valid_list.yml\"\n\n\ndef setup_logging(verbose: bool = False) -> None:\n log_to_stdout = logging.StreamHandler()\n log_to_stdout.setLevel(logging.DEBUG if verbose else logging.INFO)\n logging.getLogger('houston').addHandler(log_to_stdout)\n logging.getLogger('experiment').addHandler(log_to_stdout)\n\n\ndef parse_args():\n p = argparse.ArgumentParser(description=DESCRIPTION)\n p.add_argument('oracle', type=str, help='path to oracle trace directory.')\n p.add_argument('--verbose', action='store_true',\n help='increases logging verbosity')\n return p.parse_args()\n\n\ndef filter_truth_traces(dir_oracle: str) -> List[str]:\n trace_filenames = \\\n [fn for fn in os.listdir(dir_oracle) if fn.endswith('.json')]\n valid_traces = []\n for fn in trace_filenames:\n fn_trace = os.path.join(dir_oracle, fn)\n mission, oracle_traces = load_traces_file(fn_trace)\n oracle_traces = [t for t in oracle_traces if t.commands]\n if is_truth_valid(oracle_traces):\n valid_traces.append(fn)\n else:\n logger.debug(\"trace %s is invalid\", fn)\n return valid_traces\n\n\ndef main():\n args = parse_args()\n setup_logging(verbose=args.verbose)\n dir_oracle = args.oracle\n\n if not os.path.exists(dir_oracle):\n logger.error(\"oracle directory not found: %s\", dir_oracle)\n sys.exit(1)\n\n # obtain a list of oracle traces\n trace_filenames = filter_truth_traces(dir_oracle)\n logger.info(\"Total number of %d valid truth\", len(trace_filenames))\n\n with open(os.path.join(dir_oracle, VALID_LIST_OUTPUT), \"w\") as f:\n YAML().dump(trace_filenames, f)\n\nif __name__ == '__main__':\n main()\n"
}
] | 3 |
ahmedisam99/python-django-a2
|
https://github.com/ahmedisam99/python-django-a2
|
4e5732761b1a697a6a4591d1c86c97b46e602247
|
66eb1f499dd848ce9cf6f86222fb60ea29b6838b
|
23f21d814b573376b7da221d2a453e9c55e8794d
|
refs/heads/master
| 2020-06-15T13:26:46.898122 | 2019-07-07T14:02:27 | 2019-07-07T14:02:27 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6820448637008667,
"alphanum_fraction": 0.6820448637008667,
"avg_line_length": 41.21052551269531,
"blob_id": "1ac0c81743c48b51d99b93440f810d783b25eed2",
"content_id": "5b487f80d050baca67b628d25c8467b450edcb53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 802,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 19,
"path": "/index/urls.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django.urls import (path, include)\nfrom rest_framework_simplejwt.views import (\n TokenObtainPairView, TokenRefreshView)\nfrom .views import login_view\nfrom rest_framework.authtoken.views import obtain_auth_token\nfrom django.contrib.auth.views import LoginView\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('books/', include('book.urls')),\n path('users/', include('user.urls')),\n path('login/', LoginView.as_view(template_name='registration/login.html',\n redirect_authenticated_user=True,), name=\"login\"),\n # path('login/', login_view),\n path('api/token/', obtain_auth_token),\n # path('api/token/', TokenObtainPairView.as_view()),\n # path('api/token/refresh/', TokenRefreshView.as_view()),\n]\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 20.11111068725586,
"blob_id": "186104c11b9ca9e104df316681d9e579875c9276",
"content_id": "1c700684ad6c6fe9a221dda5b6154a5b6e986b20",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 190,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 9,
"path": "/user/urls.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom rest_framework.routers import DefaultRouter\nfrom .views import UserView\n\nrouter = DefaultRouter()\nrouter.register('', UserView)\n\n\nurlpatterns = router.urls\n"
},
{
"alpha_fraction": 0.7291666865348816,
"alphanum_fraction": 0.7291666865348816,
"avg_line_length": 18.200000762939453,
"blob_id": "a7d5c6f0715defa58af646b0a1627b54e7166f0e",
"content_id": "ccbc6c44738438d13cfc3d7ba1a5aab1748eb0a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 96,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 5,
"path": "/index/views.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\n\n\ndef login_view(req):\n return render(req, 'login.html')\n"
},
{
"alpha_fraction": 0.8144329786300659,
"alphanum_fraction": 0.8144329786300659,
"avg_line_length": 28.100000381469727,
"blob_id": "6ead74663f5e7edeb14ce08b9a3efc941fc82143",
"content_id": "53b5e3cca802161100c74d2b476f60d95dd34f7d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 291,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 10,
"path": "/user/views.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom rest_framework.viewsets import ModelViewSet\nfrom .models import User\nfrom .serializers import UserSerializer\nfrom django.http import HttpResponse\n\n\nclass UserView(ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n"
},
{
"alpha_fraction": 0.8070865869522095,
"alphanum_fraction": 0.8070865869522095,
"avg_line_length": 27.22222137451172,
"blob_id": "5a555feca58d405b471f3e90f3bda97113c5b190",
"content_id": "dc1cda512837d42b4daa7a95633e7f112be4b8f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 254,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 9,
"path": "/book/views.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom rest_framework.viewsets import ModelViewSet\nfrom .models import Book\nfrom .serializers import BookSerializer\n\n\nclass BookView(ModelViewSet):\n queryset = Book.objects.all()\n serializer_class = BookSerializer\n"
},
{
"alpha_fraction": 0.7330827116966248,
"alphanum_fraction": 0.7330827116966248,
"avg_line_length": 23.18181800842285,
"blob_id": "c753666edd94858a9a64304404bb835d566703af",
"content_id": "57f98f26d03d08462576d2a3682436829fedcbc6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 266,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 11,
"path": "/book/urls.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\nfrom .views import BookView\n\nrouter = DefaultRouter()\nrouter.register('', BookView)\n\n# urlpatterns = router.urls\nurlpatterns = [\n path('', BookView.as_view({'get': 'list'}))\n]\n"
},
{
"alpha_fraction": 0.6896551847457886,
"alphanum_fraction": 0.7068965435028076,
"avg_line_length": 28,
"blob_id": "cf8204852c9163b0f54f4d1b2c5a233a6e899efe",
"content_id": "c3802417391ae30196f18fe537238b8527914f63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 348,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 12,
"path": "/book/models.py",
"repo_name": "ahmedisam99/python-django-a2",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom user.models import User\n\n\nclass Book(models.Model):\n title = models.CharField(max_length=50)\n desc = models.CharField(max_length=1000)\n pub_date = models.DateField(verbose_name=\"Publish Date\")\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.title\n"
}
] | 7 |
amlivingamliving/ryandgood-coding-challenge-soccer
|
https://github.com/amlivingamliving/ryandgood-coding-challenge-soccer
|
75128041994b2e587c2596f0857ba775bd37fd03
|
426e3c0b72882110a31abb0b48bcce4068c709a4
|
dc7fd59816c45403c84283dfc545a4d48793c04d
|
refs/heads/master
| 2023-07-16T22:49:13.544315 | 2021-08-21T15:06:34 | 2021-08-21T15:06:34 | null | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7307692170143127,
"alphanum_fraction": 0.7396449446678162,
"avg_line_length": 15.949999809265137,
"blob_id": "f0d155d5683c6d0402c70bdebaa23264958360c7",
"content_id": "157a2c90c5e26a7d3748062555099ebb85ae2f99",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 338,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 20,
"path": "/README.md",
"repo_name": "amlivingamliving/ryandgood-coding-challenge-soccer",
"src_encoding": "UTF-8",
"text": "# Coding Challenge Soccer\n\nThis implements the scoring code challenge described in ORIGINAL_README.md.\n\n## Running\n\nThis has been implemented in Python 3 and should not require any extra\ndependencies, as everything used is in the stdlib.\n\n### Main script\n\n```\npython3 main.py\n```\n\n### Unit tests\n\n```\npython3 -m unittest tests/test.py\n```"
},
{
"alpha_fraction": 0.5421494245529175,
"alphanum_fraction": 0.5605273842811584,
"avg_line_length": 39.3870964050293,
"blob_id": "a319cdab58bd3ffdef5132f258e426241cd5028a",
"content_id": "a158c3ce35beb7bec7bb10541a64f1234d4af0e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2503,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 62,
"path": "/tests/test.py",
"repo_name": "amlivingamliving/ryandgood-coding-challenge-soccer",
"src_encoding": "UTF-8",
"text": "from main import calculate_standings, parse_input\nimport unittest\nfrom contextlib import redirect_stdout\nimport io\n\n\nclass TestRankings(unittest.TestCase):\n # This test data is the data from good-sample-input.txt\n GOOD_TEST_DATA = [\n ((\"San Jose Earthquakes\", 3), (\"Santa Cruz Slugs\", 3)),\n ((\"Capitola Seahorses\", 1), (\"Aptos FC\", 0)),\n ((\"Felton Lumberjacks\", 2), (\"Monterey United\", 0)),\n ((\"Felton Lumberjacks\", 1), (\"Aptos FC\", 2)),\n ((\"Santa Cruz Slugs\", 0), (\"Capitola Seahorses\", 0)),\n ((\"Monterey United\", 4), (\"San Jose Earthquakes\", 2)),\n ((\"Santa Cruz Slugs\", 2), (\"Aptos FC\", 3)),\n ((\"San Jose Earthquakes\", 1), (\"Felton Lumberjacks\", 4)),\n ((\"Monterey United\", 1), (\"Capitola Seahorses\", 0)),\n ((\"Aptos FC\", 2), (\"Monterey United\", 0)),\n ((\"Capitola Seahorses\", 5), (\"San Jose Earthquakes\", 5)),\n ((\"Santa Cruz Slugs\", 1), (\"Felton Lumberjacks\", 1)),\n ]\n\n # This test data is sourced from bad-sample-input-score.txt\n BAD_TEST_DATA = [\n ((\"San Jose Earthquakes\", 3), (\"Santa Cruz Slugs\", 3)),\n ((\"Capitola Seahorses\", 1), (\"Aptos FC\", 0)),\n ((\"Felton Lumberjacks\", 2), (\"Monterey United\", 0)),\n ((\"Santa Cruz Slugs\", 0), (\"Capitola Seahorses\", 0)),\n ((\"Monterey United\", 4), (\"San Jose Earthquakes\", 2)),\n ((\"Santa Cruz Slugs\", 2), (\"Aptos FC\", 3)),\n ((\"San Jose Earthquakes\", 1), (\"Felton Lumberjacks\", 4)),\n ((\"Monterey United\", 1), (\"Capitola Seahorses\", 0)),\n ((\"Aptos FC\", 2), (\"Monterey United\", 0)),\n ((\"Capitola Seahorses\", 5), (\"San Jose Earthquakes\", 5)),\n ((\"Santa Cruz Slugs\", 1), (\"Felton Lumberjacks\", 1)),\n ]\n\n def test_good_input(self):\n good_input = parse_input(\"tests/input/good-sample-input.txt\")\n assert self.GOOD_TEST_DATA == good_input\n\n def test_bad_input(self):\n # One of the matches for the input in this test has a string instead of\n # an int for the score, and thus the game gets skipped when parsing\n # the input\n bad_input = parse_input(\"tests/input/bad-sample-input-score.txt\")\n assert self.BAD_TEST_DATA == bad_input\n\n def test_calculate_standings(self):\n captured_stdout = io.StringIO()\n with open(\"tests/output/expected-output.txt\", \"r\") as f:\n output = f.read().strip()\n with redirect_stdout(captured_stdout):\n calculate_standings(self.GOOD_TEST_DATA)\n\n standings = captured_stdout.getvalue().strip()\n assert standings == output\n\n\nif __name__ == \"__main__\":\n unittest.main()"
},
{
"alpha_fraction": 0.5965619087219238,
"alphanum_fraction": 0.6032769083976746,
"avg_line_length": 31.66666603088379,
"blob_id": "536e84b778f40d6c96eb913f84088363dd4c055b",
"content_id": "f5016729f7fc4d5f90e128c42ef749f018b8be7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3723,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 114,
"path": "/main.py",
"repo_name": "amlivingamliving/ryandgood-coding-challenge-soccer",
"src_encoding": "UTF-8",
"text": "import argparse\nfrom operator import itemgetter\n\n\ndef parse_input(input_path: str) -> list:\n \"\"\"\n parse_input takes in the input file, and breaks it down into\n a managable data structure. It returns a list of matches,\n with each match represented as a tuple. This tuple is\n itself composed of two tuples, one for each team and their score.\n Tuples all the way down, really.\n \"\"\"\n parsed_input = []\n matches = []\n\n with open(input_path, \"r\") as f:\n for line in f:\n line = line.rstrip()\n matches.append(line.split(sep=\", \"))\n for match in matches:\n first_team = match[0].rsplit(\" \", 1)\n second_team = match[1].rsplit(\" \", 1)\n try:\n first_team_parsed = first_team[0], int(first_team[1])\n second_team_parsed = second_team[0], int(second_team[1])\n except ValueError:\n print(\n f\"Score invalid for match between {first_team_parsed[0]} and {second_team_parsed[0]}, skipping\"\n )\n continue\n match_tuple = first_team_parsed, second_team_parsed\n parsed_input.append(match_tuple)\n return parsed_input\n\n\ndef calculate_standings(parsed_input):\n \"\"\"\n calculate_standings takes the parsed input, and determines the winner\n of each match. If a team has already played, it adds the daily ranking\n to the match_history dictionary and begins a new\n \"\"\"\n day_count = 1\n daily_ranking = {}\n played_today = []\n for match_data in parsed_input:\n team_one, team_one_score = match_data[0]\n team_two, team_two_score = match_data[1]\n team_one_rank = daily_ranking.get(team_one, 0)\n team_two_rank = daily_ranking.get(team_two, 0)\n\n if team_one_score > team_two_score:\n team_one_rank += 3\n elif team_one_score < team_two_score:\n team_two_rank += 3\n elif team_one_score == team_two_score:\n team_one_rank += 1\n team_two_rank += 1\n\n # if a team has already played, it's safe to assume a new day\n if team_one in played_today or team_two in played_today:\n output_prettily(daily_ranking, day_count)\n played_today.clear()\n day_count += 1\n\n # update the daily rankings per team.\n daily_ranking[team_one] = team_one_rank\n daily_ranking[team_two] = team_two_rank\n played_today.append(team_one)\n played_today.append(team_two)\n\n # For the final day, we won't hit the last played_today check\n # so we need to call it one more time here.\n output_prettily(daily_ranking, day_count)\n\n\ndef output_prettily(daily_ranking: dict, day: int):\n \"\"\"\n output_prettily will write the rankings to stdout in the format required.\n \"\"\"\n count = 0\n # sort each item in the daily ranking based on value\n ranked = sorted(daily_ranking.items(), key=itemgetter(1), reverse=True)\n print(\"Matchday \" + str(day))\n while count < 3:\n team, score = ranked[count]\n if score == 1:\n units = \" pt\"\n else:\n units = \" pts\"\n print(team + \", \" + str(score) + units)\n count += 1\n print()\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Calculate soccer rankings after each match day\"\n )\n parser.add_argument(\n \"--input_path\", help=\"path to a file containing matches\", required=True\n )\n parser.add_argument(\n \"--output_path\",\n help=\"path to output results to. Defaults to STDOUT if not set.\",\n required=False,\n )\n args = parser.parse_args()\n\n match_list = parse_input(args.input_path)\n calculate_standings(match_list)\n\n\nif __name__ == \"__main__\":\n main()"
},
{
"alpha_fraction": 0.7302631735801697,
"alphanum_fraction": 0.7302631735801697,
"avg_line_length": 15.777777671813965,
"blob_id": "7d5cf50ea8f48138e2a6edbdbcfb9ad4a56ed22d",
"content_id": "0053759c37bddf2c9829da0faced76e1b924432a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 152,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 9,
"path": "/tests/input/README.md",
"repo_name": "amlivingamliving/ryandgood-coding-challenge-soccer",
"src_encoding": "UTF-8",
"text": "# Test inputs\n\n## good-sample-input\n\nSame as the sample-input.txt provided\n\n## bad-sample-input-score\n\nHas a score defined as a letter and not an int.\n\n"
}
] | 4 |
RyanLeeStratton/CIS433
|
https://github.com/RyanLeeStratton/CIS433
|
d316a983672fe19818ae27fb01182bb08e83fa72
|
c0744a18a0b951aa70c7b06e237827c65964182f
|
1a73f57ad0a495499260e85819df7bcb0d863255
|
refs/heads/master
| 2021-01-15T17:09:54.154379 | 2017-08-08T21:05:05 | 2017-08-08T21:05:05 | 99,735,953 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5741917490959167,
"alphanum_fraction": 0.6197844743728638,
"avg_line_length": 31.026548385620117,
"blob_id": "a4f6594e16948157bb1beaa6fc8e8ba4be9a02be",
"content_id": "5188802a39b1a98439b9ce62c29f503bc011d520",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7238,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 226,
"path": "/audioArray_1.py",
"repo_name": "RyanLeeStratton/CIS433",
"src_encoding": "UTF-8",
"text": "########################################################################################################################\n#audioArray.py\n#Ryan Stratton\n#Fall 2016\n#program that sets up the links to audio files.\n########################################################################################################################\n__author__ = 'Ryan Stratton'\n\nfrom sound import Sound\n\n#sets the array size for each of the three arrays to hold sound file locations\nplayDay = [1]*7\nplayHour = [1]*24\nplayMinutes = [1]*60\nplayInfo = [1]*10\n\n#this section is where the audio for general information is stored\nplayInfo[0] = Sound \\\n( \"wav_files/menus_modes_navigation_f/Set_date_and_time_f.wav\")\nplayInfo[1] = Sound \\\n( \"wav_files/menus_modes_navigation_f/Set_day_of_week_f.wav\")\nplayInfo[2] = Sound \\\n( \"wav_files/menus_modes_navigation_f/Set_hour_f.wav\")\nplayInfo[3] = Sound \\\n( \"wav_files/menus_modes_navigation_f/Set_minutes_f.wav\")\nplayInfo[4] = Sound \\\n( \"wav_files/menus_modes_navigation_f/Press_again_to_quit_f.wav\")\nplayInfo[5] = Sound \\\n( \"wav_files/menus_modes_navigation_f/exiting_program_f.wav\")\nplayInfo[6] = Sound \\\n( \"wav_files/menus_modes_navigation_f/you_selected_f.wav\")\nplayInfo[7] = Sound \\\n( \"wav_files/hours_f/AM_f.wav\")\nplayInfo[8] = Sound \\\n( \"wav_files/hours_f/PM_f.wav\")\nplayInfo[9] = Sound \\\n( \"wav_files/menus_modes_navigation_f/o_clock_f.wav\")\n\n#this section is where the audio for the days of the week is stored\nplayDay[0] = Sound \\\n( \"wav_files/days_of_week_f/friday_f.wav\")\nplayDay[1] = Sound \\\n (\"wav_files/days_of_week_f/saturday_f.wav\")\nplayDay[2] = Sound \\\n (\"wav_files/days_of_week_f/sunday_f.wav\")\nplayDay[3] = Sound \\\n (\"wav_files/days_of_week_f/monday_f.wav\")\nplayDay[4] = Sound \\\n (\"wav_files/days_of_week_f/tuesday_f.wav\")\nplayDay[5] = Sound \\\n (\"wav_files/days_of_week_f/wednesday_f.wav\")\nplayDay[6] = Sound \\\n (\"wav_files/days_of_week_f/thursday_f.wav\")\n\n#this section is where the audio for the hours is stored\nplayHour[0] = Sound \\\n (\"wav_files/hours_f/.1AM_f.wav\")\nplayHour[1] = Sound \\\n (\"wav_files/hours_f/.2AM_f.wav\")\nplayHour[2] = Sound \\\n (\"wav_files/hours_f/.3AM_f.wav\")\nplayHour[3] = Sound \\\n (\"wav_files/hours_f/.4AM_f.wav\")\nplayHour[4] = Sound \\\n (\"wav_files/hours_f/.5AM_f.wav\")\nplayHour[5] = Sound \\\n (\"wav_files/hours_f/.6AM_f.wav\")\nplayHour[6] = Sound \\\n (\"wav_files/hours_f/.7AM_f.wav\")\nplayHour[7] = Sound \\\n (\"wav_files/hours_f/.8AM_f.wav\")\nplayHour[8] = Sound \\\n (\"wav_files/hours_f/.9AM_f.wav\")\nplayHour[9] = Sound \\\n (\"wav_files/hours_f/.10AM_f.wav\")\nplayHour[10] = Sound \\\n (\"wav_files/hours_f/.11AM_f.wav\")\nplayHour[11] = Sound \\\n (\"wav_files/hours_f/.12PM_f.wav\")\nplayHour[12] = Sound \\\n (\"wav_files/hours_f/1PM_f.wav\")\nplayHour[13] = Sound \\\n (\"wav_files/hours_f/2PM_f.wav\")\nplayHour[14] = Sound \\\n (\"wav_files/hours_f/3PM_f.wav\")\nplayHour[15] = Sound \\\n (\"wav_files/hours_f/4PM_f.wav\")\nplayHour[16] = Sound \\\n (\"wav_files/hours_f/5PM_f.wav\")\nplayHour[17] = Sound \\\n (\"wav_files/hours_f/6PM_f.wav\")\nplayHour[18] = Sound \\\n (\"wav_files/hours_f/7PM_f.wav\")\nplayHour[19] = Sound \\\n (\"wav_files/hours_f/8PM_f.wav\")\nplayHour[20] = Sound \\\n (\"wav_files/hours_f/9PM_f.wav\")\nplayHour[21] = Sound \\\n (\"wav_files/hours_f/10PM_f.wav\")\nplayHour[22] = Sound \\\n (\"wav_files/hours_f/11PM_f.wav\")\nplayHour[23] = Sound \\\n (\"wav_files/hours_f/12AM_f.wav\")\n\n#this section will is where the audio for mintues is stored\n\nplayMinutes[0] = Sound \\\n (\"wav_files/minutes_f/00_f.wav\")\nplayMinutes[1] = Sound \\\n (\"wav_files/minutes_f/01_f.wav\")\nplayMinutes[2] = Sound \\\n (\"wav_files/minutes_f/02_f.wav\")\nplayMinutes[3] = Sound \\\n (\"wav_files/minutes_f/03_f.wav\")\nplayMinutes[4] = Sound \\\n (\"wav_files/minutes_f/04_f.wav\")\nplayMinutes[5] = Sound \\\n (\"wav_files/minutes_f/05_f.wav\")\nplayMinutes[6] = Sound \\\n (\"wav_files/minutes_f/06_f.wav\")\nplayMinutes[7] = Sound \\\n (\"wav_files/minutes_f/07_f.wav\")\nplayMinutes[8] = Sound \\\n (\"wav_files/minutes_f/08_f.wav\")\nplayMinutes[9] = Sound \\\n (\"wav_files/minutes_f/09_f.wav\")\nplayMinutes[10] = Sound \\\n (\"wav_files/minutes_f/10_f.wav\")\nplayMinutes[11] = Sound \\\n (\"wav_files/minutes_f/11_f.wav\")\nplayMinutes[12] = Sound \\\n (\"wav_files/minutes_f/12_f.wav\")\nplayMinutes[13] = Sound \\\n (\"wav_files/minutes_f/13_f.wav\")\nplayMinutes[14] = Sound \\\n (\"wav_files/minutes_f/14_f.wav\")\nplayMinutes[15] = Sound \\\n (\"wav_files/minutes_f/15_f.wav\")\nplayMinutes[16] = Sound \\\n (\"wav_files/minutes_f/16_f.wav\")\nplayMinutes[17] = Sound \\\n (\"wav_files/minutes_f/17_f.wav\")\nplayMinutes[18] = Sound \\\n (\"wav_files/minutes_f/18_f.wav\")\nplayMinutes[19] = Sound \\\n (\"wav_files/minutes_f/19_f.wav\")\nplayMinutes[20] = Sound \\\n (\"wav_files/minutes_f/20_f.wav\")\nplayMinutes[21] = Sound \\\n (\"wav_files/minutes_f/21_f.wav\")\nplayMinutes[22] = Sound \\\n (\"wav_files/minutes_f/22_f.wav\")\nplayMinutes[23] = Sound \\\n (\"wav_files/minutes_f/23_f.wav\")\nplayMinutes[24] = Sound \\\n (\"wav_files/minutes_f/24_f.wav\")\nplayMinutes[25] = Sound \\\n (\"wav_files/minutes_f/25_f.wav\")\nplayMinutes[26] = Sound \\\n (\"wav_files/minutes_f/26_f.wav\")\nplayMinutes[27] = Sound \\\n (\"wav_files/minutes_f/27_f.wav\")\nplayMinutes[28] = Sound \\\n (\"wav_files/minutes_f/28_f.wav\")\nplayMinutes[29] = Sound \\\n (\"wav_files/minutes_f/29_f.wav\")\nplayMinutes[30] = Sound \\\n (\"wav_files/minutes_f/30_f.wav\")\nplayMinutes[31] = Sound \\\n (\"wav_files/minutes_f/31_f.wav\")\nplayMinutes[32] = Sound \\\n (\"wav_files/minutes_f/32_f.wav\")\nplayMinutes[33] = Sound \\\n (\"wav_files/minutes_f/33_f.wav\")\nplayMinutes[34] = Sound \\\n (\"wav_files/minutes_f/34_f.wav\")\nplayMinutes[35] = Sound \\\n (\"wav_files/minutes_f/35_f.wav\")\nplayMinutes[36] = Sound \\\n (\"wav_files/minutes_f/36_f.wav\")\nplayMinutes[37] = Sound \\\n (\"wav_files/minutes_f/37_f.wav\")\nplayMinutes[38] = Sound \\\n (\"wav_files/minutes_f/38_f.wav\")\nplayMinutes[39] = Sound \\\n (\"wav_files/minutes_f/39_f.wav\")\nplayMinutes[40] = Sound \\\n (\"wav_files/minutes_f/40_f.wav\")\nplayMinutes[41] = Sound \\\n (\"wav_files/minutes_f/41_f.wav\")\nplayMinutes[42] = Sound \\\n (\"wav_files/minutes_f/42_f.wav\")\nplayMinutes[43] = Sound \\\n (\"wav_files/minutes_f/43_f.wav\")\nplayMinutes[44] = Sound \\\n (\"wav_files/minutes_f/44_f.wav\")\nplayMinutes[45] = Sound \\\n (\"wav_files/minutes_f/45_f.wav\")\nplayMinutes[46] = Sound \\\n (\"wav_files/minutes_f/46_f.wav\")\nplayMinutes[47] = Sound \\\n (\"wav_files/minutes_f/47_f.wav\")\nplayMinutes[48] = Sound \\\n (\"wav_files/minutes_f/48_f.wav\")\nplayMinutes[49] = Sound \\\n (\"wav_files/minutes_f/49_f.wav\")\nplayMinutes[50] = Sound \\\n (\"wav_files/minutes_f/50_f.wav\")\nplayMinutes[51] = Sound \\\n (\"wav_files/minutes_f/51_f.wav\")\nplayMinutes[52] = Sound \\\n (\"wav_files/minutes_f/52_f.wav\")\nplayMinutes[53] = Sound \\\n (\"wav_files/minutes_f/53_f.wav\")\nplayMinutes[54] = Sound \\\n (\"wav_files/minutes_f/54_f.wav\")\nplayMinutes[55] = Sound \\\n (\"wav_files/minutes_f/55_f.wav\")\nplayMinutes[56] = Sound \\\n (\"wav_files/minutes_f/56_f.wav\")\nplayMinutes[57] = Sound \\\n (\"wav_files/minutes_f/57_f.wav\")\nplayMinutes[58] = Sound \\\n (\"wav_files/minutes_f/58_f.wav\")\nplayMinutes[59] = Sound \\\n (\"wav_files/minutes_f/59_f.wav\")\n"
},
{
"alpha_fraction": 0.4812869429588318,
"alphanum_fraction": 0.4968264400959015,
"avg_line_length": 27.024539947509766,
"blob_id": "317b905ae63d883c473a542a82da25251c417bcd",
"content_id": "95f3882dd64fc14cd5a46e8526c546b3433c738a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4569,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 163,
"path": "/set_clock_1.py",
"repo_name": "RyanLeeStratton/CIS433",
"src_encoding": "UTF-8",
"text": "__author__ = 'Ryan Stratton'\n\n########################################################################################################################\n#set_clock.py\n#Ryan Stratton\n#Fall2016\n#build using the sample code provided by the professor.\n#initial design for the first assignment of the User interface at UofO\n#incomplete version, needs better control design\n########################################################################################################################\n\n# Package imports\nimport readchar\n\nfrom audioArray import *\n\n#clock audio controls\nCYCLE_UP = 'j'\nCYCLE_DOWN = 'k'\n\nSET = 'l'\nBACK = ';'\nEXIT = ' '\n\n\n#what state the system is in for setting the audio for the clock\nstate = 0\n\n#place holders for array indexes\ndayPosition = 0\nhourPosition = 0\nminutePosition = 0\nhourSelection = 1\n\n########################################################################################################################\n#state 0 is for setting the day, 1 for the hour and 2 for the minute.\n#the controls currently allow for scrolling foward/backward through each state using the same buttons.\n########################################################################################################################\n\n\n#endless loop to dectect user input and respond\n#currently doesn't use the EXIT key to end the loop (I havn't copied the code from the sample yet)\nplayInfo[0].play_to_end()\n\nwhile True:\n\n inputCharacter = readchar.readchar()\n\n #set day\n if state == 0:\n if inputCharacter == CYCLE_UP:\n dayPosition = (dayPosition + 1)%7\n playDay[dayPosition].play()\n\n\n elif inputCharacter == CYCLE_DOWN:\n dayPosition = (dayPosition - 1) % 7\n playDay[dayPosition].play()\n\n\n elif inputCharacter == SET:\n state = 1\n playInfo[2].play()\n #goes to set hour menu\n\n\n elif inputCharacter == BACK:\n state = 0\n playInfo[1].play()\n #doesn't do anything, audio plays for understanding\n\n\n\n elif inputCharacter == EXIT:\n state = 0\n playInfo[5].play_to_end()\n #exiting progam audio\n break\n\n #end day selection\n\n #set hour\n elif state == 1:\n if inputCharacter == CYCLE_UP:\n hourPosition = (hourPosition + 1) % 24\n hourSelection = (hourSelection +1) % 12\n playHour[hourPosition].play()\n\n if inputCharacter == CYCLE_DOWN:\n hourPosition = (hourPosition - 1) % 24\n hourSelection = (hourSelection - 1) % 12\n playHour[hourPosition].play()\n\n if inputCharacter == SET:\n state = 2\n playInfo[3].play()\n\n if inputCharacter == BACK:\n state = 0\n playInfo[1].play()\n # audio about going back to day selection\n\n if inputCharacter == EXIT:\n state = 1\n playInfo[5].play_to_end()\n # exiting progam audio\n break\n\n # end hour selection\n\n #set minute\n elif state == 2:\n if inputCharacter == CYCLE_UP:\n minutePosition = (minutePosition + 1) % 60\n playMinutes[minutePosition].play()\n\n if inputCharacter == CYCLE_DOWN:\n minutePosition = (minutePosition - 1) % 60\n playMinutes[minutePosition].play()\n\n if inputCharacter == SET:\n state = 4\n playInfo[6].play_to_end()\n playDay[dayPosition].play_to_end()\n\n #play the 12 sound\n if hourSelection == 0:\n playMinutes[12].play_to_end()\n\n else:\n playMinutes[hourSelection].play_to_end()\n\n #play o clock sound\n if minutePosition == 0:\n playInfo[9].play_to_end()\n\n else:\n playMinutes[minutePosition].play_to_end()\n #play AM\n if hourPosition <= 10:\n playInfo[7].play_to_end()\n\n elif hourPosition == 23:\n playInfo[7].play_to_end()\n\n #play PM\n else:\n playInfo[8].play_to_end()\n break\n #audio selection being finished\n\n if inputCharacter == BACK:\n state = 1\n playInfo[2].play()\n # audio about going back to hour selection, remove state = 1 when audio added\n\n if inputCharacter == EXIT:\n state = 2\n playInfo[5].play_to_end()\n # exiting progam audio\n break\n\n # end minute selection\n\n"
},
{
"alpha_fraction": 0.644831120967865,
"alphanum_fraction": 0.6720736026763916,
"avg_line_length": 36.61258316040039,
"blob_id": "fcc1063099c07ac8c7499f6b322142577b498459",
"content_id": "79fd9b9c49bf249ed578e64b8db038e7e94c5719",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 60971,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 1621,
"path": "/set_clock_2.py",
"repo_name": "RyanLeeStratton/CIS433",
"src_encoding": "UTF-8",
"text": "__author__ = 'Ryan Stratton'\n# this project was modifed from the sample provided by professor hornof and using information\n# gained from experimentation and various sources, sources that provided useful to me are\n# listed below\n\n# additional resources used besides the ones provided by the professor\n\n# https://daniweb.com/programming/software-development/code/216830/tkinter-keypress-event-python\n# https://www.tutorialspoint.com/python/tk.pack.htm\n# stackoverflow.com/questions/16115378/tkinter-example-code-for-multiple-windows-why-wont-buttons-load-correctly\n\n\n# I apologize for the long repetitive code, I was having some problems with getting it to work \n# and used repetitive code instead of using loops to better understand what was going on and \n# I ended up sticking with it instead of making function calls and loops. I understand its not \n# great code design but my main goal was understanding.\n\n\n# Package imports\nimport readchar\n\n# Local imports\nfrom sound import Sound\nfrom tkinter import *\nfrom audioArray import *\n\n\n#place holders for locations in the arrays of visual displays\nColorIndex = 0\nDayIndex = 0\nHourIndex = 0\nAMorPM = 0\nMinuteIndex = 0\n\n#this class handles the selection of days\nclass Day:\n\tdef __init__(self,parent):\n\t\tself.parent = parent\n\t\tself.frame = Frame(parent)\n\n\t\tif DayIndex == 0:\n\t\t\tself.Day1 = Label(self.parent, text = ' Monday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\t\n\t\t\tself.Day1 = Label(self.parent, text = ' Monday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day1.pack(side = LEFT)\n\t\tself.Day1.bind(\"<Key>\", self.DayKeyPress)\t\t\n\t\t\n\t\tif DayIndex == 1:\n\t\t\tself.Day2 = Label(self.parent, text = ' Tuesday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\t\n\t\t\tself.Day2 = Label(self.parent, text = ' Tuesday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day2.pack(side = LEFT)\n\t\tself.Day2.bind(\"<Key>\", self.DayKeyPress)\t\t\n\n\t\tif DayIndex == 2:\n\t\t\tself.Day3 = Label(self.parent, text = ' Wednesday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\t\n\t\t\tself.Day3 = Label(self.parent, text = ' Wednesday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day3.pack(side = LEFT)\n\t\tself.Day3.bind(\"<Key>\", self.DayKeyPress)\t\t\n\n\t\tif DayIndex == 3:\n\t\t\tself.Day4 = Label(self.parent, text = ' Thursday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Day4 = Label(self.parent, text = ' Thursday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day4.pack(side = LEFT)\n\t\tself.Day4.bind(\"<Key>\", self.DayKeyPress)\t\t\n\t\t\n\t\tif DayIndex == 4:\n\t\t\tself.Day5 = Label(self.parent, text = ' Friday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Day5 = Label(self.parent, text = ' Friday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day5.pack(side = LEFT)\n\t\tself.Day5.bind(\"<Key>\", self.DayKeyPress)\t\t\n\n\t\tif DayIndex == 5:\n\t\t\tself.Day6 = Label(self.parent, text = ' Saturday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Day6 = Label(self.parent, text = ' Saturday ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Day6.pack(side = LEFT)\n\t\tself.Day6.bind(\"<Key>\", self.DayKeyPress)\t\t\n\n\t\tif DayIndex == 6:\n\t\t\tself.Day7 = Label(self.parent, text = ' Sunday ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Day7 = Label(self.parent, text = ' Sunday ', font=(\"Courier,22\"), background = \"white\")\n\t\t\n\t\tself.Day7.pack(side = LEFT)\n\t\tself.Day7.bind(\"<Key>\", self.DayKeyPress)\t\t\n\n\t\tself.frame.pack()\n\t\tself.parent.bind(\"<Key>\", self.DayKeyPress)\n\n\t#close the window\n\tdef close_windows(self):\n\t\tself.parent.destroy()\n\n\t#what happens when j,k, or space is hit in the day menu\n\tdef DayKeyPress(self,event):\n\t\tglobal DayIndex\n\t\tif event.keysym == 'space' or event.char == event.keysym:\n\n\t\t\tif event.char == 'j':\n\t\t\t\tif DayIndex == 0:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/sunday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 6\n\n\t\t\t\telif DayIndex == 1:\n\t\t\t\t\tself.Day1.configure(background =\"green\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/monday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 0\n\n\t\t\t\telif DayIndex == 2:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"green\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/tuesday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 1\n\n\n\t\t\t\telif DayIndex == 3:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"green\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/wednesday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 2\n\n\n\t\t\t\telif DayIndex == 4:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"green\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/thursday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 3\n\n\n\t\t\t\telif DayIndex == 5:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"green\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/friday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 4\n\n\n\t\t\t\telif DayIndex == 6:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"green\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/saturday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 5\n\n\n\t\t\telif event.char == 'k':\n\t\t\t\tif DayIndex == 0:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"green\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/tuesday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 1\n\n\n\t\t\t\telif DayIndex == 1:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"green\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/wednesday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 2\n\n\n\t\t\t\telif DayIndex == 2:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"green\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/thursday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 3\n\n\n\t\t\t\telif DayIndex == 3:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"green\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/friday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 4\n\n\n\t\t\t\telif DayIndex == 4:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"green\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/saturday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 5\n\n\n\t\t\t\telif DayIndex == 5:\n\t\t\t\t\tself.Day1.configure(background =\"white\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/sunday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 6\n\n\n\t\t\t\telif DayIndex == 6:\n\t\t\t\t\tself.Day1.configure(background =\"green\")\n\t\t\t\t\tself.Day2.configure(background =\"white\")\n\t\t\t\t\tself.Day3.configure(background =\"white\")\n\t\t\t\t\tself.Day4.configure(background =\"white\")\n\t\t\t\t\tself.Day5.configure(background =\"white\")\n\t\t\t\t\tself.Day6.configure(background =\"white\")\n\t\t\t\t\tself.Day7.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/days_of_week_f/monday_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tDayIndex = 0\n\n\t\t\telif event.keysym == 'space':\n\t\t\t\tself.close_windows()\n\n\n\n\n\n#the class that handles hour selection\nclass Hour:\n\tdef __init__(self,parent):\n\t\tself.parent = parent\n\t\tself.frame = Frame(parent)\n\t\t\n\t\tif HourIndex == 0:\n\t\t\tself.Hour1 = Label(self.parent, text = ' 1 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour1 = Label(self.parent, text = ' 1 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour1.pack(side = LEFT)\n\t\tself.Hour1.bind(\"<Key>\", self.HourKeyPress)\t\t\n\n\t\tif HourIndex == 1:\n\t\t\tself.Hour2 = Label(self.parent, text = ' 2 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour2 = Label(self.parent, text = ' 2 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour2.pack(side = LEFT)\n\t\tself.Hour2.bind(\"<Key>\", self.HourKeyPress)\t\t\n\t\n\t\tif HourIndex == 2:\n\t\t\tself.Hour3 = Label(self.parent, text = ' 3 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour3 = Label(self.parent, text = ' 3 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour3.pack(side = LEFT)\n\t\tself.Hour3.bind(\"<Key>\", self.HourKeyPress)\t\t\n\n\t\tif HourIndex == 3:\n\t\t\tself.Hour4 = Label(self.parent, text = ' 4 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour4 = Label(self.parent, text = ' 4 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour4.pack(side = LEFT)\n\t\tself.Hour4.bind(\"<Key>\", self.HourKeyPress)\t\t\n\n\t\tif HourIndex == 4:\n\t\t\tself.Hour5 = Label(self.parent, text = ' 5 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour5 = Label(self.parent, text = ' 5 ', font=(\"Courier,22\"), background = \"white\")\n\t\t\n\t\tself.Hour5.pack(side = LEFT)\n\t\tself.Hour5.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 5:\n\t\t\tself.Hour6 = Label(self.parent, text = ' 6 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour6 = Label(self.parent, text = ' 6 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour6.pack(side = LEFT)\n\t\tself.Hour6.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 6:\n\t\t\tself.Hour7 = Label(self.parent, text = ' 7 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour7 = Label(self.parent, text = ' 7 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour7.pack(side = LEFT)\n\t\tself.Hour7.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 7:\n\t\t\tself.Hour8 = Label(self.parent, text = ' 8 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour8 = Label(self.parent, text = ' 8 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour8.pack(side = LEFT)\n\t\tself.Hour8.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 8:\n\t\t\tself.Hour9 = Label(self.parent, text = ' 9 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour9 = Label(self.parent, text = ' 9 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour9.pack(side = LEFT)\n\t\tself.Hour9.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 9:\n\t\t\tself.Hour10 = Label(self.parent, text = ' 10 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour10 = Label(self.parent, text = ' 10 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour10.pack(side = LEFT)\n\t\tself.Hour10.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 10:\n\t\t\tself.Hour11 = Label(self.parent, text = ' 11 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour11 = Label(self.parent, text = ' 11 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour11.pack(side = LEFT)\n\t\tself.Hour11.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 11:\n\t\t\tself.Hour12 = Label(self.parent, text = ' 12 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Hour12 = Label(self.parent, text = ' 12 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Hour12.pack(side = LEFT)\n\t\tself.Hour12.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tif HourIndex == 12:\n\t\t\tself.Hour13 = Label(self.parent, text = ' AM ', font=(\"Courier,22\"), background =\"green\")\n\t\telse:\n\t\t\tself.Hour13 = Label(self.parent, text = ' AM ', font=(\"Courier,22\"), background =\"white\")\n\n\t\tself.Hour13.pack(side = LEFT)\n\t\tself.Hour13.bind(\"<Key>\", self.HourKeyPress)\n\n\t\tself.frame.pack()\n\t\tself.parent.bind(\"<Key>\", self.HourKeyPress)\n\n\t#close the window\n\tdef close_windows(self):\n\t\tself.parent.destroy()\n\n\t#what happens when j,k, or space is hit in the hour menu\n\tdef HourKeyPress(self,event):\n\t\tglobal HourIndex\n\t\tglobal AMorPM\n\t\tif event.keysym == 'space' or event.char == event.keysym:\n\n\t\t\tif event.char == 'j':\n\t\t\t\tif HourIndex == 0:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"green\")\n\t\t\t\t\tif AMorPM == 0:\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/AM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\t\t\t\t\telse:\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/PM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\n\t\t\t\t\tHourIndex = 12\n\n\t\t\t\telif HourIndex == 1:\n\t\t\t\t\tself.Hour1.configure(background =\"green\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/01_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 0\n\n\t\t\t\telif HourIndex == 2:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"green\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/02_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 1\n\n\t\t\t\telif HourIndex == 3:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"green\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/03_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 2\n\n\t\t\t\telif HourIndex == 4:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"green\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/04_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 3\n\n\t\t\t\telif HourIndex == 5:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"green\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/05_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 4\n\n\t\t\t\telif HourIndex == 6:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"green\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/06_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 5\n\n\t\t\t\telif HourIndex == 7:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"green\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/07_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 6\n\n\t\t\t\telif HourIndex == 8:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"green\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/08_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 7\n\n\t\t\t\telif HourIndex == 9:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"green\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/09_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 8\n\n\t\t\t\telif HourIndex == 10:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"green\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/10_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 9\n\n\t\t\t\telif HourIndex == 11:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"green\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/11_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 10\n\n\t\t\t\telif HourIndex == 12:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"green\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/12_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 11\n\n\t\t\telif event.char == 'k':\n\t\t\t\tif HourIndex == 11:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"green\")\n\t\t\t\t\tif AMorPM == 0:\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/AM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\t\t\t\t\telse:\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/PM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\n\t\t\t\t\tHourIndex = 12\n\n\t\t\t\telif HourIndex == 12:\n\t\t\t\t\tself.Hour1.configure(background =\"green\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/01_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 0\n\n\t\t\t\telif HourIndex == 0:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"green\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/02_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 1\n\n\t\t\t\telif HourIndex == 1:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"green\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/03_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 2\n\n\t\t\t\telif HourIndex == 2:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"green\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/04_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 3\n\n\t\t\t\telif HourIndex == 3:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"green\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/05_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 4\n\n\t\t\t\telif HourIndex == 4:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"green\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/06_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 5\n\n\t\t\t\telif HourIndex == 5:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"green\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/07_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 6\n\n\t\t\t\telif HourIndex == 6:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"green\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/08_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 7\n\n\t\t\t\telif HourIndex == 7:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"green\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/09_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 8\n\n\t\t\t\telif HourIndex == 8:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"green\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/10_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 9\n\n\t\t\t\telif HourIndex == 9:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"green\")\n\t\t\t\t\tself.Hour12.configure(background =\"white\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/11_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 10\n\n\t\t\t\telif HourIndex == 10:\n\t\t\t\t\tself.Hour1.configure(background =\"white\")\n\t\t\t\t\tself.Hour2.configure(background =\"white\")\n\t\t\t\t\tself.Hour3.configure(background =\"white\")\n\t\t\t\t\tself.Hour4.configure(background =\"white\")\n\t\t\t\t\tself.Hour5.configure(background =\"white\")\n\t\t\t\t\tself.Hour6.configure(background =\"white\")\n\t\t\t\t\tself.Hour7.configure(background =\"white\")\n\t\t\t\t\tself.Hour8.configure(background =\"white\")\n\t\t\t\t\tself.Hour9.configure(background =\"white\")\n\t\t\t\t\tself.Hour10.configure(background =\"white\")\n\t\t\t\t\tself.Hour11.configure(background =\"white\")\n\t\t\t\t\tself.Hour12.configure(background =\"green\")\n\t\t\t\t\tself.Hour13.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/12_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tHourIndex = 11\n\n\t\t\telif event.keysym == 'space':\n\t\t\t\tif HourIndex == 12:\n\t\t\t\t\tif AMorPM == 0:\n\t\t\t\t\t\tself.Hour13.configure(text = \" PM \")\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/PM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\t\t\t\t\t\tAMorPM = 1\n\t\t\t\t\t\n\t\t\t\t\telse:\n\t\t\t\t\t\t\n\t\t\t\t\t\tself.Hour13.configure(text = \" AM \")\n\t\t\t\t\t\tSounds = Sound( \"wav_files/hours_f/AM_f.wav\")\n\t\t\t\t\t\tSounds.play()\n\t\t\t\t\t\tAMorPM = 0\n\t\t\t\telse:\n\t\t\t\t\tself.close_windows()\n\n\n\n\n#the class that handles the minute selection\nclass Minute:\n\tdef __init__(self,parent):\n\t\tself.parent = parent\n\t\tself.frame = Frame(parent)\n\n\t\tif MinuteIndex == 0:\n\t\t\tself.Minute1 = Label(self.parent, text = ' 0 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute1 = Label(self.parent, text = ' 0 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute1.pack(side = LEFT)\n\t\tself.Minute1.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 1:\n\t\t\tself.Minute2 = Label(self.parent, text = ' 5 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute2 = Label(self.parent, text = ' 5 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute2.pack(side = LEFT)\n\t\tself.Minute2.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 2:\n\t\t\tself.Minute3 = Label(self.parent, text = ' 10 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute3 = Label(self.parent, text = ' 10 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute3.pack(side = LEFT)\n\t\tself.Minute3.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 3:\n\t\t\tself.Minute4 = Label(self.parent, text = ' 15 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute4 = Label(self.parent, text = ' 15 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute4.pack(side = LEFT)\n\t\tself.Minute4.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 4:\n\t\t\tself.Minute5 = Label(self.parent, text = ' 20 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute5 = Label(self.parent, text = ' 20 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute5.pack(side = LEFT)\n\t\tself.Minute5.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 5:\n\t\t\tself.Minute6 = Label(self.parent, text = ' 25 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute6 = Label(self.parent, text = ' 25 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute6.pack(side = LEFT)\n\t\tself.Minute6.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 6:\n\t\t\tself.Minute7 = Label(self.parent, text = ' 30 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute7 = Label(self.parent, text = ' 30 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute7.pack(side = LEFT)\n\t\tself.Minute7.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 7:\n\t\t\tself.Minute8 = Label(self.parent, text = ' 35 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute8 = Label(self.parent, text = ' 35 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute8.pack(side = LEFT)\n\t\tself.Minute8.bind(\"<Key>\", self.MinuteKeyPress)\n\t\t\n\t\tif MinuteIndex == 8:\n\t\t\tself.Minute9 = Label(self.parent, text = ' 40 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute9 = Label(self.parent, text = ' 40 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute9.pack(side = LEFT)\n\t\tself.Minute9.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 9:\n\t\t\tself.Minute10 = Label(self.parent, text = ' 45 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute10 = Label(self.parent, text = ' 45 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute10.pack(side = LEFT)\n\t\tself.Minute10.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 10:\n\t\t\tself.Minute11 = Label(self.parent, text = ' 50 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute11 = Label(self.parent, text = ' 50 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute11.pack(side = LEFT)\n\t\tself.Minute11.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tif MinuteIndex == 11:\n\t\t\tself.Minute12 = Label(self.parent, text = ' 55 ', font=(\"Courier,22\"), background = \"green\")\n\t\telse:\n\t\t\tself.Minute12 = Label(self.parent, text = ' 55 ', font=(\"Courier,22\"), background = \"white\")\n\n\t\tself.Minute12.pack(side = LEFT)\n\t\tself.Minute12.bind(\"<Key>\", self.MinuteKeyPress)\t\t\n\n\t\tself.frame.pack()\n\t\tself.parent.bind(\"<Key>\", self.MinuteKeyPress)\n\n\t#close the window\n\tdef close_windows(self):\n\t\tself.parent.destroy()\n\n\t#what happens when you hit j,k or space when in the minutes menu\n\tdef MinuteKeyPress(self,event):\n\t\tglobal MinuteIndex\n\t\tif event.keysym == 'space' or event.char == event.keysym:\n\n\t\t\tif event.char == 'j':\n\n\t\t\t\tif MinuteIndex == 0:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/55_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 11\n\n\t\t\t\telif MinuteIndex == 1:\n\t\t\t\t\tself.Minute1.configure(background =\"green\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/00_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 0\n\n\t\t\t\telif MinuteIndex == 2:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"green\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/05_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 1\n\n\t\t\t\telif MinuteIndex == 3:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"green\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/10_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 2\n\n\t\t\t\telif MinuteIndex == 4:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"green\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/15_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 3\n\n\t\t\t\telif MinuteIndex == 5:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"green\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/20_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 4\n\n\t\t\t\telif MinuteIndex == 6:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"green\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/25_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 5\n\n\t\t\t\telif MinuteIndex == 7:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"green\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/30_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 6\n\n\t\t\t\telif MinuteIndex == 8:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"green\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/35_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 7\n\n\t\t\t\telif MinuteIndex == 9:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"green\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/40_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 8\n\n\t\t\t\telif MinuteIndex == 10:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"green\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/45_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 9\n\n\t\t\t\telif MinuteIndex == 11:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"green\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/50_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 10\n\n\n\t\t\telif event.char == 'k':\n\n\t\t\t\tif MinuteIndex == 11:\n\t\t\t\t\tself.Minute1.configure(background =\"green\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/00_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 0\n\n\t\t\t\telif MinuteIndex == 0:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"green\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/05_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 1\n\n\t\t\t\telif MinuteIndex == 1:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"green\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/10_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 2\n\n\t\t\t\telif MinuteIndex == 2:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"green\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/15_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 3\n\n\t\t\t\telif MinuteIndex == 3:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"green\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/20_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 4\n\n\t\t\t\telif MinuteIndex == 4:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"green\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/25_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 5\n\n\t\t\t\telif MinuteIndex == 5:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"green\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/30_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 6\n\n\t\t\t\telif MinuteIndex == 6:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"green\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/35_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 7\n\n\t\t\t\telif MinuteIndex == 7:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"green\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/40_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 8\n\n\t\t\t\telif MinuteIndex == 8:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"green\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/45_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 9\n\n\t\t\t\telif MinuteIndex == 9:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"green\")\n\t\t\t\t\tself.Minute12.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/50_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 10\n\n\t\t\t\telif MinuteIndex == 10:\n\t\t\t\t\tself.Minute1.configure(background =\"white\")\n\t\t\t\t\tself.Minute2.configure(background =\"white\")\n\t\t\t\t\tself.Minute3.configure(background =\"white\")\n\t\t\t\t\tself.Minute4.configure(background =\"white\")\n\t\t\t\t\tself.Minute5.configure(background =\"white\")\n\t\t\t\t\tself.Minute6.configure(background =\"white\")\n\t\t\t\t\tself.Minute7.configure(background =\"white\")\n\t\t\t\t\tself.Minute8.configure(background =\"white\")\n\t\t\t\t\tself.Minute9.configure(background =\"white\")\n\t\t\t\t\tself.Minute10.configure(background =\"white\")\n\t\t\t\t\tself.Minute11.configure(background =\"white\")\n\t\t\t\t\tself.Minute12.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/minutes_f/55_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tMinuteIndex = 11\n\n\t\t\telif event.keysym == 'space':\n\t\t\t\tself.close_windows()\n\n\n\n\n#This is the main class that starts on first execution of the program. this starts the selection menu for\n#day,hour,minute or exit\nclass GUIAPP:\n\tdef __init__(self, parent):\n\t\tself.parent = parent\n\t\tself.frame = Frame(parent)\n\t\tself.frame.pack()\n\t\tself.parent.bind(\"<Key>\", self.keyPress)\n\n\t\tself.label1 = Label(self.parent)\n\t\tif ColorIndex == 0:\n\t\t\tself.label1.configure(font=(\"Courier\",32),text=\" Set day \", background =\"green\")\n\t\telse:\n\t\t\tself.label1.configure(font=(\"Courier\",32),text=\" Set day \", background =\"white\")\n\n\t\tself.label1.pack(side=LEFT)\n\t\tself.label1.bind(\"<Key>\", self.keyPress)\n\n\n\t\tself.label2 = Label(self.parent)\n\t\tif ColorIndex == 1:\n\t\t\tself.label2.configure(font=(\"Courier\",32),text=\" Set hour \", background =\"green\")\n\t\telse:\n\t\t\tself.label2.configure(font=(\"Courier\",32),text=\" Set hour \", background =\"white\")\n\n\t\tself.label2.pack(side=LEFT)\n\t\tself.label2.bind(\"<Key>\", self.keyPress)\n\t\t\n\n\t\tself.label3 = Label(self.parent)\n\t\tif ColorIndex == 2:\n\t\t\tself.label3.configure(font=(\"Courier\",32),text=\" Set minute \", background =\"green\")\n\t\telse:\n\t\t\tself.label3.configure(font=(\"Courier\",32),text=\" Set minute \", background =\"white\")\n\n\t\tself.label3.pack(side=LEFT)\n\t\tself.label3.bind(\"<Key>\", self.keyPress)\n\n\t\tself.label4 = Label(self.parent)\n\t\tif ColorIndex == 3:\n\t\t\tself.label4.configure(font=(\"Courier\",32),text=\" Exit program \", background =\"green\")\n\t\telse:\n\t\t\tself.label4.configure(font=(\"Courier\",32),text=\" Exit program \", background =\"white\")\n\n\t\tself.label4.pack(side=LEFT)\n\t\tself.label4.bind(\"<Key>\", self.keyPress)\n\n\t#open day menu\n\tdef new_window(self):\n\t\tself.newWindow = Toplevel(self.parent)\n\t\tself.app = Day(self.newWindow)\n\t\n\t#open hour menu\n\tdef new_window_Hour(self):\n\t\tself.newWindowHour = Toplevel(self.parent)\n\t\tself.app = Hour(self.newWindowHour)\n\t\n\t#open minute menu\n\tdef new_window_Minute(self):\n\t\tself.newWindowMinute = Toplevel(self.parent)\n\t\tself.app = Minute(self.newWindowMinute)\n\n\t#close main menu\n\tdef close_windows(self):\n\t\tself.parent.destroy()\n\n\t#what happens when the j,k or space is hit when in the main menu\n\tdef keyPress(self,event):\n\t\tglobal ColorIndex\n\t\tif event.keysym == 'space' or event.char == event.keysym:\n\t\t\tif event.char == 'k':\n\t\t\t\tif ColorIndex == 0:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"green\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_hour_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 1\n\n\t\t\t\telif ColorIndex == 1:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"green\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_minutes_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 2\n\n\t\t\t\telif ColorIndex == 2:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/exit_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 3\n\n\t\t\t\telif ColorIndex == 3:\n\t\t\t\t\tself.label1.configure(background =\"green\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_day_of_week_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 0\n\n\t\t\telif event.char == 'j':\n\t\t\t\tif ColorIndex == 0:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"green\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/exit_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 3\n\n\t\t\t\telif ColorIndex == 1:\n\t\t\t\t\tself.label1.configure(background =\"green\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_day_of_week_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 0\n\n\t\t\t\telif ColorIndex == 2:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"green\")\n\t\t\t\t\tself.label3.configure(background =\"white\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_hour_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 1\n\n\t\t\t\telif ColorIndex == 3:\n\t\t\t\t\tself.label1.configure(background =\"white\")\n\t\t\t\t\tself.label2.configure(background =\"white\")\n\t\t\t\t\tself.label3.configure(background =\"green\")\n\t\t\t\t\tself.label4.configure(background =\"white\")\n\t\t\t\t\tSounds = Sound( \"wav_files/menus_modes_navigation_f/Set_minutes_f.wav\")\n\t\t\t\t\tSounds.play()\n\t\t\t\t\tColorIndex = 2\n\n\t\t\telif event.keysym == 'space':\n\n\t\t\t\tif ColorIndex == 0:\n\t\t\n\t\t\t\t\tself.new_window()\n\n\t\t\t\telif ColorIndex == 1:\n\t\t\t\t\t\n\t\t\t\t\tself.new_window_Hour()\n\n\t\t\t\telif ColorIndex == 2:\n\n\t\t\t\t\tself.new_window_Minute()\n\t\t\t\t\n\t\t\t\telif ColorIndex == 3:\n\t\t\t\t\t\n\t\t\t\t\tself.close_windows()\n\n\nroot = Tk()\nGUIAPP = GUIAPP(root)\nroot.mainloop()\n\n"
},
{
"alpha_fraction": 0.6176470518112183,
"alphanum_fraction": 0.7941176295280457,
"avg_line_length": 10.333333015441895,
"blob_id": "d7291dcb31df5809c50cf094c5e78746e6acefdc",
"content_id": "a458d52ac2f7a61d98ab9f33443125db7504607f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 34,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 3,
"path": "/README.md",
"repo_name": "RyanLeeStratton/CIS433",
"src_encoding": "UTF-8",
"text": "# CIS433\n\nAssignments from CIS433\n"
}
] | 4 |
danj92/hajdecka
|
https://github.com/danj92/hajdecka
|
0c5cd2c59e6848bfca9edb6eb2e12e945d812baa
|
e0a6de36c6684e6464d31ec1d24858a207a67ddb
|
8a1faffe010ed0f645712cdf920d7fff44c1feea
|
refs/heads/master
| 2020-05-24T04:06:23.665498 | 2019-05-24T18:56:58 | 2019-05-24T18:56:58 | 150,469,404 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.625,
"avg_line_length": 19.66666603088379,
"blob_id": "ce8ecc9810ffb1680517a74722b54cc0a17a8beb",
"content_id": "64cb3c3fb1bf07f66823fd1111c32bf55c33282f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 248,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 12,
"path": "/frontend/src/app/app-routing.module.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Routes } from '@angular/router';\n\nexport const appRoutes: Routes = [\n {\n path: 'auth',\n loadChildren: './auth/auth.module#AuthModule',\n },\n {\n path: 'desktop',\n loadChildren: './desktop/desktop.module#DesktopModule',\n }\n];\n"
},
{
"alpha_fraction": 0.645550549030304,
"alphanum_fraction": 0.645550549030304,
"avg_line_length": 21.100000381469727,
"blob_id": "3e11e24ff8b4aed05eb30c377dc244236f6fbf05",
"content_id": "52545395654e0f0cc7fea64c1c20b74e936ef6fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 663,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 30,
"path": "/frontend/src/app/landing-page/landing-page/landing-page.component.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Component, OnInit } from '@angular/core';\nimport { ApiService } from 'src/app/core/api.service';\nimport { UserSimple } from 'src/app/core/user.interface';\n\n@Component({\n selector: 'app-landing-page',\n templateUrl: './landing-page.component.html',\n styleUrls: ['./landing-page.component.scss']\n})\nexport class LandingPageComponent implements OnInit {\n\n users: UserSimple;\n\n constructor(private api: ApiService) { }\n\n ngOnInit() {\n this.fetchUsers();\n }\n\n async fetchUsers() {\n try {\n // console.log('start');\n this.users = await this.api.users.me();\n // console.log('ME', this.users);\n } catch (e) {} finally {\n\n }\n }\n\n}\n"
},
{
"alpha_fraction": 0.6706587076187134,
"alphanum_fraction": 0.6706587076187134,
"avg_line_length": 20.648147583007812,
"blob_id": "7637dde3694e20bf87fef303327692aea1cac104",
"content_id": "c81587d3a9a159b3dec45a1c1e16dfde4c671808",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1169,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 54,
"path": "/frontend/src/app/core/core.module.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport {\n HttpClientModule,\n HttpClientXsrfModule,\n} from '@angular/common/http';\n\nimport {\n HTTP_INTERCEPTORS,\n} from '@angular/common/http';\n\nimport { ApiService } from './api.service';\nimport { AuthService } from './auth.service';\nimport { SessionService } from './session.service';\nimport { ToastComponent } from './toasts/toast/toast.component';\nimport { ToastsComponent } from './toasts/toasts.component';\nimport { ToastsService } from './toasts/toasts.service';\n\nimport { ErrorInterceptor } from './error.interceptor';\n\n@NgModule({\n imports: [\n CommonModule,\n HttpClientModule,\n HttpClientXsrfModule.withOptions({\n cookieName: 'csrftoken',\n headerName: 'X-CSRFToken',\n }),\n ],\n providers: [\n ApiService,\n AuthService,\n SessionService,\n ToastsService,\n {\n provide: HTTP_INTERCEPTORS,\n useClass: ErrorInterceptor,\n multi: true,\n },\n ],\n declarations: [\n ToastComponent,\n ToastsComponent,\n ],\n exports: [\n ToastComponent,\n ToastsComponent,\n ]\n})\n\nexport class CoreModule {\n constructor() {\n }\n}\n"
},
{
"alpha_fraction": 0.6760563254356384,
"alphanum_fraction": 0.6760563254356384,
"avg_line_length": 20.299999237060547,
"blob_id": "0f1ac7db8ec5b12eabd33c28c031e604c8f50617",
"content_id": "f48cf2c0aec8143f265160812d23b3be00d764d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 213,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 10,
"path": "/frontend/src/app/desktop/desktop.routing.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Routes } from '@angular/router';\nimport { DesktopComponent } from './desktop/desktop.component';\n\n\nexport const desktopRoutes: Routes = [\n {\n path: 'desktop',\n component: DesktopComponent,\n },\n];\n"
},
{
"alpha_fraction": 0.6346153616905212,
"alphanum_fraction": 0.6359416246414185,
"avg_line_length": 26.418182373046875,
"blob_id": "6d3cc90ea9c3102916afc7e548e0bb07f8c88256",
"content_id": "a29bc14890d670a1fa17d10b23b0ccc1c672107d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1508,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 55,
"path": "/frontend/src/app/forms/form-helpers.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import {\n AbstractControl,\n Validators,\n FormGroup,\n FormArray,\n} from '@angular/forms';\n\nexport function isControlRequired(control: AbstractControl) {\n if (control.validator && control.enabled) {\n const result = control.validator(Validators.required as any);\n return result && result.required;\n }\n return false;\n}\n\nfunction setDrfErrors(formGroup: FormGroup, drfErrors: any) {\n for (const errorKey of Object.keys(drfErrors)) {\n const error = drfErrors[errorKey];\n const formControl = formGroup.controls[errorKey];\n if (formGroup.controls[errorKey] instanceof FormArray) {\n for (let i = 0; i < error.length; i++) {\n const hasErrors = Object.keys(error[i]).length > 0;\n if (hasErrors) {\n const formArray = formControl as FormArray;\n const nestedFormGroup = formArray.controls[i] as FormGroup;\n setDrfErrors(nestedFormGroup, error[i]);\n }\n }\n } else if (formGroup.controls[errorKey] instanceof FormGroup) {\n setDrfErrors(formControl as FormGroup, error);\n } else {\n if (formControl) {\n formControl.setErrors(error);\n } else if (errorKey === 'nonFieldErrors') {\n formGroup.setErrors({\n global: error,\n });\n }\n }\n }\n}\n\nexport async function wrapApiFormPost<T>(\n formGroup: FormGroup,\n callback: () => Promise<T>,\n): Promise<T> {\n try {\n return await callback();\n } catch (e) {\n if (e.error) {\n setDrfErrors(formGroup, e.error);\n }\n // throw e;\n }\n}\n"
},
{
"alpha_fraction": 0.5350140333175659,
"alphanum_fraction": 0.7198879718780518,
"avg_line_length": 17.789474487304688,
"blob_id": "195da116c16aa6125f466ef48278c46d83bc62b3",
"content_id": "19b2b1d91fc5190841eb5a9a7fbdf36ab74effeb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 357,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 19,
"path": "/backend/requirements.txt",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "certifi==2019.3.9\nchardet==3.0.4\ndefusedxml==0.5.0\nDjango==2.2\ndjango-allauth==0.39.1\ndjango-rest-auth==0.9.5\ndjangorestframework==3.9.2\ndjangorestframework-camel-case==1.0.3\ndjrill==2.1.0\nidna==2.8\noauthlib==3.0.1\npkg-resources==0.0.0\npython3-openid==3.1.0\npytz==2018.9\nrequests==2.21.0\nrequests-oauthlib==1.2.0\nsix==1.12.0\nsqlparse==0.3.0\nurllib3==1.24.1\n"
},
{
"alpha_fraction": 0.7252747416496277,
"alphanum_fraction": 0.7252747416496277,
"avg_line_length": 26.69565200805664,
"blob_id": "42db99c64c72a1ad5e7013156c61b1a0ffb46df8",
"content_id": "a315a2b3f2eccc1acc23b747c51547fe55cc5da6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 23,
"path": "/backend/src/api/urls.py",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\nfrom django.urls import path\nfrom django.conf.urls import include, url\nfrom django.http import HttpResponse\nfrom users.views import UsersView\nfrom rest_framework import routers\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UsersView, base_name='users')\n\n\ndef my_email(request):\n return HttpResponse(request.user.email)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n url('my_email/', my_email),\n url(r'^api/rest-auth/', include('rest_auth.urls')),\n url(r'^api/rest-auth/registration/', include('rest_auth.registration.urls')),\n url(r'^api/', include(router.urls))\n]\n"
},
{
"alpha_fraction": 0.6505608558654785,
"alphanum_fraction": 0.6540120840072632,
"avg_line_length": 22.18000030517578,
"blob_id": "a5ca1fc5a76e9dbad83a9cf23bc39b240a11084e",
"content_id": "4f4f8b43a3d53595bbb8b94faf3299300dc379cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1159,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 50,
"path": "/frontend/src/app/auth/registration/registration.component.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Component, OnInit } from '@angular/core';\nimport {\n FormGroup,\n FormControl,\n FormBuilder,\n Validators,\n} from '@angular/forms';\n\nimport { AuthService } from 'src/app/core/auth.service';\n\nimport { wrapApiFormPost } from 'src/app/forms/form-helpers';\n\n@Component({\n selector: 'app-registration',\n templateUrl: './registration.component.html',\n styleUrls: ['./registration.component.scss']\n})\nexport class RegistrationComponent implements OnInit {\n\n formGroup: FormGroup;\n\n waiting = false;\n\n constructor(\n private fb: FormBuilder,\n private auth: AuthService,\n ) { }\n\n ngOnInit() {\n this.formGroup = this.fb.group({\n username: new FormControl('', Validators.required),\n email: new FormControl('', [Validators.required, Validators.email]),\n password1: new FormControl('', Validators.minLength(8)),\n password2: new FormControl('', Validators.minLength(8)),\n });\n }\n\n async register() {\n this.waiting = true;\n try {\n await wrapApiFormPost(\n this.formGroup,\n () => this.auth.register(this.formGroup.value)\n );\n } catch (e) {} finally {\n this.waiting = false;\n }\n }\n\n}\n"
},
{
"alpha_fraction": 0.6263048052787781,
"alphanum_fraction": 0.6263048052787781,
"avg_line_length": 16.740739822387695,
"blob_id": "d45e53b6f69474b5f708e27c7234b7a6b67fcac6",
"content_id": "8671aedffc8ba0e94ef40fa2e3c57d836fbd6585",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 479,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 27,
"path": "/frontend/src/app/core/toasts/toast/toast.component.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Component, Input } from '@angular/core';\n\nimport { Toast } from '../toasts.interface';\n\nconst ICONS = {\n 'info': 'circle_info',\n 'success': 'circle_check',\n 'warning': 'warning',\n 'error': 'circle_close',\n};\n\n@Component({\n selector: 'app-toast',\n templateUrl: './toast.component.html',\n styleUrls: ['./toast.component.scss']\n})\nexport class ToastComponent {\n\n @Input() toast: Toast;\n\n constructor() { }\n\n get icon() {\n return ICONS[this.toast.type];\n }\n\n}\n"
},
{
"alpha_fraction": 0.7039275169372559,
"alphanum_fraction": 0.7190332412719727,
"avg_line_length": 24.538461685180664,
"blob_id": "e0f66d46380eb0e1351d72f866bccf18ebf86410",
"content_id": "7a5daf3becf1c3a64f7358b1eca88efdf8f05c6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 331,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 13,
"path": "/README.md",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "# Run project roomsy :)\n\n* `git clone https://github.com/danj92/login.git`\n* `open project`\n* `python3 -m venv venv`\n* `source venv/bin/activate`\n* `pip3 install -r requirements.txt`\n* `python3 manage.py createsuperuser`\n* `./manage.py runserver`\n\nAdd icon like svg\n* chmod +x /frontend/bin/update_icons\n* frontend/bin/update_icons"
},
{
"alpha_fraction": 0.6153846383094788,
"alphanum_fraction": 0.6221470832824707,
"avg_line_length": 22.19607925415039,
"blob_id": "d21d80c0e5bdf40618653de5ecd32136d605720b",
"content_id": "b748c4a80218e806fede3b57f2a07210b01457cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1183,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 51,
"path": "/frontend/src/app/core/toasts/toasts.service.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Injectable } from '@angular/core';\n\nimport { ReplaySubject } from 'rxjs';\n\nimport { Toast, MessageType } from './toasts.interface';\n\n@Injectable()\nexport class ToastsService {\n\n AUTO_DISMISS_TIMEOUT = 5000;\n\n toasts: Toast[] = [];\n private _toasts$ = new ReplaySubject<Toast[]>(1);\n toasts$ = this._toasts$.asObservable();\n\n info(message: string) {\n this.push('info', message);\n }\n\n success(message: string) {\n this.push('success', message);\n }\n\n warning(message: string) {\n this.push('warning', message);\n }\n\n error(message: string) {\n this.push('error', message);\n }\n\n private push(type: MessageType, message: string) {\n const toast = {type, message};\n // console.log('toast', toast);\n this.toasts.push(toast);\n // console.log('push toast = ', this.toasts);\n this._toasts$.next(this.toasts);\n setTimeout(() => this.dismiss(toast), this.AUTO_DISMISS_TIMEOUT);\n }\n\n dismiss(toast: Toast) {\n const index = this.toasts.indexOf(toast);\n // console.log('index', index);\n if (index !== -1) {\n // console.log('toast2', this.toasts);\n this.toasts.splice(index, 1);\n this._toasts$.next(this.toasts);\n }\n }\n\n}\n"
},
{
"alpha_fraction": 0.6556991934776306,
"alphanum_fraction": 0.6556991934776306,
"avg_line_length": 20.274999618530273,
"blob_id": "6de89ec91f3c21d5c631946e645a1fd1e3bbd5fb",
"content_id": "ab92dac8ef505bd21980d8c3e00b0da2fb19955d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 852,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 40,
"path": "/frontend/src/app/core/auth.service.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Injectable } from '@angular/core';\nimport { Router } from '@angular/router';\n\n\nimport { ApiService } from './api.service';\nimport { SessionService } from './session.service';\n\n@Injectable()\nexport class AuthService {\n\n constructor(\n private router: Router,\n private api: ApiService,\n private sessionService: SessionService,\n ) {\n\n }\n\n async register(formData: any) {\n await this.api.auth.register(formData);\n await this.sessionService.reload();\n this.router.navigate(['/']);\n }\n\n async login(formData: any) {\n await this.api.auth.login(formData);\n await this.sessionService.reload();\n const url = '/';\n this.router.navigate([url]);\n }\n\n async logout() {\n await this.api.auth.logout();\n this.sessionService.flush();\n this.router.navigate(['/']);\n // console.log('zostaleś wylogowany');\n }\n\n\n}\n"
},
{
"alpha_fraction": 0.7334494590759277,
"alphanum_fraction": 0.7351916432380676,
"avg_line_length": 15.882352828979492,
"blob_id": "aaa117db6bcd063ba92d04201b31645f9547a51d",
"content_id": "4e1082a24cf3d5d16f8675649c6df5b658ecf6cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 1148,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 68,
"path": "/backend/src/mypy.ini",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "[mypy]\nstrict_optional = False\n\n[mypy-*.migrations.*]\nignore_errors = True\n\n[mypy-django.*]\nignore_missing_imports = True\n\n[mypy-rest_framework.*]\nignore_missing_imports = True\n\n[mypy-rest_auth.*]\nignore_missing_imports = True\n\n[mypy-channels.*]\nignore_missing_imports = True\n\n[mypy-debug_toolbar.*]\nignore_missing_imports = True\n\n[mypy-factory.*]\nignore_missing_imports = True\n\n[mypy-pytest.*]\nignore_missing_imports = True\n\n[mypy-allauth.*]\nignore_missing_imports = True\n\n[mypy-freezegun.*]\nignore_missing_imports = True\n\n[mypy-asgiref.*]\nignore_missing_imports = True\n\n[mypy-sentry_sdk.*]\nignore_missing_imports = True\n\n[mypy-hashid_field.*]\nignore_missing_imports = True\n\n[mypy-django_fsm.*]\nignore_missing_imports = True\n\n[mypy-PIL.*]\nignore_missing_imports = True\n\n[mypy-versatileimagefield.*]\nignore_missing_imports = True\n\n[mypy-simple_history.*]\nignore_missing_imports = True\n\n[mypy-markdown2.*]\nignore_missing_imports = True\n\n[mypy-djangorestframework_camel_case.*]\nignore_missing_imports = True\n\n[mypy-redis.*]\nignore_missing_imports = True\n\n[mypy-boto3.*]\nignore_missing_imports = True\n\n[mypy-xmltodict.*]\nignore_missing_imports = True\n"
},
{
"alpha_fraction": 0.717391312122345,
"alphanum_fraction": 0.717391312122345,
"avg_line_length": 21.20689582824707,
"blob_id": "34306e13cbc84f096888db4941830a26bf6766d8",
"content_id": "4700432af18cf0de93468227916398400775ebfb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 29,
"path": "/frontend/src/app/forms/forms.module.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\n\nimport { InputComponent } from './input/input.component';\nimport { FormErrorsComponent } from './form-errors/form-errors.component';\nimport { ValidationMessages } from './validation-messages';\n\n\nconst COMPONENTS = [\n InputComponent,\n FormErrorsComponent,\n];\n\n\n@NgModule({\n imports: [\n CommonModule,\n FormsModule,\n ReactiveFormsModule,\n ],\n declarations: COMPONENTS,\n exports: COMPONENTS,\n providers: [\n ValidationMessages,\n ],\n})\n\nexport class RoomsyFormsModule { }\n"
},
{
"alpha_fraction": 0.6454780101776123,
"alphanum_fraction": 0.648061990737915,
"avg_line_length": 27.455883026123047,
"blob_id": "8f420b755fdcbd683f738de3a7ad06ccf36ce98f",
"content_id": "b6af10e9745a7fb27ac48a88ee30c0e36f44ccca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1935,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 68,
"path": "/frontend/bin/update_icons",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env node\n\n/*\nThe script generates fonts from SVG icon files.\nUsage:\nRemember to have `npm install` called before running this script.\nCall `frontend/bin/update_icons`.\n*/\n\nconst fs = require('fs');\nconst path = require('path');\nconst webfontsGenerator = require('vusion-webfonts-generator');\n\nconst SRC_PATH = path.normalize(__dirname + '/../src/');\nconst ICONS_PATH = SRC_PATH + 'icons-svg/';\nconst FONTS_PATH = SRC_PATH + 'assets/fonts/';\nconst ICONS_LIST_PATH = FONTS_PATH + 'icons-list.json';\nconst FONT_NAME = 'magda';\n\nfs.readdir(ICONS_PATH, (err, icons) => {\n if (err) {\n console.error(`Unable to read ${ICONS_PATH}`);\n process.exit(1);\n }\n console.log(`Found ${icons.length} icons. Processing...`);\n\n generateFonts(icons);\n updateIconsList(icons);\n});\n\nfunction generateFonts(icons) {\n webfontsGenerator({\n files: icons.map(iconName => ICONS_PATH + iconName),\n dest: FONTS_PATH,\n fontName: FONT_NAME,\n types: ['woff', 'woff2'],\n css: false,\n }, err => {\n if (err) {\n console.error(`Failed to generate fonts. Reason: ${err}`);\n process.exit(1);\n }\n\n // .svg and .ttf fonts are generated regardles of that types we set in\n // webfontsGenerator. This is because .woff generation depends on .ttf\n // and .ttf generation depends on .svg font type.\n // Let's manually remove redundant files.\n fs.unlinkSync(`${FONTS_PATH}${FONT_NAME}.svg`);\n fs.unlinkSync(`${FONTS_PATH}${FONT_NAME}.ttf`);\n\n console.log(`Fonts saved to ${FONTS_PATH}`);\n });\n}\n\nfunction updateIconsList(icons) {\n // The list is used within playground to display all the icons.\n icons = icons.map(icon => icon.split('.')[0]);\n const data = JSON.stringify({icons});\n\n fs.writeFile(ICONS_LIST_PATH, data, err => {\n if (err) {\n console.error(`Failed to save ${ICONS_LIST_PATH}. Reason: ${err}`);\n process.exit(1);\n }\n\n console.log(`Updated ${ICONS_LIST_PATH}`);\n });\n}\n"
},
{
"alpha_fraction": 0.6262940168380737,
"alphanum_fraction": 0.6304348111152649,
"avg_line_length": 24.421052932739258,
"blob_id": "564c6c4b7085bf808e4aa4068699267d29fb1fa5",
"content_id": "c02cfc3f045a21d68754a5da8e19ffe7e8742c1c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 968,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 38,
"path": "/frontend/src/app/core/error.interceptor.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Injectable } from '@angular/core';\nimport {\n HttpEvent,\n HttpInterceptor,\n HttpHandler,\n HttpRequest,\n HttpErrorResponse,\n} from '@angular/common/http';\n\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\nimport { ToastsService } from './toasts/toasts.service';\n\n\n@Injectable()\nexport class ErrorInterceptor implements HttpInterceptor {\n\n constructor(private toastsService: ToastsService) {}\n\n intercept(\n req: HttpRequest<any>,\n next: HttpHandler,\n ): Observable<HttpEvent<any>> {\n return next.handle(req).pipe(tap(\n () => {},\n err => {\n if (err instanceof HttpErrorResponse) {\n const response = err as HttpErrorResponse;\n if (response.status === 500) {\n this.toastsService.error('Nieoczekiwany błąd serwera.');\n } else if (response.status === 0) {\n this.toastsService.error('Brak odpowiedzi od serwera.');\n }\n }\n }\n ));\n }\n}\n"
},
{
"alpha_fraction": 0.6906077265739441,
"alphanum_fraction": 0.6906077265739441,
"avg_line_length": 18.052631378173828,
"blob_id": "155b8f45e5cde93909827a1575a5e2f457ed5c55",
"content_id": "cd7d21ea02a6acb58688c080d92f31bc4f6dd3e7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 362,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 19,
"path": "/frontend/src/app/desktop/desktop.module.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\n\n\nimport { DesktopComponent } from './desktop/desktop.component';\nimport { desktopRoutes } from './desktop.routing';\n\n\n@NgModule({\n imports: [\n RouterModule.forChild(desktopRoutes),\n ],\n declarations: [\n DesktopComponent,\n ],\n})\n\n\nexport class DesktopModule { }\n"
},
{
"alpha_fraction": 0.6854838728904724,
"alphanum_fraction": 0.6854838728904724,
"avg_line_length": 23.799999237060547,
"blob_id": "275321e34021bd3daa908f3a93cd998f53b82d5e",
"content_id": "93918d76ea92fa60e2ccb87150e64c30ee871298",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 248,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 10,
"path": "/frontend/src/app/landing-page/landing-page.routing.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Routes } from '@angular/router';\nimport { LandingPageComponent } from './landing-page/landing-page.component';\n\nexport const landingPageRoutes: Routes = [\n {\n path: '',\n pathMatch: 'full',\n component: LandingPageComponent\n }\n];\n"
},
{
"alpha_fraction": 0.6201117038726807,
"alphanum_fraction": 0.6201117038726807,
"avg_line_length": 24.600000381469727,
"blob_id": "0355f407b998b62ad8095511fea03aef2ca2e51a",
"content_id": "e63730601702bd6f93363e7b899b17b849cefc69",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 895,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 35,
"path": "/backend/src/emails/client.py",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "from django.core.mail import EmailMultiAlternatives\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\nfrom typing import List\n\n\ndef send_email(\n context: dict,\n to: List[str],\n template: str,\n title: str,\n cc: List[str] = None,\n bcc: List[str] = None,\n):\n plaintext = render_to_string(f'{template}.txt', context)\n\n mail = EmailMultiAlternatives(\n subject=title,\n body=plaintext,\n from_email=settings.DEFAULT_FROM_EMAIL,\n to=to,\n cc=cc,\n bcc=bcc,\n )\n\n # if not settings.EMAIL_TEXT_ONLY:\n # html = render_to_string(f'{template}.html', context)\n # mail.attach_alternative(html, 'text/html')\n\n # payload_size = len(mail.message().as_bytes())\n\n # if payload_size > MAX_PAYLOAD_SIZE:\n # raise PayloadSizeExceeded(payload_size)\n\n mail.send()"
},
{
"alpha_fraction": 0.6441774368286133,
"alphanum_fraction": 0.6441774368286133,
"avg_line_length": 22.021276473999023,
"blob_id": "5c38b9482fb1afd3c9f9eb424a63be573c3d3b91",
"content_id": "110fea2ec2b6b03425f594112406f6275a5dfd2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1082,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 47,
"path": "/frontend/src/app/auth/login/login.component.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Component, OnInit } from '@angular/core';\nimport {\n FormGroup,\n FormControl,\n FormBuilder,\n Validators,\n} from '@angular/forms';\n\nimport { wrapApiFormPost } from 'src/app/forms/form-helpers';\nimport { AuthService } from 'src/app/core/auth.service';\n\n@Component({\n selector: 'app-login',\n templateUrl: './login.component.html',\n styleUrls: ['./login.component.scss']\n})\nexport class LoginComponent implements OnInit {\n waiting = false;\n\n formGroup: FormGroup;\n\n constructor(\n private fb: FormBuilder,\n private auth: AuthService,\n ) { }\n\n ngOnInit() {\n this.formGroup = this.fb.group({\n username: new FormControl('Andriy', [Validators.required]),\n email: new FormControl('[email protected]', [Validators.required, Validators.email]),\n password: new FormControl('andriy19921', [Validators.required]),\n });\n }\n\n async login() {\n this.waiting = true;\n try {\n await wrapApiFormPost(\n this.formGroup,\n () => this.auth.login(this.formGroup.value)\n );\n } catch (e) {} finally {\n this.waiting = false;\n }\n }\n\n}\n"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 41,
"blob_id": "d714f4f4b0050731d0cd59e978b2605b09fa9063",
"content_id": "b6ae613d8c9fba79fed6a4d1d3b28b8d0bd83e22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 42,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 1,
"path": "/frontend/src/app/landing-page/index.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "// export * from './landing-page.module';\n"
},
{
"alpha_fraction": 0.6188055872917175,
"alphanum_fraction": 0.6251588463783264,
"avg_line_length": 31.12244987487793,
"blob_id": "3394b8791e5739e4fe04f6de151d4a528c30553a",
"content_id": "7afdfc9d2ded6b440c764d57147c5e986686de5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1574,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 49,
"path": "/backend/src/users/views.py",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import viewsets\nfrom rest_framework.permissions import IsAuthenticated\nfrom .models import User\nfrom rest_framework.decorators import action\nfrom django.core.mail import send_mail\n\nfrom .serializers import UserSerializer\n\n\nclass UsersView(viewsets.GenericViewSet):\n\n permission_classes = (IsAuthenticated,)\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @action(methods=['GET'], detail=False)\n def me(self, request):\n user = User.objects.filter(pk=request.user.pk).first()\n\n # send_mail(\n # 'Subject here',\n # 'Here is the message.',\n # '[email protected]',\n # ['[email protected]'],\n # fail_silently=False,\n # )\n\n\n # import os\n # from sendgrid import SendGridAPIClient\n # from sendgrid.helpers.mail import Mail\n\n # message = Mail(\n # from_email='[email protected]',\n # to_emails='[email protected]',\n # subject='Sending with Twilio SendGrid is Fun',\n # html_content='<strong>and easy to do anywhere, even with Python</strong>')\n # try:\n # sg = SendGridAPIClient('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')\n # response = sg.send(message)\n # print(response.status_code)\n # print(response.body)\n # print(response.headers)\n # except Exception as e:\n # print(e.message)\n\n # return Response(UserSerializer(user).data)\n"
},
{
"alpha_fraction": 0.6636363863945007,
"alphanum_fraction": 0.6636363863945007,
"avg_line_length": 19.625,
"blob_id": "afaed7f3abde520922fa7da2911492c7f67e4e1d",
"content_id": "665fb38ed8905853fc384e4ddd676ca9a9641af8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 330,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 16,
"path": "/frontend/src/app/forms/validation-messages.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "export class ValidationMessages {\n\n constructor() { }\n\n required() {\n return 'To pole jest wymagane.';\n }\n\n email() {\n return 'Niepoprawny adres email.';\n }\n\n minlength(data: {actualLength: number, requiredLength: number}) {\n return `Wymagane co najmniej ${data.requiredLength}, podano ${data.actualLength}`;\n }\n}\n"
},
{
"alpha_fraction": 0.586107075214386,
"alphanum_fraction": 0.6005788445472717,
"avg_line_length": 21.29032325744629,
"blob_id": "01abf375ef69437225c908c83be6ec62db56c6d0",
"content_id": "a79169c6f1defe26d6d21a67c9d7e7109a1b9dd7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 691,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 31,
"path": "/frontend/src/app/core/toasts/toasts.component.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Component } from '@angular/core';\nimport {\n trigger,\n style,\n animate,\n transition,\n} from '@angular/animations';\nimport { ToastsService } from './toasts.service';\n\n@Component({\n selector: 'app-toasts',\n templateUrl: './toasts.component.html',\n styleUrls: ['./toasts.component.scss'],\n animations: [\n trigger('slide', [\n transition(':enter', [\n style({opacity: 0}),\n animate('100ms ease-in', style({opacity: 1})),\n ]),\n transition(':leave', [\n style({opacity: 1}),\n animate('300ms ease-in', style({opacity: 0})),\n ]),\n ])\n ],\n})\nexport class ToastsComponent {\n\n constructor(public toastsService: ToastsService) { }\n\n}\n"
},
{
"alpha_fraction": 0.7240437269210815,
"alphanum_fraction": 0.7295082211494446,
"avg_line_length": 18.105262756347656,
"blob_id": "b966ef522dbb2f3ef4be97fc183bbb918eaf4915",
"content_id": "137e1efb55188ed437972af08c8444ef54944b68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 366,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 19,
"path": "/frontend/src/app/auth/auth.interface.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { GeneralResponse } from '../core/response.interface';\n\nexport interface RegistrationForm {\n username: string;\n email: string;\n password: string;\n password1: string;\n password2: string;\n}\n\nexport interface LoginForm {\n username: string;\n email: string;\n password: string;\n}\n\nexport interface AuthResponse extends GeneralResponse {\n key: string;\n}\n\n\n\n"
},
{
"alpha_fraction": 0.6147058606147766,
"alphanum_fraction": 0.6147058606147766,
"avg_line_length": 20.25,
"blob_id": "69dc3b0d5267ced01919590bf0b31c59caffbc60",
"content_id": "8eb9dd09efa1ac0d3453d043a5fec71d9e0ec2a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1020,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 48,
"path": "/frontend/src/app/core/api.service.ts",
"repo_name": "danj92/hajdecka",
"src_encoding": "UTF-8",
"text": "import { Injectable } from '@angular/core';\nimport {\n HttpClient,\n} from '@angular/common/http';\nimport {\n RegistrationForm,\n AuthResponse,\n LoginForm,\n } from '../auth/auth.interface';\nimport { GeneralResponse } from './response.interface';\nimport { UserSimple } from './user.interface';\n\n@Injectable()\nexport class ApiService {\n URL_PATH = '/api';\n\n\n\n constructor(public http: HttpClient) {}\n\n auth = {\n register: (formData: RegistrationForm) =>\n this.post<AuthResponse>('/rest-auth/registration/', formData),\n\n login: (formData: LoginForm) =>\n this.post('/rest-auth/login/', formData),\n\n logout: () =>\n this.post<GeneralResponse>('/rest-auth/logout/'),\n };\n\n users = {\n me: () => this.get<UserSimple>('/users/me/')\n };\n\n private post<T>(url: string, body: any = null) {\n return this.http.post<T>(\n `${this.URL_PATH}${url}`, body\n ).toPromise();\n }\n\n private get<T>(url: string) {\n return this.http.get<T>(\n `${this.URL_PATH}${url}`\n ).toPromise();\n }\n\n}\n"
}
] | 26 |
mfm24/beowulf_bot
|
https://github.com/mfm24/beowulf_bot
|
ef7a63c92f6439e4336e3bb5fc20bdceee395f50
|
2eec40909e79c2c2f229bf9947ff708d6ea75906
|
85df6904d8c3b020fb8bc6b98d40c2adf8c259e3
|
refs/heads/master
| 2020-12-02T00:38:39.178430 | 2016-09-11T20:57:53 | 2016-09-11T20:57:53 | 67,892,028 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.6781193614006042,
"alphanum_fraction": 0.6817359924316406,
"avg_line_length": 22.04166603088379,
"blob_id": "e40b31757e0e5abe0f6c892e94c3d013e2a8fd9c",
"content_id": "d507f6579c92c34502856f01e5ca9039b54c788a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 553,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 24,
"path": "/beowulf_bot.py",
"repo_name": "mfm24/beowulf_bot",
"src_encoding": "UTF-8",
"text": "import markovify\nimport requests\nimport tweepy\nimport json\nimport os\n\nbw = open('beowulf.txt').read()\n\nm = markovify.Text(bw)\n\nsecrets = json.load(open('hrothgar_secrets.json'))\nauth = tweepy.OAuthHandler(secrets['API Key'], secrets['API Secret'])\nauth.secure = True\nauth.set_access_token(secrets['Access Token'], secrets['Access Token Secret'])\nt = tweepy.API(auth)\n\nfor __ in range(10):\n tweet = m.make_sentence()\n print(\"Tweeting: \", tweet)\n try:\n t.update_status(tweet)\n break\n except tweepy.error.TweepError:\n pass\n"
}
] | 1 |
battmuck32138/c_assembly_code_generation
|
https://github.com/battmuck32138/c_assembly_code_generation
|
64d0662351f29e818730a359c8f0c373e8ee014a
|
99683b4e6671043d04656ca6530672ebfe36c110
|
8227394247f75ba8a91dd1a82b95c880cf12098f
|
refs/heads/master
| 2022-11-13T21:21:50.391174 | 2020-07-01T01:14:17 | 2020-07-01T01:14:17 | 276,238,841 | 1 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7244060635566711,
"alphanum_fraction": 0.727861762046814,
"avg_line_length": 23.8817195892334,
"blob_id": "ab2b095d41584fb6adeb2a8a29b43d91e8a97ecb",
"content_id": "04c78a6dae1d86e562080af40d6e9a6e010be7d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2315,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 93,
"path": "/cgen-helpers.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that contains functions used to assist in code generation but none of\n * the actual code generation.\n */\n\n#ifndef CGEN_HELPERS_H\n#define CGEN_HELPERS_H\n\n#include \"dast.h\"\n#include \"instructions.h\"\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n\ntypedef struct stringLabelMap {\n char* string;\n char* label;\n struct stringLabelMap* next;\n} stringLabelMap;\n\nextern stringLabelMap* s;\n\n/*\n * Helper function to free the associated memory with the list of string\n * literals.\n */\nvoid FreeStringList(stringLabelMap* lst);\n\n/*\n * Helper function to create a local label that can be used anywhere in a file.\n * This is intended for jumps that are required inside of functions and not for\n * function labels.\n */\nchar* GenerateLocalLabel();\n\n/*\n * Used to create a string used to refer to a label at the end of functions\n * for return statements.\n */\nchar* GenerateFunctionEndLabel(char* funcName);\n\n/*\n * Creates a new string label for the given string and adds to the\n * stringLabelMap s\n */\nchar* GenerateStringLabel(char* str);\n\n/*\n * Helper function that outputs the code for creating a string literal. It makes\n * a call to one of the emits in instructions.h\n */\nvoid GenerateString(Decl* curr);\n\n/*\n * Helper function that outputs a data value and pads 0s to the end of it.\n */\nvoid GenerateDataValue(int64_t value, size_t dataSize);\n\n/*\n * Helper function used to start the data section.\n */\nvoid GenerateDataLabel(char* label, size_t dataSize);\n\n/*\n * Helper function used to output labels for global variables.\n */\nchar* GenerateVarLabel();\n\n/*\n * Helper function used to locate the label for a string literal.\n */\nchar* GetStringLabel(stringLabelMap* temp, char* str);\n\n/*\n * Helper function used to ensure the output of an operation fits inside/matches\n * its type specifications.\n */\nvoid ApplyTypeRules(DAST* dast, enum reg S1);\n\n/*\n * Helper function used to make sure comparisons occur with proper width for\n * binary expressions.\n */\nvoid MatchSizes(DAST* child1, enum reg child1Reg, DAST* child2, enum reg child2Reg);\n\n/*\n * Helper functions to determine how much to allocate on the stack for call\n * expressions and where to place the arguments.\n */\nsize_t ComputeArgLocations(Decl* funcDecl, size_t* offsets, size_t* sizes);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.6781967878341675,
"alphanum_fraction": 0.6966260075569153,
"avg_line_length": 21.458599090576172,
"blob_id": "c2f8a7dbdcddf85fbb661a57b6e2a33539ee6328",
"content_id": "ce587bf5a504f4ee6926ebd32d6206ef79a523f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3527,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 157,
"path": "/instructions.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that holds all of the instructions used to generate code in the\n * compiler. This contains all the instructions the staff used to produce\n * the solution, as well as some additional instructions. You are welcome\n * to use additional instructions and not use some of these instructions.\n * Any new instructions should be added to additional-instructions.c and\n * additional-instructions.h. You are not allowed to modify this file.\n */\n\n#ifndef INST_H\n#define INST_H\n\n#include <stdint.h>\n#include <stddef.h>\n\n/*\n * For loads and stores note that our inputs go:\n * Register, Imm, Register and match:\n * lw Register Imm(Register)\n */\n\n\n/*\n * Enum containing all of the possible register names that can be output by\n * the compiler.\n */\nenum reg {\n X0, FP, S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, T0, T1, T2, T3, T4, T5, SP, RA, GP, A0, A1\n};\n\n/*\n * Global variable of register names used to map our enum of registers to\n * strings for printing.\n */\nextern const char* regNames[];\n\n/*\n * Produces the code for a label.\n */\nvoid EmitLABEL(char* label);\n\n/*\n * Produces the code for a risc-v comment.\n */\nvoid EmitCOMMENT(char* comment);\n\nvoid EmitADDI(enum reg rd, enum reg rs, int imm);\n\nvoid EmitADD(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSUB(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitMUL(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitDIV(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitDIVU(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitREM(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitREMU(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSLL(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSLLI(enum reg rd, enum reg rs1, int imm);\n\nvoid EmitSRL(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSRAI(enum reg rd, enum reg rs1, int imm);\n\nvoid EmitOR(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitXOR(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitXORI(enum reg rd, enum reg rs1, int imm);\n\nvoid EmitAND(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitANDI(enum reg rd, enum reg rs1, int imm);\n\nvoid EmitSW(enum reg rs1, int imm, enum reg rs2);\n\nvoid EmitLW(enum reg rd, int imm, enum reg rs);\n\nvoid EmitSB(enum reg rs1, int imm, enum reg rs2);\n\nvoid EmitLB(enum reg rd, int imm, enum reg rs);\n\nvoid EmitLBU(enum reg rd, int imm, enum reg rs);\n\nvoid EmitSEQZ(enum reg rd, enum reg rs);\n\nvoid EmitSNEZ(enum reg rd, enum reg rs);\n\nvoid EmitSLT(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSLTU(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitSLTIU(enum reg rd, enum reg rs1, int imm);\n\nvoid EmitLA(enum reg rd, char* label);\n\nvoid EmitLI(enum reg rd, int imm);\n\nvoid EmitMV(enum reg rd, enum reg rs);\n\nvoid EmitJAL(enum reg rd, char* label);\n\nvoid EmitBEQ(enum reg rs1, enum reg rs2, char* label);\n\nvoid EmitBNE(enum reg rs1, enum reg rs2, char* label);\n\nvoid EmitBEQZ(enum reg rs, char* label);\n\nvoid EmitBNEZ(enum reg rs, char* label);\n\nvoid EmitJAL(enum reg rs, char* label);\n\nvoid EmitJR(enum reg rs);\n\nvoid EmitJ(char* label);\n\nvoid EmitECALL();\n\nvoid EmitBREAK();\n\n/*\n * Outputs a .text directive.\n */\nvoid EmitTEXT();\n\n/*\n * Outputs a .data directive.\n */\nvoid EmitDATA();\n\n/*\n * Outputs a .globl main directive.\n */\nvoid EmitGLOBLMAIN();\n\n/*\n * Outputs a .word and a value.\n */\nvoid EmitWORDVALUE(int64_t value);\n\n/*\n * Outputs a .word reference to a label.\n */\nvoid EmitWORDLABEL(char* label);\n\n/*\n * Outputs the contents for a string as a series of bytes.\n */\nvoid EmitSTRING(char* string);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.6285714507102966,
"alphanum_fraction": 0.6285714507102966,
"avg_line_length": 16.5,
"blob_id": "0eced69e074088aa28e6d20a195b7725219b91cd",
"content_id": "c0efc2107b06e7282d07ff78fdfbbf322f6839f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 35,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 2,
"path": "/cgen-lib/exit.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "int error_and_exit ();\nint exit();\n"
},
{
"alpha_fraction": 0.6839392185211182,
"alphanum_fraction": 0.6935842633247375,
"avg_line_length": 39.01250076293945,
"blob_id": "b83627eea0fb6437c1bf0fe6f0bf8da0280934ff",
"content_id": "c1fc9057edeb4c83e0ff7f50d3a81e98b8b79f49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 25609,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 640,
"path": "/student-cgen.c",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "#include \"additional-instructions.h\"\n#include \"instructions.h\"\n#include \"student-cgen.h\"\n#include \"cgen.h\"\n#include \"cgen-helpers.h\"\n#include \"decorate-builtins.h\"\n#include \"utils.h\"\n\n/*\n * Code used to generate the negate expression. This is complete and is\n * included to provide you an example of code generation.\n *\n * Note how it calls dispatch on its child to recurse into generate code\n * that needs to be negated. Then it cause apply its operation to the value\n * of register S1 because we assume our most recent output is always in S1.\n * Finally it places it own result in S1.\n */\nvoid ProcessExprPrefixNegate(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n DAST* child1 = dast->children[0];\n\n \n /* cgen and load arguments */\n Dispatch(child1, startLabel, endLabel, regBytes);\n /* Negate by flipping all the bits and add 1. */\n EmitXORI(S1, S1, -1);\n EmitADDI(S1, S1, 1);\n\n \n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n\n/*\n * Helper function used to ease maintaining the our latest value in S1 invariant\n * for binary expression. It returns an enum value which contains the value of\n * the register used to hold a value the first of the two expresions,\n * (the second is defined to be in s1).\n *\n * You should use the enum values in instructions.h and be sure and restore the\n * stack to its previous value upon returning from the function\n *\n * Hint: When using lw/sw the argument order is Reg, imm, Reg and it matches\n *\n * lw register immediate(register)\n */\nenum reg SetupBinaryInvariant(DAST* dast, char* startLabel, char* endLabel, int regBytes) {\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* STUDENT CODE GOES HERE. */\n \n\n /*\n * Replace this return value with the register you load the first arg into.\n */\n return -1;\n}\n\n/*\n * Function used to handle code generation for all & expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * No type checking should be necessary for this operator.\n */\nvoid ProcessExprBinaryBitAnd(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n\n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n/*\n * Function used to handle code generation for all | expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * No type checking should be necessary for this operator.\n */\nvoid ProcessExprBinaryBitOr(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n\n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n/*\n * Function used to handle code generation for all ^ expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * No type checking should be necessary for this operator.\n */\nvoid ProcessExprBinaryBitXor(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n\n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n/*\n * Function used to handle code generation for all && expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * An operand is considered to have a true value if it is nonzero and a false\n * value if it is 0.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryLogicAnd(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all || expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * An operand is considered to have a true value if it is nonzero and a false\n * value if it is 0.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryLogicOr(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all == expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For equality you should not need to consider the types of the operands at all\n * and simply need to determine if the results are equal.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryEq(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all != expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For equality you should not need to consider the types of the operands at all\n * and simply need to determine if the results are equal.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryNotEq(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n DAST* child2 = dast->children[1];\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all add expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * Add needs to handle both normal arithmetic and pointer arithmetic. As a\n * refresher in C adding to a pointer increments the address by one\n * element in size. For example if we have\n *\n * x + 1\n *\n * where x is an int *, then x + 1 produces x + sizeof (int) * 1 in assembly.\n *\n * To handle this case you should use c1PtrTotal and c2PtrTotal to determine\n * if either child is a pointer (only 1 will ever be a pointer and you do not\n * need to check this condition). Then you will need to determine the sizeof\n * amount. Our compiler organizes types as having a typeDecl, which contains\n * a base type (like int), and a pointer counter, which roughly indicates how\n * many *s there are. To find the size of the base type, you should look at\n * the child1/2->typeDecl->dataSize.\n */\nvoid ProcessExprBinaryAdd(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n\n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n/*\n * Function used to handle code generation for all sub expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * Sub needs to handle both normal subtraction, pointer arithmetic and\n * subtracting one pointer from another. As a refresher in C adding to a pointer\n * decrements the address by one element in size. For example if we have\n *\n * x - 1\n *\n * where x is an int *, then x - 1 produces x - sizeof (int) * 1 in assembly.\n *\n * To handle this case you should use c1PtrTotal and c2PtrTotal to determine\n * if either child is a pointer. Then you will need to determine the sizeof\n * amount. Our compiler organizes types as having a typeDecl, which contains\n * a base type (like int), and a pointer counter, which roughly indicates how\n * many *s there are. To find the size of the base type, you should look at\n * the child1->typeDecl->dataSize.\n *\n * In addition you also need to consider the case where two pointers are\n * being subtracted from each other. For example:\n *\n * (x + 2) - x = 2\n *\n * regardless of the actual distance between the addresses in x and x + 2.\n * Once again you will need the pointer count and/or the dataSize to complete\n * this step.\n */\nvoid ProcessExprBinarySub(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n\n /* Make sure we squash any overflow for future operations. */\n ApplyTypeRules (dast, S1);\n}\n\n/*\n * Function used to handle code generation for all >= expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For comparison operations the type of the operator is important for selecting\n * the correct comparison instruction. In particular we are concerned with two\n * types of comparisons:\n * signed\n * unsigned\n *\n * To determine when to select which type of comparison, we have two conditions.\n * First if we are working with pointers, both pointers must be the same type\n * and c1PtrTotal/c2PtrTotal will be > 0. All pointer comparisons are unsigned.\n * The other possibility is that we are working with an integer type. There are\n * 5 integer types and they can be determined by comparing child1/2->typedecl\n * directly with some global variables (use ==). These types are:\n *\n * 1. unsigned int (global variable: uintType), unsigned\n * 2. int (global variable: intType), signed\n * 3. unsigned char (global variable: ucharType), unsigned\n * 4. char (global variable: charType), signed\n * 5. NULL (global variable: nullType), signed/unsigned (doesn't matter)\n *\n * For our comparisons we select the signedness (signed or unsigned) of the\n * highest priority operand (unsigned int is highest, NULL is lowest). So for\n * example if we had:\n *\n * x >= y\n *\n * where x is a char and y is an unsigned int, then we would do an unsigned\n * comparison because unsigned int is higher priority than char. Do not worry\n * about making the sizes of the operands the same, this is handled for you by\n * the starter code.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryGTEq(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all > expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For comparison operations the type of the operator is important for selecting\n * the correct comparison instruction. In particular we are concerned with two\n * types of comparisons:\n * signed\n * unsigned\n *\n * To determine when to select which type of comparison, we have two conditions.\n * First if we are working with pointers, both pointers must be the same type\n * and c1PtrTotal/c2PtrTotal will be > 0. All pointer comparisons are unsigned.\n * The other possibility is that we are working with an integer type. There are\n * 5 integer types and they can be determined by comparing child1/2->typedecl\n * directly with some global variables (use ==). These types are:\n *\n * 1. unsigned int (global variable: uintType), unsigned\n * 2. int (global variable: intType), signed\n * 3. unsigned char (global variable: ucharType), unsigned\n * 4. char (global variable: charType), signed\n * 5. NULL (global variable: nullType), signed/unsigned (doesn't matter)\n *\n * For our comparisons we select the signedness (signed or unsigned) of the\n * highest priority operand (unsigned int is highest, NULL is lowest). So for\n * example if we had:\n *\n * x > y\n *\n * where x is a char and y is an unsigned int, then we would do an unsigned\n * comparison because unsigned int is higher priority than char. Do not worry\n * about making the sizes of the operands the same, this is handled for you by\n * the starter code.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryGT(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all <= expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For comparison operations the type of the operator is important for selecting\n * the correct comparison instruction. In particular we are concerned with two\n * types of comparisons:\n * signed\n * unsigned\n *\n * To determine when to select which type of comparison, we have two conditions.\n * First if we are working with pointers, both pointers must be the same type\n * and c1PtrTotal/c2PtrTotal will be > 0. All pointer comparisons are unsigned.\n * The other possibility is that we are working with an integer type. There are\n * 5 integer types and they can be determined by comparing child1/2->typedecl\n * directly with some global variables (use ==). These types are:\n *\n * 1. unsigned int (global variable: uintType), unsigned\n * 2. int (global variable: intType), signed\n * 3. unsigned char (global variable: ucharType), unsigned\n * 4. char (global variable: charType), signed\n * 5. NULL (global variable: nullType), signed/unsigned (doesn't matter)\n *\n * For our comparisons we select the signedness (signed or unsigned) of the\n * highest priority operand (unsigned int is highest, NULL is lowest). So for\n * example if we had:\n *\n * x <= y\n *\n * where x is a char and y is an unsigned int, then we would do an unsigned\n * comparison because unsigned int is higher priority than char. Do not worry\n * about making the sizes of the operands the same, this is handled for you by\n * the starter code.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryLTEq(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to handle code generation for all < expressions. As with all\n * binary expressions it relies on the binary invariant completed in part 1.\n *\n * For comparison operations the type of the operator is important for selecting\n * the correct comparison instruction. In particular we are concerned with two\n * types of comparisons:\n * signed\n * unsigned\n *\n * To determine when to select which type of comparison, we have two conditions.\n * First if we are working with pointers, both pointers must be the same type\n * and c1PtrTotal/c2PtrTotal will be > 0. All pointer comparisons are unsigned.\n * The other possibility is that we are working with an integer type. There are\n * 5 integer types and they can be determined by comparing child1/2->typedecl\n * directly with some global variables (use ==). These types are:\n *\n * 1. unsigned int (global variable: uintType), unsigned\n * 2. int (global variable: intType), signed\n * 3. unsigned char (global variable: ucharType), unsigned\n * 4. char (global variable: charType), signed\n * 5. NULL (global variable: nullType), signed/unsigned (doesn't matter)\n *\n * For our comparisons we select the signedness (signed or unsigned) of the\n * highest priority operand (unsigned int is highest, NULL is lowest). So for\n * example if we had:\n *\n * x < y\n *\n * where x is a char and y is an unsigned int, then we would do an unsigned\n * comparison because unsigned int is higher priority than char. Do not worry\n * about making the sizes of the operands the same, this is handled for you by\n * the starter code.\n *\n * If the condition is met then you should produce 1. If the condition is not\n * met not then you should produce 0. Failure to return either of these two\n * values exactly may result in a loss of credit, regardless of the truthiness\n * of the values returned being correct.\n */\nvoid ProcessExprBinaryLT(DAST* dast,\n char* startLabel,\n char* endLabel, int regBytes) {\n\n DAST* child1 = dast->children[0];\n int c1PtrTotal = child1->typeDeclArrCount + child1->typeDeclPtrCount;\n DAST* child2 = dast->children[1];\n int c2PtrTotal = child2->typeDeclArrCount + child2->typeDeclPtrCount;\n /* First apply our invariant. */\n enum reg firstReg = SetupBinaryInvariant (dast, startLabel, endLabel, regBytes);\n /* Make sure type sizes match. */\n MatchSizes (child1, firstReg, child2, S1);\n /* STUDENT CODE HERE. */\n}\n\n/*\n * Function used to generate call expressions. It decrements the stack to\n * allocate space for the arguments, places the arguments on the stack and\n * then switches control to the function it calls. On return it moves the\n * output to our S1, our invariant register and restores the stack to its\n * previous state.\n *\n * To determine where to place arugments you should use the values in offsets\n * and to determine how large of a value to store (either word or byte) you\n * should use the results in sizes.\n */\nvoid ProcessExprCall(DAST* dast, char* startLabel, char* endLabel, int regBytes) {\n DAST* funcID = dast->children[0];\n DAST* params = dast->children[1];\n char* funcLabel = funcID->data.identifier;\n int decr = 0;\n /* move stack for all children, if they exist */\n if (params->size > 0) {\n\n /* First allocate memory to compute locations. */\n size_t* offsets = malloc (sizeof(size_t) * params->size);\n if (offsets == NULL) {\n AllocationFailed ();\n }\n size_t* sizes = malloc (sizeof(size_t) * params->size);\n if (sizes == NULL) {\n AllocationFailed ();\n }\n\n decr = ComputeArgLocations (funcID->varDecl, offsets, sizes);\n /* Decrement the stack. */\n EmitADDI(SP, SP, -1 * decr);\n for (int i = 0; i < params->size; i++) {\n /* STUDENT CODE HERE */\n }\n /* Free the memory. */\n free (offsets);\n free (sizes);\n }\n\n /* STUDENT CODE HERE */\n\n /* Restore the stack */\n if (params->size > 0) {\n EmitADDI(SP, SP, decr);\n }\n}\n\n/*\n * Helper function for decrementing the stack and storing any registers\n * that need to be saved. NOTE that you DO NOT know what code will be\n * Generated after the function declaration and in fact we have hid some\n * of the code from you.\n *\n * As a result, you should save every register that calling convention\n * dictates may need to be restored (look at lecture slides if you\n * are not sure which registers may need to be restored).\n *\n * The starter code has already saved the Frame Pointer (S0/FP), so you\n * do NOT need to save that register.\n *\n * This function returns the number of bytes the stack was decremented\n * by. It should always return a non-negative value.\n */\nsize_t SaveRegisters() {\n /* STUDENT CODE HERE */\n /* Replace me with number of bytes the SP moves. */\n return 0;\n}\n\n/*\n * Helper function for restoring all saved registers. You may assume that the\n * stack pointer is currently located at the value it was set to when modified\n * in SaveRegisters ().\n */\nvoid RestoreRegisters() {\n /* STUDENT CODE HERE */\n}\n\n/*\n * Function used for generating code for all if/else expressions. This code\n * produces labels that should be used to navigate which code block to execute\n * as a result of the condition provided. None of these labels should change\n * the start or end label because those values are used for the starts and\n * ends of loops.\n */\nvoid ProcessIfElse(DAST* dast, char* startLabel, char* endLabel, int regBytes) {\n char* condEnd = GenerateLocalLabel();\n char* elseStart = GenerateLocalLabel();\n DAST* condition = dast->children[0];\n DAST* ifBody = dast->children[1];\n DAST* elseBody = NULL;\n if (dast->size == 3) {\n elseBody = dast->children[2];\n }\n /* STUDENT CODE HERE. */\n\n /* Free the labels used. */\n free (condEnd);\n free (elseStart);\n}\n\n/*\n * Function used for generating code for all while expressions. This code\n * produces labels that should be used to navigate which code block to execute\n * as a result of the condition provided return to the condition when the end\n * of the loop is reached. In any recursive calls you should replace startLabel\n * with the label used at the start of the loop and endWhile with the label\n * used at the end of the loop.\n */\nvoid ProcessWhile(DAST* dast, char* startLabel, char* endLabel, int regBytes) {\n char* startWhile = GenerateLocalLabel();\n char* endWhile = GenerateLocalLabel();\n DAST* condition = dast->children[0];\n DAST* whileBody = dast->children[1];\n\n /* STUDENT CODE HERE. */\n\n /* Free the labels used. */\n free (startWhile);\n free (endWhile);\n}\n\n"
},
{
"alpha_fraction": 0.6097898483276367,
"alphanum_fraction": 0.6178097128868103,
"avg_line_length": 47.21333312988281,
"blob_id": "7de6a461d847a3c51fcfa3cd4840fa358dfc281f",
"content_id": "7a1d1abd8225f3ae234066681a7a808c01ba3f18",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3616,
"license_type": "no_license",
"max_line_length": 228,
"num_lines": 75,
"path": "/run-tests.py",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "import argparse, os, re, subprocess, sys\n\n\nfilenamePattern = re.compile (\"(.+)\\.61c\")\nbasePath = \"tests\"\n\ndef main (section, staffTests):\n # Next we want to get the list of all files for the tests we will be running\n files = os.listdir (\"{}/{}/inputs\".format (basePath, section))\n\n # Verify that the outputs folder exists\n with open (\"/dev/null\", \"w\") as f:\n subprocess.run ([\"mkdir\", \"-p\", \"{}/{}/outputs\".format (basePath, section)], stdout=f, stderr=f)\n \n totalTests = 0\n testsPassed = 0\n \n # Now iterate through every file to produce results\n for f in files:\n # Select the base name of the test\n baseMatch = filenamePattern.match (f)\n if baseMatch:\n baseName = baseMatch.group (1)\n totalTests += 1\n # Run the compiler on the file and place the output in output\n destFile = \"{}-output.S\".format (baseName)\n with open (\"{}/{}/outputs/{}\".format (basePath, section, destFile), \"w\") as outputFile:\n res = subprocess.run ([\"./61ccc\", \"-c\", \"{}/{}/inputs/{}\".format (basePath, section, f)], stdout=outputFile)\n if res.returncode:\n print (\"Error in compiling the test.\", file=sys.stderr)\n else:\n # Check if there is a .s/.S file to append to the output\n assemFile = \"{}.S\".format (baseName)\n if assemFile in files:\n with open (\"{}/{}/outputs/{}\".format (basePath, section, destFile), \"a\") as outputFile:\n subprocess.run ([\"cat\", \"{}/{}/inputs/{}\".format (basePath, section, assemFile)], stdout=outputFile)\n assemFile = \"{}.s\".format (baseName)\n if assemFile in files:\n with open (\"{}/{}/outputs/{}\".format (basePath, section, destFile), \"a\") as outputFile:\n subprocess.run ([\"cat\", \"{}/{}/inputs/{}\".format (basePath, section, assemFile)], stdout=outputFile)\n\n # Append the print library to the file\n with open (\"{}/{}/outputs/{}\".format (basePath, section, destFile), \"a\") as outputFile:\n subprocess.run ([\"cat\", \"cgen-lib/print.s\"], stdout=outputFile)\n\n # Run the actual file through venus\n with open (\"{}/{}/outputs/{}.out\".format (basePath, section, baseName), \"w\") as outputFile:\n res = subprocess.run ([\"java\", \"-jar\", \"venus.jar\", \"{}/{}/outputs/{}\".format (basePath, section, destFile)], stdout=outputFile)\n ret1 = res.returncode\n\n if staffTests:\n # Record and compare the result of the output\n res = subprocess.run ([\"diff\", \"{}/{}/outputs/{}.out\".format (basePath, section, baseName), \"{}/{}/expected/{}.out\".format (basePath, section, baseName)])\n if res.returncode == 0:\n testsPassed += 1\n else:\n # Output whether/where it matched\n print (\"Difference between output and expected output for {0}. Run:\\n\\n\\ndiff {1}/{2}/outputs/{3}.out {1}/{2}/expected/{3}.out\\n\\n\\n To view the differences.\".format (f, basePath, section, baseName), file=sys.stderr)\n \n if staffTests:\n # Provide a hollistic output on the results for that part\n print (\"{}: {}/{} Tests Passed\".format (section, testsPassed, totalTests))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser (description=\"Runs all of the .\")\n parser.add_argument (\"--section\", type=int, dest=\"section\", help=\"Determines what stage of tests to run\")\n stages = [\"part1\", \"part2\", \"part3\", \"part4\", \"part5\", \"part6\", \"integration\"]\n items = parser.parse_args ()\n if items.section == 0:\n main (\"student-tests\", False) \n elif items.section < 1 or items.section > 7:\n print (\"Invalid Argument\")\n os.exit (1)\n else:\n main (stages[items.section - 1], True)\n"
},
{
"alpha_fraction": 0.6310904622077942,
"alphanum_fraction": 0.7030162215232849,
"avg_line_length": 19.046510696411133,
"blob_id": "7d9d6356c299ef0e657add750a3daa9a75d4b997",
"content_id": "7744c30e6daf714189c659cb050e68e7880b6553",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 862,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 43,
"path": "/Makefile",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "CC=gcc\nFLAGS=-Wall -g -std=c99\nLinkingInfo=-L/home/ff/cs61c/bin/static -l61Ccc-notcgen\nSRCS=$(wildcard *.c)\nOBJS=$(patsubst %.c, %.o, $(SRCS))\nDEPS=$(wildcard *.h)\n\n61ccc : $(OBJS)\n\t$(CC) $(FLAGS) -o 61ccc $(OBJS) $(LinkingInfo)\n\n%.o: %.c $(DEPS)\n\t$(CC) $(FLAGS) -c $<\n\npart1: 61ccc\n\tpython3 run-tests.py --section=1\n\npart2: 61ccc\n\tpython3 run-tests.py --section=2\n\npart3: 61ccc\n\tpython3 run-tests.py --section=3\n\npart4: 61ccc\n\tpython3 run-tests.py --section=4\n\npart5: 61ccc\n\tpython3 run-tests.py --section=5\n\npart6: 61ccc\n\tpython3 run-tests.py --section=6\n\nintegration: 61ccc\n\tpython3 run-tests.py --section=7\n\nrun-student-tests: 61ccc\n\tpython3 run-tests.py --section=0\n\nrun-all-tests: part1 part2 part3 part4 part5 part6 integration run-student-tests\n\nclean:\n\trm $(OBJS) 61ccc\n\n.PHONY: clean part1 part2 part3 part4 part5 part6 run-student-tests run-all-tests\n"
},
{
"alpha_fraction": 0.6888889074325562,
"alphanum_fraction": 0.6888889074325562,
"avg_line_length": 20.600000381469727,
"blob_id": "950367d72d4d2adaef3ddc8a480581eafb3eaf44",
"content_id": "00ec9ff2989591785cff93d9df733991de5ba76f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 540,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 25,
"path": "/cgen-lib/print.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "// Used to print out strings.\nint PrintString (char *str);\n\n// Used to print out integers.\nint PrintInt (int i);\n\n// Used to print out character.\nint PrintChar (char c);\n\n// Prints bools as an integer\n// value. Used solely for type\n// matching.\nint PrintBool (bool b);\n\n// Prints out a newline\nint PrintNewline ();\n\n// Prints out many integers\nint PrintInts (int a, int b, int c);\n\n// Prints out many chars\nint PrintChars (char a, char b, char c);\n\n// Prints out chars and ints\nint PrintMixed (char a, char b, int x, int y, char c, int z);\n"
},
{
"alpha_fraction": 0.7428023219108582,
"alphanum_fraction": 0.7485604882240295,
"avg_line_length": 26.36842155456543,
"blob_id": "0ce19c53e140bcde727f3ac07a6e7e09d8304984",
"content_id": "96ecd04997e4daa1fc75f6a46c76c1669d88f437",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 521,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 19,
"path": "/additional-instructions.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File used to add any instructions needed to complete code generation.\n * Editting this file is completely optional. This file is intended to\n * allow you to include any instructions that venus recognizes but we\n * opted not to use in our implementation.\n */\n\n#ifndef ADDITIONAL_INSTRUCTIONS_H\n#define ADDITIONAL_INSTRUCTIONS_H\n\n#include <stdint.h>\n#include <stddef.h>\n#include \"instructions.h\"\n\nvoid EmitMULH(enum reg rd, enum reg rs1, enum reg rs2);\n\nvoid EmitORI(enum reg rd, enum reg rs1, int imm);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.7456896305084229,
"alphanum_fraction": 0.75,
"avg_line_length": 37.66666793823242,
"blob_id": "c4b3b1b269c97da72490c9553745dbaa642debff",
"content_id": "f6839f3a58639d692006e074612dff23fd546f46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 232,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 6,
"path": "/cgen-lib/allocs.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/* Function which allocates the specified number of bytes to the bottom of the\n calling stack frame. Since the stack must be word aligned we will pad the\n allocation to be a multiple of 4.\n*/\n\nchar *alloca (unsigned int bytes);\n"
},
{
"alpha_fraction": 0.7366818785667419,
"alphanum_fraction": 0.7366818785667419,
"avg_line_length": 21.25423812866211,
"blob_id": "4485f04616801b744513dc9c68f906eaa3f99850",
"content_id": "0dd27c6a01526fe180e6c992948b818a6bbeb159",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1314,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 59,
"path": "/decorate-builtins.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File used to hold the information about any builtin types and variables\n * needed for initializing decoration.\n */\n\n#ifndef DECORATE_BUILTINS_H\n#define DECORATE_BUILTINS_H\n\n#include \"decl.h\"\n\n#define ERROR_STRING \"__error__\"\n#define NULL_STRING \"null\"\n#define BOOL_STRING \"bool\"\n#define CHAR_STRING \"char\"\n#define UCHAR_STRING \"unsigned char\"\n#define INT_STRING \"int\"\n#define UINT_STRING \"unsigned int\"\n\n/* Number of builtin types + error and null. */\nextern size_t builtinTotal;\n\n/* Global List of all available types */\nextern Decl** typeList;\nextern size_t typeSize;\nextern size_t typeCapacity;\n\n/* Global List of all available functions */\nextern Decl** funcList;\nextern size_t funcSize;\nextern size_t funcCapacity;\n\n/*\n * Global List of all decls that need to be freed\n * and are not stored elsewhere.\n */\nextern Decl** freeList;\nextern size_t freeSize;\nextern size_t freeCapacity;\n\n/* Global Variable for error types */\nextern Decl* errorType;\n\n/* Global Variable for NULL */\nextern Decl* nullType;\n\n/* Global Variables for built in types */\nextern Decl* boolType;\nextern Decl* charType;\nextern Decl* ucharType;\nextern Decl* intType;\nextern Decl* uintType;\n\n/*\n * Function used to initialize the builtin types and lists for the decorating\n * step.\n */\nvoid InitBuiltins(char* filename);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.7197608947753906,
"alphanum_fraction": 0.7197608947753906,
"avg_line_length": 31.30681800842285,
"blob_id": "ee1a9d26d99c3f82c47255b9012be33eae07c675",
"content_id": "e2dc8f318e67b50807712d9334a1b8050227fc58",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2844,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 88,
"path": "/cgen.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that contains the main code generation. It parses the DAST and Decls\n * list and uses those values to make calls to Emit instructions and generate\n * actual code.\n */\n\n#ifndef CGEN_H\n#define CGEN_H\n\n#include <stddef.h>\n#include \"dast.h\"\n#include \"decl.h\"\n#include \"instructions.h\"\n\n/*\n * Main function used to generate all of the code. It starts by first outputting\n * any global variable declarations for the .data segment and then produces\n * the .text segment.\n */\nvoid GenerateCode(DAST* dast, char* filename, Decl* globalDecl);\n\n/*\n * Default process for any node that does not produce code or have an action\n * other than recursing over its children.\n */\nvoid ProcessDefault(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n/*\n * Process function generating the result of a variable.\n */\nvoid ProcessID(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessConstTrue(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessConstFalse(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessConstInt(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessConstNull(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessExprBinaryMul(DAST* dast,\n\n char* startLabel,\n char* endLabel, int regBytes);\n\nvoid ProcessExprBinaryDiv(DAST* dast,\n\n char* startLabel,\n char* endLabel, int regBytes);\n\nvoid ProcessFuncDecl(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessBlock(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n\nvoid ProcessFor(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n\nvoid ProcessVarDecl(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessReturn(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessExprAssign(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessBreak(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessContinue(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n/*\n * Primary function that calls the appropriate code generation function for\n * each node.\n */\nvoid Dispatch(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n/*\n * Dispatch function used for acquiring addresses.\n */\nvoid DispatchLeft(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessLeftDot(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessLeftAarow(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessLeftID(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\nvoid ProcessLeftDeref(DAST* dast, char* startLabel, char* endLabel, int regBytes);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.5877574682235718,
"alphanum_fraction": 0.5877574682235718,
"avg_line_length": 33.118812561035156,
"blob_id": "97560377884afd8029e002d7a821b0cdf53eef1c",
"content_id": "f415d2c7110b674654698e18460f42ab68e6de97",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3447,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 101,
"path": "/dast.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that holds the information about a dast, which is a conversion\n * of the previous ast datastructure with more information.\n */\n\n#ifndef DAST_H\n#define DAST_H\n\n#include <stddef.h>\n#include \"ast.h\"\n#include \"decl.h\"\n\n\n\n/*\n * Decorated AST that tracks where the element is declared.\n */\ntypedef struct dast {\n\n/* INFORMATION FROM THE AST. */\n\n enum NodeType type; /* What kind of node */\n union NodeData data; /* Data needed for literals. */\n struct dast** children; /* Children of a given node */\n size_t size; /* How many children are there */\n size_t capacity; /* Memory allocated for children */\n int linenum; /* What line does this node start at. */\n char* filename; /* What file is this node in. */\n\n/* UNIQUE TO DAST. */\n int declCount; /* When the dast was encountered\n * relatively to various declarations */\n\n\n Decl* varDecl; /* Pointer to declaration for this\n * dast node. This value is NULL if\n * this value does not apply to this\n * node (for example an operator). */\n\n Decl* typeDecl; /* Pointer to the declaration of the\n * type this node evaluates to. This\n * is most useful for tracking types\n * for things like operators and for\n * subsequently applying things like\n * pointer arithmetic. This value is\n * NULL for anything that does not\n * evaluate to a type. */\n\n int typeDeclPtrCount; /* Tracks how many pointers to the\n * type the node is. */\n\n int typeDeclArrCount; /* Tracks how many arr of the type\n * the node is. */\n\n} DAST;\n\n/*\n * Takes in an AST and count and returns a DAST derived from the AST.\n */\nDAST* ConvertAST(AST* ast, int count);\n\n/*\n * Takes in an AST and count and returns a DAST, recursing over all children.\n * This is used for error checking in arrays before declarations are finished.\n */\nDAST* CreateFullDAST(AST* ast);\n\n/*\n * Creates a DAST from the necessary information. This is useful when\n * creating DASTs directly for optimization purposes. It takes in a type\n * linenum, filename, and declCount and creates a generic DAST node of that\n * type. All appending, adding data, and compressing must occur outside this\n * function.\n */\nDAST* CreateDAST(enum NodeType type, int linenum, char* filename, int declCount);\n\n/*\n * Takes in an two DASTs and concatenates the two by making node a child\n * of tree. This is used for optimizations when the tree needs to be\n * directly manipulated.\n */\nvoid AppendDAST(DAST* tree, DAST* node);\n\n/*\n * Takes in an DAST that has had all of its children allocated and resizes\n * the children member to conserve memory.\n */\nvoid ReduceDASTMem(DAST* dast);\n\n/*\n * Takes in a DAST node and free all memory allocated for that particular\n * node. It does not recurse onto its children.\n */\nvoid FreeDASTNode(DAST* dast);\n\n/*\n * Takes in a DAST node and free all memory allocated for the entire tree.\n */\nvoid FreeDAST(DAST* dast);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.6437908411026001,
"alphanum_fraction": 0.6633986830711365,
"avg_line_length": 29.5,
"blob_id": "7f03dff6eacf76b16d771d78a7eb8b218ebfbcdb",
"content_id": "482a6beb9578dd7c162b0b1c335112ea381dc49c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 10,
"path": "/additional-instructions.c",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "#include <stdio.h>\n#include \"additional-instructions.h\"\n\nvoid EmitMULH(enum reg rd, enum reg rs1, enum reg rs2) {\n printf(\"mulh %s %s %s\\n\", regNames[rd], regNames[rs1], regNames[rs2]);\n}\n\nvoid EmitORI(enum reg rd, enum reg rs1, int imm) {\n printf(\"ori %s %s %d\\n\", regNames[rd], regNames[rs1], imm);\n}\n\n"
},
{
"alpha_fraction": 0.5947712659835815,
"alphanum_fraction": 0.5947712659835815,
"avg_line_length": 43.099098205566406,
"blob_id": "b6e62fc3cc2c64d0dca9b6ffc8a61eb7f0e1f454",
"content_id": "a0932870b5f6af7c2cae900f7c62814b9d46d824",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 4896,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 111,
"path": "/decl.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that holds the information about the declaration type, which is\n * used to hold any variable declarations and proper scopes.\n */\n\n#ifndef DECL_H\n#define DECL_H\n\n#include <stddef.h>\n\n/*\n * Types of Decls\n */\nenum DeclGroup {\n DECL_VAR, /* Variable */\n DECL_BUILTIN_TYPE, /* bool, int, uint, char, and uchar */\n DECL_STRUCT, /* Declared Struct */\n DECL_FUNC_DEF, /* Function fully defined */\n DECL_FUNC_NO_DEF, /* Function declaration without body */\n DECL_BLOCK, /* Used for Blocks and Globals */\n DECL_STR /* Used for String Literals */\n};\n\n/*\n * Types of levels at which a declaration can be stored.\n */\nenum DeclLevel {\n STRUCT, /* Used for declarations of struct members. */\n GLOBAL, /* Used for declarations at the global level. */\n FUNCTION /* Used for declarations inside functions. */\n};\n\n/*\n * Struct used to declare an element.\n */\ntypedef struct decl {\n enum DeclGroup group; /* Used to identify the type of decl */\n char* identifier; /* Holds the name of the declaration */\n int declCount; /* Ctr for telling if a variable has been decl'd */\n struct decl** types; /* List of Decls to hold types */\n size_t* typePointers; /* List of Number of pointers each type has */\n size_t typeSize; /* Number of type decls */\n size_t typeCapacity; /* Memory allocated for types. */\n struct decl** children; /* Used to track fields */\n size_t childrenSize; /* Number of children */\n size_t childrenCapacity; /* Memory allocated for children */\n struct decl* parent; /* Pointer back to parent */\n int linenum; /* Linenumber the decl occurs on */\n char* filename; /* File name the decl occurs in. */\n enum DeclLevel level; /* Variable to track where a var should be offset */\n int offset; /* Tracks how far offset a decl is. */\n int alignment; /* Tracks the number of bytes to align to. */\n int dataSize; /* Tracks how many bytes a decl uses. */\n int* arrValues; /* Tracks the values for each array level. */\n size_t arrTotal; /* Takes how many array levels a decl has. */\n char* contents; /* Pointer to value to initialize to. */\n} Decl;\n\n/*\n * Takes in a group, identifier, count, parent Decl, linenum, filename, level,\n * offset, datasize, alignment, if it is a global variable, in which case\n * the actual contents need to be stored inside the decl, a ptr to array values,\n * and the length of the array. It then creates a Decl initialized with those\n * parameters and returns a ptr to the decl.\n */\nDecl* CreateDecl(enum DeclGroup group, char* identifier, int count, Decl* parent, int line, char* filename,\n enum DeclLevel level, int offset, int dataSize, int alignment, int isGlobal, int* arrValues,\n size_t arrTotal);\n\n/*\n * Takes in a pointer to a declaration list, a pointer to its size,\n * a pointer to its capacity, and a declaration, and appends the\n * declaration to the declaration list, updating the size and possibly\n * resizing if necessary.\n */\nvoid AppendDecl(Decl*** declList, size_t* sizePtr, size_t* capacityPtr, Decl* decl);\n\n/*\n * Takes in a Declaration list of a particular size and two decls, old\n * and new, and replaces old in the declaration list with new if it\n * exists. Otherwise it does nothing.\n */\nvoid ReplaceDecl (Decl * *declList, size_t size, Decl * new, Decl* old);\n\n/*\n * Helper function to replace a decl in a list after it has been realloc'd\n */\nvoid UpdateDecl (Decl * *declList, size_t size, Decl * new, Decl* old);\n\n/*\n * Takes in an Decl that has been finished and resizes its typePointers\n * and children fields to conserve memory.\n */\nvoid ReduceDeclMem(Decl* decl);\n\n/*\n * Takes in a declaration and frees all memory allocated in the declaration\n * and all of its children.\n */\nvoid FreeDecl(Decl* decl);\n\n/*\n * Takes in a pointer to a decl_list, a pointer to its size, a pointer to its\n * capacity, a decl, a pointer to a list of pointers totals, and a pointer\n * value. Appends the decl to the decl list passed in and appends the pointer\n * to the pointer list, updating the size and resizing as necessary.\n */\nvoid AppendType(Decl*** declList, size_t* sizePtr, size_t* capacityPtr, Decl* decl, size_t** pointerList,\n size_t pointer);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.7351962924003601,
"alphanum_fraction": 0.7378576397895813,
"avg_line_length": 37.52564239501953,
"blob_id": "155341509f2754bdb59872632809c2a57fd11c95",
"content_id": "72f7473ca2a4470f76573cd77f2d9ef7c6eaf5f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3006,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 78,
"path": "/parser-errors.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that contains the functions which assist with error messages and\n * error tracking during parsing.\n */\n\n#ifndef PARSER_ERRORS_H\n#define PARSER_ERRORS_H\n\n#include \"ast.h\"\n\n/*\n * Tracks if when we have run out of tokens. Used to prevent redundant error\n * messages.\n */\nextern int eofReached;\n\n/*\n * Used to track the name of the current file. This is show if an unexpect eof\n * occurs we can determine in what file it occurred.\n */\nextern char* currFilename;\n\n/*\n * Function that takes in an AST and determines if any error has occurred.\n * Returns 0 if no errors are in the AST and otherwise returns a nonzero value.\n */\nint CheckErrors(AST* ast);\n\n/*\n * Function that takes in an AST and determines if any errors\n * occurred in its creation. In addition to the AST, the function also contains\n * parameters 'is_for', which is true if the current node is a descendent of a\n * For Loop node, and 'incorrect_returns' which is pointer to an integer. This\n * value is only useful for descendent of a func decl node that contains a\n * body (a function definition). It should point to 0 if the function always\n * successfully returns and should be nonzero otherwise.\n *\n * This function shouldreturn 0 if there are no errors and otherwise a nonzero\n * value if there are ANY ERRORS. (Note that 'incorrect_returns' must be used to\n * determine the return value of the function and simply setting it to the\n * correct value will not be sufficient).\n *\n * There are 4 types of errors:\n *\n * 1. An Error Node is present in the AST. This means an error occurred in\n * parsing. There is no need to print any output message as one as already\n * occurred during parsing.\n *\n * 2. A Break statement outside a for loop. If a Break statement is encountered while\n * 'is_for' is false then an error has occurred. You should display an output message to STDERR indicating the problem. This is not\n * quired for grading but will be essential for debugging any tests you write.\n *\n *\n * 3. A Continue statement outside a for loop. If a Continue statement is encountered while\n * 'is_for' is false then an error has occurred. You should display an output message to STDERR\n * indicating the problem. This is not required for grading but will be\n * essential for debugging any tests you write.\n *\n * Note: if you're interested in knowing /why/ we have to account for these errors\n * specifically rather than have them be resolved by the parser like some other errors,\n * check out the footnote in the spec.\n */\nint CheckImproperStatements(AST* ast, int isLoop);\n\n/*\n * Generates the error message for when there are not enough tokens to continue\n * parsing rules. It switches eofReached to 1 to prevent redundant print\n * statements.\n */\nvoid GenerateEofError();\n\n/*\n * Function to assist the output of error messages when a token is needed to\n * complete a rule in the grammar but is not found.\n */\nvoid GenerateErrorMessage(char* missing, char* filename, int linenum);\n\n#endif\n\n"
},
{
"alpha_fraction": 0.72265625,
"alphanum_fraction": 0.732421875,
"avg_line_length": 18.653846740722656,
"blob_id": "1d0ef2902bfdbddb769ed5252155ecdc17732980",
"content_id": "ac85e175d6c653f38776b8e3c118f7738a762c71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 512,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 26,
"path": "/utils.h",
"repo_name": "battmuck32138/c_assembly_code_generation",
"src_encoding": "UTF-8",
"text": "/*\n * File that holds miscellaneous functions that are possibly useful throughout\n * the compiler.\n */\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#define BYTESIZE 1\n#define WORDSIZE 4\n#define INITIAL_CAPACITY 8\n#define DEFAULT_BUFFERSIZE 80\n\n/*\n * Function to exit the program and report the error for when\n * memory allocation fails.\n */\nvoid AllocationFailed();\n\n/*\n * Function to compute ceil division. This is useful for aligning\n * the offsets for padding.\n */\nint CeilDiv(int dividend, int divisor);\n\n#endif\n\n"
}
] | 16 |
DevHerles/minsa_viajeros
|
https://github.com/DevHerles/minsa_viajeros
|
dcdc395696125be3cbf5277472623f0349574714
|
5d7ae71b53c43c1065d576953061c6a6c1150b68
|
c3da4b42fb6650a1fe0008e4f75065d51d3df0a2
|
refs/heads/master
| 2023-09-02T18:46:59.652226 | 2021-10-05T21:59:41 | 2021-10-05T21:59:41 | 379,735,212 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.7407407164573669,
"alphanum_fraction": 0.7749287486076355,
"avg_line_length": 25.923076629638672,
"blob_id": "a9c431272919c44b63046d5c2049fb6fab95e285",
"content_id": "f0d3692a1c8928993d2e06ce7f92d3c98940eded",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 351,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 13,
"path": "/people_api/models/alarm_signal_update.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "from typing import Optional\n\nfrom people_api.models.fields import AlarmSignalFields\n\nfrom .common import BaseModel\n\nclass AlarmSignal(BaseModel):\n q1: bool = AlarmSignalFields.q1\n q2: bool = AlarmSignalFields.q2\n q3: bool = AlarmSignalFields.q3\n q4: bool = AlarmSignalFields.q4\n q5: bool = AlarmSignalFields.q5\n q6: bool = AlarmSignalFields.q6\n\n"
},
{
"alpha_fraction": 0.7752613425254822,
"alphanum_fraction": 0.7752613425254822,
"avg_line_length": 29.210525512695312,
"blob_id": "f822a846340a225a4aedfeb674369f33514307f8",
"content_id": "e8611362b4eb9fb3394b0e1cabbaefba2ed80ffc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 574,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 19,
"path": "/people_api/database.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"DATABASE\nMongoDB database initialization\n\"\"\"\n\n# # Installed # #\nfrom pymongo import MongoClient\nfrom pymongo.collection import Collection\n\n# # Package # #\nfrom .settings import mongo_settings as settings\n\n__all__ = (\"client\", \"collection\", \"symptomCollection\", \"comorbidities\")\n\nclient = MongoClient(settings.uri)\ncollection: Collection = client[settings.database][settings.collection]\nsymptomCollection: Collection = client[settings.database][\n settings.symptoms_collection]\ncomorbidities: Collection = client[settings.database][\n settings.comorbidity_collection]\n"
},
{
"alpha_fraction": 0.7208374738693237,
"alphanum_fraction": 0.7208374738693237,
"avg_line_length": 38.33333206176758,
"blob_id": "4636066388a536ccd5c450e44cb5595bd1c1337d",
"content_id": "9ee58a5440fadc5ac50fde9bde6392bb803222cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2006,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 51,
"path": "/people_api/models/person_update.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON - UPDATE\nPerson Update model. All attributes are set as Optional, as we use the PATCH method for update\n(in which only the attributes to change are sent on request body)\n\"\"\"\n\n# # Native # #\nfrom datetime import date\nfrom typing import Optional, List\nfrom contextlib import suppress\n\nfrom people_api.models.alarm_signal_update import AlarmSignal\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import ContactFields, AddressFields, ComorbidityFields, SymptomFields\nfrom .person_address import Address\nfrom .person_comorbidity import Comorbidity\nfrom .person_symptoms import Symptoms\nfrom .person_eess import Eess\n\n__all__ = (\"ContactUpdate\", )\n\n\nclass ContactUpdate(BaseModel):\n \"\"\"Body of Person PATCH requests\"\"\"\n contact_id: Optional[str] = ContactFields.person_id\n parent_contact_id: Optional[str] = ContactFields.person_id\n doc_type: Optional[str] = ContactFields.doc_type\n doc_number: Optional[str] = ContactFields.doc_number\n name: Optional[str] = ContactFields.name\n first_name: Optional[str] = ContactFields.first_name\n last_name: Optional[str] = ContactFields.last_name\n birth: Optional[date] = ContactFields.birth\n start_date: Optional[date] = ContactFields.start_date\n alternative_cellphone_number: Optional[\n str] = ContactFields.alternative_cellphone_number\n cellphone_number: Optional[str] = ContactFields.cellphone_number\n address: Optional[Address]\n comorbidity: Optional[Comorbidity]\n symptoms: Optional[List[Symptoms]]\n\n # eess: Optional[Eess]\n\n def dict(self, **kwargs):\n # The \"birth\" field must be converted to string (isoformat) when exporting to dict (for Mongo)\n # TODO Better way to do this? (automatic conversion can be done with Config.json_encoders, but not available for dict\n d = super().dict(**kwargs)\n with suppress(KeyError):\n d[\"birth\"] = d.pop(\"birth\").isoformat()\n d[\"start_date\"] = d.pop(\"start_date\").isoformat()\n return d\n"
},
{
"alpha_fraction": 0.6680285930633545,
"alphanum_fraction": 0.7150152921676636,
"avg_line_length": 27.794116973876953,
"blob_id": "49621ffbad5fbdb8d98114f3a88247d6065de9bd",
"content_id": "386cfd207f29eaf1034bb4e1710a366677b3962f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 979,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 34,
"path": "/people_api/models/person_comorbidity.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON COMORBIDITY\nThe comorbidity of a person is part of the Person model\n\"\"\"\n\n# # Native # #\nfrom datetime import date\nfrom typing import Optional\nfrom contextlib import suppress\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import ComorbidityFields\n\n__all__ = (\"Comorbidity\", )\n\n\nclass Comorbidity(BaseModel):\n \"\"\"The comorbidity information of a person\"\"\"\n q1: bool = ComorbidityFields.q1\n q2: bool = ComorbidityFields.q2\n q3: bool = ComorbidityFields.q3\n q4: bool = ComorbidityFields.q4\n q5: bool = ComorbidityFields.q5\n q6: bool = ComorbidityFields.q6\n q7: bool = ComorbidityFields.q7\n q8: bool = ComorbidityFields.q8\n q9: bool = ComorbidityFields.q9\n q10: bool = ComorbidityFields.q10\n q11: bool = ComorbidityFields.q11\n q12: bool = ComorbidityFields.q12\n q13: bool = ComorbidityFields.q13\n q14: bool = ComorbidityFields.q14\n q15: bool = ComorbidityFields.q15\n q16: bool = ComorbidityFields.q16\n"
},
{
"alpha_fraction": 0.7382297515869141,
"alphanum_fraction": 0.7382297515869141,
"avg_line_length": 23.136363983154297,
"blob_id": "fcc51fce6d9e1564fb7df34a126819fc4a627e0e",
"content_id": "1ffc77690191978a7e8f5cab6b5290d7eda93129",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 531,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 22,
"path": "/people_api/models/person_address.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON ADDRESS\nThe address of a person is part of the Person model\n\"\"\"\nfrom typing import Optional\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import AddressFields\n\nfrom .department import Department\nfrom .province import Province\nfrom .district import District\n\n__all__ = (\"Address\", )\n\n\nclass Address(BaseModel):\n \"\"\"The address information of a person\"\"\"\n department: Optional[Department]\n province: Optional[Province]\n district: Optional[District]\n street: str = AddressFields.street\n"
},
{
"alpha_fraction": 0.6611478924751282,
"alphanum_fraction": 0.6732891798019409,
"avg_line_length": 31.945453643798828,
"blob_id": "18c9579f471134b7a809541728f80dc5a79e48ae",
"content_id": "9db1ba679404269eb6139a843ae4a38de9840347",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1812,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 55,
"path": "/people_api/models/person_symptoms.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON SYMPTOMS\nThe symptoms of a person is part of the Person model\n\"\"\"\n\n# # Native # #\nfrom datetime import date, datetime\nfrom typing import Optional\nfrom contextlib import suppress\n\nimport pydantic\n\nfrom people_api.models.alarm_signal_update import AlarmSignal\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import SymptomFields\n\n__all__ = (\"Symptoms\", )\n\n\nclass Symptoms(BaseModel):\n \"\"\"The symptoms information of a person\"\"\"\n q1: bool = SymptomFields.q1\n q2: bool = SymptomFields.q2\n q3: bool = SymptomFields.q3\n q4: bool = SymptomFields.q4\n q5: bool = SymptomFields.q5\n q6: bool = SymptomFields.q6\n q7: bool = SymptomFields.q7\n q8: bool = SymptomFields.q8\n q9: bool = SymptomFields.q9\n q10: Optional[str] = SymptomFields.q10\n is_suspicious: bool = SymptomFields.is_suspicious\n created: Optional[date] = SymptomFields.created_at\n updated: Optional[date] = SymptomFields.updated_at\n alarm_signal: Optional[AlarmSignal]\n latitude: Optional[str] = SymptomFields.latitude\n longitude: Optional[str] = SymptomFields.longitude\n\n @pydantic.root_validator()\n def _set_age(cls, data):\n \"\"\"Calculate the current age of the person from the date of birth, if any\"\"\"\n today = datetime.now().date()\n data[\"created\"] = today\n data[\"updated\"] = today\n return data\n\n def dict(self, **kwargs):\n # The \"birth\" field must be converted to string (isoformat) when exporting to dict (for Mongo)\n # TODO Better way to do this? (automatic conversion can be done with Config.json_encoders, but not available for dict\n d = super().dict(**kwargs)\n with suppress(KeyError):\n d[\"created\"] = d.pop(\"created\").isoformat()\n d[\"updated\"] = d[\"created\"]\n return d\n"
},
{
"alpha_fraction": 0.7216035723686218,
"alphanum_fraction": 0.7216035723686218,
"avg_line_length": 21.450000762939453,
"blob_id": "b3faa7afe1a277d763655ef3582b8929dede39be",
"content_id": "7495c37af8dfb40431676de1c9623e7be46cc432",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 20,
"path": "/people_api/models/province.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON SYMPTOMS\nThe symptoms of a person is part of the Person model\n\"\"\"\n\n# # Native # #\nfrom datetime import date\nfrom typing import Optional\nfrom contextlib import suppress\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import DepartmentFields\n\n__all__ = (\"Province\", )\n\n\nclass Province(BaseModel):\n \"\"\"The Province information of a person\"\"\"\n code: str = DepartmentFields.code\n name: str = DepartmentFields.name\n"
},
{
"alpha_fraction": 0.7649253606796265,
"alphanum_fraction": 0.7649253606796265,
"avg_line_length": 28.77777862548828,
"blob_id": "f6a0f52ba1e1ad7d8972103989887908fdc2e49b",
"content_id": "c6f5f00727b49e15b5b27600bbb9d823c146ed45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 9,
"path": "/people_api/models/__init__.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "from .person_update import *\nfrom .person_create import *\nfrom .person_read import *\nfrom .person_address import *\nfrom .person_comorbidity import *\nfrom .person_symptoms import *\nfrom .symptom_update import *\nfrom .symptom_create import *\nfrom .symptom_read import *\n"
},
{
"alpha_fraction": 0.6333377361297607,
"alphanum_fraction": 0.6559239029884338,
"avg_line_length": 43.02325439453125,
"blob_id": "ac971060c87d8892ab06617f2de4bb1c0e778f40",
"content_id": "220591700e58089f656b3163ec77c5919dc22f40",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7592,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 172,
"path": "/people_api/models/fields.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - FIELDS\nDefinition of Fields used on model classes attributes.\nWe define them separately because the PersonUpdate and PersonCreate models need to re-define their attributes,\nas they change from Optional to required.\nAddress could define its fields on the model itself, but we define them here for convenience\n\"\"\"\n\n# # Installed # #\nfrom pydantic import Field\n\n# # Package # #\nfrom ..utils import get_time, get_uuid\n\n__all__ = (\"ContactFields\", \"AddressFields\", \"ComorbidityFields\",\n \"SymptomFields\")\n\n_string = dict(min_length=1)\n\"\"\"Common attributes for all String fields\"\"\"\n_unix_ts = dict(example=get_time())\n\"\"\"Common attributes for all Unix timestamp fields\"\"\"\n\n\nclass ContactFields:\n name = Field(description=\"Name of this person\", example=\"John\", **_string)\n first_name = Field(description=\"First name of this person\",\n example=\"Doe\",\n **_string)\n last_name = Field(description=\"Last name of this person\",\n example=\"Smith\",)\n\n doc_type = Field(description=\"Document type of this person\",\n example=\"DNI\",\n **_string)\n doc_number = Field(description=\"Document number of this person\",\n example=\"45117789\",\n **_string)\n address = Field(description=\"Address object where this person live\")\n address_update = Field(\n description=f\"{address.description}. When updating, the whole Address object is required, as it gets replaced\"\n )\n comorbidities = Field(description=\"Comorbidity object\")\n comorbidities_update = Field(\n description=f\"{comorbidities.description}. When updating, the whole Comorbidity object is required, as it gets replaced\"\n )\n symptoms = Field(description=\"Symptoms object\")\n symptoms_update = Field(\n description=f\"{symptoms.description}. When updating, the whole Symptoms object is required, as it gets replaced\"\n )\n birth = Field(\n description=\"Date of birth, in format YYYY-MM-DD, or Unix timestamp\",\n example=\"1999-12-31\")\n start_date = Field(\n description=\"Symptom register start date, in format YYYY-MM-DD, or Unix timestamp\",\n example=\"2021-10-04\")\n age = Field(\n description=\"Age of this person, if date of birth is specified\",\n example=20)\n alternative_cellphone_number = Field(description=\"Alternative Cellphone number of this person\",\n example=935397346)\n cellphone_number = Field(description=\"Cellphone number of this person\",\n example=935397346)\n person_id = Field(\n description=\"Unique identifier of this person in the database\",\n example=get_uuid(),\n min_length=36,\n max_length=36)\n \"\"\"The person_id is the _id field of Mongo documents, and is set on PeopleRepository.create\"\"\"\n\n created = Field(\n alias=\"created\",\n description=\"When the person was registered (Unix timestamp)\",\n **_unix_ts)\n \"\"\"Created is set on PeopleRepository.create\"\"\"\n updated = Field(\n alias=\"updated\",\n description=\"When the person was updated for the last time (Unix timestamp)\",\n **_unix_ts)\n \"\"\"Created is set on PeopleRepository.update (and initially on create)\"\"\"\n\n\nclass AddressFields:\n street = Field(description=\"Main address line\",\n example=\"22nd Bunker Hill Avenue\",\n **_string)\n city = Field(description=\"City\", example=\"Hamburg - PER\", **_string)\n state = Field(description=\"State, province and/or region\",\n example=\"Mordor\",\n **_string)\n zip_code = Field(description=\"Postal/ZIP code\", example=\"19823\", **_string)\n\n\nclass ComorbidityFields:\n q1 = Field(description=\"Enfermedad cardiovascular\", example=True)\n q2 = Field(description=\"Enfermedad renal crónica\", example=True)\n q3 = Field(description=\"Enfermedad respiratoria crónica\", example=True)\n q4 = Field(description=\"Enfermedad hepática crónica\", example=True)\n q5 = Field(description=\"Diabetes\", example=True)\n q6 = Field(description=\"Cáncer\", example=True)\n q7 = Field(description=\"VIH\", example=True)\n q8 = Field(description=\"Tuberculosis activa\", example=True)\n q9 = Field(description=\"Transtornos neurológicos crónicos\", example=True)\n q10 = Field(description=\"Transtornos de células falciformes\", example=True)\n q11 = Field(description=\"Consumo de tabaco\", example=True)\n q12 = Field(description=\"Obecidad severa (IMC > 40)\", example=True)\n q13 = Field(description=\"Hipertensión\", example=True)\n q14 = Field(description=\"Gestante\", example=True)\n q15 = Field(description=\"Mayor de 60 años\", example=True)\n q16 = Field(description=\"Personal de salud\", example=True)\n created = Field(\n alias=\"created\",\n description=\"When the comorbidity was registered (Unix timestamp)\",\n **_unix_ts)\n updated = Field(\n alias=\"updated\",\n description=\"When the comorbidity was updated for the last time (Unix timestamp)\",\n **_unix_ts)\n\n\nclass EessFields:\n code = Field(description=\"Código del establecimiento de salud\",\n example=\"01\",\n **_string)\n name = Field(description=\"Nombre del establecimiento de salud\",\n example=\"AMAZONAS\",\n **_string)\n\n\nclass DepartmentFields:\n code = Field(description=\"Código\", example=\"01\", **_string)\n name = Field(description=\"Nombre\", example=\"AMAZONAS\", **_string)\n\n\nclass SymptomFields:\n person_id = Field(\n description=\"Id de la persona\",\n example=\"62c64bab-1f44-49dc-9ba3-6af33c887a12\",\n **_string,\n )\n symptom_id = Field(description=\"Id de la síntoma\",\n example=\"c7166343-0913-4dc2-91e5-569d7d66f905\",\n **_string)\n q1 = Field(description=\"Tos y/o dolor de garganta\", example=True)\n q1 = Field(description=\"Tos y/o dolor de garganta\", example=True)\n q2 = Field(description=\"Malestar general\", example=True)\n q3 = Field(description=\"Fiebre > 38ºC\", example=True)\n q4 = Field(description=\"Cefalea\", example=True)\n q5 = Field(description=\"Congestión nasal\", example=True)\n q6 = Field(description=\"Diarrea\", example=True)\n q7 = Field(description=\"Dificultad para respirar\", example=True)\n q8 = Field(description=\"Pérdida de olfato (Anosmia)\", example=True)\n q9 = Field(description=\"Pérdida de gusto (Ageusia)\", example=True)\n q10 = Field(description=\"Otro (describir)\", example=\"Otro\", **_string)\n is_suspicious = Field(description=\"¿Es sospechoso?\", example=True)\n latitude = Field(description=\"Latitud\", example=\"12.123123\", **_string)\n longitude = Field(description=\"Longitud\", example=\"12.123123\", **_string)\n alarm_signal = Field(description=\"Signos de alarma\", **_string)\n created_at = Field(\n alias=\"created\",\n description=\"When the Symptoms was registered (Unix timestamp)\",\n **_unix_ts)\n updated_at = Field(\n alias=\"updated\",\n description=\"When the symptoms was updated for the last time (Unix timestamp)\",\n **_unix_ts)\n\nclass AlarmSignalFields:\n q1 = Field(description=\"Disnea\", example=True)\n q2 = Field(description=\"Taquipedia (>=22 rpm)\", example=True)\n q3 = Field(description=\"Saturación de oxígeno < 92%\", example=True)\n q4 = Field(description=\"Alteración de la conciencia\", example=True)\n q5 = Field(description=\"Otro signo\", example=True)\n q6 = Field(description=\"Ninguno\", example=True)"
},
{
"alpha_fraction": 0.738898754119873,
"alphanum_fraction": 0.738898754119873,
"avg_line_length": 30.27777862548828,
"blob_id": "fa806033bc17d0460858d4ffa8df360fafb69970",
"content_id": "b04868dbce3f7370162b4470139ad3c3c9447582",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 563,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 18,
"path": "/people_api/models/symptom_create.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - SYMPTOM - CREATE\nSymptom Create model. Inherits from SymptomUpdate, but all the required fields must be re-defined\n\"\"\"\nfrom typing import Optional, List\n\n# # Package # #\nfrom .symptom_update import SymptomUpdate\nfrom .fields import SymptomFields\n\n__all__ = (\"SymptomCreate\", )\n\n\nclass SymptomCreate(SymptomUpdate):\n \"\"\"Body of Symptom POST requests\"\"\"\n person_id: str = SymptomFields.person_id\n latitude: str = SymptomFields.latitude\n longitude: str = SymptomFields.longitude\n # Birth remains Optional, so is not required to re-declare\n"
},
{
"alpha_fraction": 0.7716972231864929,
"alphanum_fraction": 0.7731437087059021,
"avg_line_length": 64.84127044677734,
"blob_id": "8bf18ccf09f1d7e8334204433c371256a8981250",
"content_id": "9f94068c16ddbe607938e5d19eb525fb03395282",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4148,
"license_type": "no_license",
"max_line_length": 301,
"num_lines": 63,
"path": "/README.md",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "# FastAPI + Pydantic + MongoDB REST API Example\n\nSample API using FastAPI, Pydantic models and settings, and MongoDB as database - non-async.\n\nThe API works with a single entity, \"Person\" (or \"People\" in plural) that gets stored on a single Mongo database and collection.\n\nThe code is intended to create the whole OpenAPI documentation with the maximum detail, including full, detailed models for requests, responses and errors.\n\n## Endpoints\n\nEndpoints define the whole CRUD operations that can be performed on Person entities:\n\n- GET `/docs` - OpenAPI documentation (generated by FastAPI)\n- GET `/people` - list all available persons\n- GET `/people/{person_id}` - get a single person by its unique ID\n- POST `/people` - create a new person\n- PATCH `/people/{person_id}` - update an existing person\n- DELETE `/people/{person_id}` - delete an existing person\n\n## Project structure (modules)\n\n- `app.py`: initialization of FastAPI and all the routes used by the API. On APIs with more endpoints and different entities, would be better to split the routes in different modules by their context or entity.\n- `models`: definition of all model classes. As we are using MongoDB, we can use the same JSON schema for API request/response and storage. However, different classes for the same entity are required, depending on the context:\n - `person_update.py`: model used as PATCH request body. Includes all the fields that can be updated, set as optional.\n - `person_create.py`: model used as POST request body. Includes all the fields from the Update model, but all those fields that are required on Create, must be re-declared (in type and Field value).\n - `person_read.py`: model used as GET and POST response body. Includes all the fields from the Create model, plus the person_id (which comes from the _id field in Mongo document) and the age (calculated from the date of birth, if any).\n - `person_address.py`: part of the Person model, address attribute.\n - `common.py`: definition of the common BaseModel, from which all the model classes inherit, directly or indirectly.\n - `fields.py`: definition of Fields, which are the values of the models attributes. Their main purpose is to complete the OpenAPI documentation by providing a description and examples. Fields are declared outside the classes because of the re-declaration required between Update and Create models.\n - `errors.py`: error models. They are referenced on Exception classes defined in `exceptions.py`.\n- `database.py`: initialization of MongoDB client. Actually is very short as Mongo/pymongo do not require to pre-connecting to Mongo or setup the database/collection, but with other databases (like SQL-like using SQLAlchemy) this can get more complex.\n- `exceptions.py`: custom exceptions, that can be translated to JSON responses the API can return to clients (mainly if a Person does not exist or already exists).\n- `middlewares.py`: the Request Handler middleware catches the exceptions raised while processing requests, and tries to translate them into responses given to the clients.\n- `repositories.py`: methods that interact with the Mongo database to read or write Person data. These methods are directly called from the route handlers.\n- `exceptions.py`: custom exceptions raised during request processing. They have an error model associated, so OpenAPI documentation can show the error models. Also define the error message and status code returned.\n- `settings.py`: load of application settings through environment variables or dotenv file, using Pydantic's BaseSettings classes.\n- `utils.py`: misc helper functions.\n- `tests`: acceptance+integration tests, that run directly against the API endpoints and real Mongo database.\n\n## Requirements\n\n- Python >= 3.7\n- Requirements listed on [requirements.txt](requirements.txt)\n- Running MongoDB server\n\n## make tools\n\n```bash\n# Install requirements\nmake install-requirements\n\n# Run the app (available at http://localhost:5000/...)\nmake run\n\n# Install test requirements\nmake install-test-requirements\n\n# Start MongoDB for tests (requires Docker)\nmake start-test-mongo\n\n# Run the tests\nmake test\n```\n"
},
{
"alpha_fraction": 0.6926877498626709,
"alphanum_fraction": 0.7144268751144409,
"avg_line_length": 29.66666603088379,
"blob_id": "ebd33c437967587b6f794e843a877b3ed0aebf0e",
"content_id": "f873bda7cff78d3b4827ec16857f8c497091b8ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1012,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 33,
"path": "/people_api/models/symptom_update.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON - UPDATE\nPerson Update model. All attributes are set as Optional, as we use the PATCH method for update\n(in which only the attributes to change are sent on request body)\n\"\"\"\n\n# # Native # #\nfrom datetime import date\nfrom typing import Optional, List\nfrom contextlib import suppress\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import SymptomFields, ContactFields\n\n__all__ = (\"SymptomUpdate\", )\n\n\nclass SymptomUpdate(BaseModel):\n \"\"\"Body of Symptom PATCH requests\"\"\"\n created: Optional[date] = ContactFields.start_date\n is_suspicious: bool = SymptomFields.is_suspicious\n q1: str = SymptomFields.q1\n q2: str = SymptomFields.q2\n q3: str = SymptomFields.q3\n q4: str = SymptomFields.q4\n q5: str = SymptomFields.q5\n q6: str = SymptomFields.q6\n q7: str = SymptomFields.q7\n q8: str = SymptomFields.q8\n q9: str = SymptomFields.q9\n q10: str = SymptomFields.q10\n latitude: str = SymptomFields.latitude\n longitude: str = SymptomFields.longitude\n"
},
{
"alpha_fraction": 0.5230414867401123,
"alphanum_fraction": 0.578341007232666,
"avg_line_length": 18.727272033691406,
"blob_id": "fdd8e8384e4fdab3a9cf03d790eb1ed3161b225c",
"content_id": "8b848d881b33aa5db55e6760a9c4fc8e251e8cc8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 434,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 22,
"path": "/docker-compose.yml",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "version: '3'\n\nservices:\n people_api:\n build:\n context: .\n ports:\n - 5000:5000\n volumes:\n - /etc/localtime:/etc/localtime:ro\n - /etc/timezone:/etc/timezone:ro\n - ./:/home/user/app/\n environment:\n - MONGO_URI=mongodb://mongodb:27017\n\n mongodb:\n image: mongo:latest\n ports:\n - 27018:27017\n volumes:\n - /etc/localtime:/etc/localtime:ro\n - /etc/timezone:/etc/timezone:ro\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7345678806304932,
"avg_line_length": 15.199999809265137,
"blob_id": "d5a0721ab5c2b57b54ca1f39ffec9eced6305116",
"content_id": "278489ad583a0f8ee4a1adfbd26eb33c08b3cf46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 10,
"path": "/Dockerfile",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "FROM python:3.8\n\nRUN useradd -ms /bin/bash user\nUSER user\n\nCOPY . /home/user/app/\nWORKDIR /home/user/app\nRUN pip install --user -r requirements.txt\n\nCMD make run\n"
},
{
"alpha_fraction": 0.7046818733215332,
"alphanum_fraction": 0.7046818733215332,
"avg_line_length": 35.75,
"blob_id": "cfb915c71dc04d687c023669b7e5d78e06e0dcaa",
"content_id": "69c6a2dcbabc827386114a65afa91d073fde4ff5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2499,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 68,
"path": "/people_api/models/person_read.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON - READ\nPerson Read model. Inherits from PersonCreate and adds the person_id field, which is the _id field on Mongo documents\n\"\"\"\n\n# # Native # #\nfrom datetime import date, datetime\nfrom typing import Optional, List\nfrom people_api.models.alarm_signal_update import AlarmSignal\n\n# # Installed # #\nimport pydantic\nfrom dateutil.relativedelta import relativedelta\n\n# # Package # #\nfrom .person_create import ContactCreate\nfrom .person_update import ContactUpdate\nfrom .fields import ContactFields\nfrom .person_address import Address\nfrom .person_comorbidity import Comorbidity\nfrom .person_symptoms import Symptoms\nfrom .person_eess import Eess\n\n__all__ = (\"ContactRead\", \"ContactsRead\")\n\n\nclass ContactRead(ContactUpdate):\n \"\"\"Body of Person GET and POST responses\"\"\"\n contact_id: Optional[str] = ContactFields.person_id\n parent_contact_id: Optional[str] = ContactFields.person_id\n doc_type: Optional[str] = ContactFields.doc_type\n doc_number: Optional[str] = ContactFields.doc_number\n name: Optional[str] = ContactFields.name\n first_name: Optional[str] = ContactFields.first_name\n last_name: Optional[str] = ContactFields.last_name\n birth: Optional[date] = ContactFields.birth\n start_date: Optional[date] = ContactFields.start_date\n alternative_cellphone_number: Optional[\n str] = ContactFields.alternative_cellphone_number\n cellphone_number: Optional[str] = ContactFields.cellphone_number\n address: Optional[Address]\n comorbidity: Optional[Comorbidity]\n symptoms: Optional[List[Symptoms]]\n # eess: Optional[Eess]\n # alarm_signal: Optional[AlarmSignal]\n\n @pydantic.root_validator(pre=True)\n def _set_contact_id(cls, data):\n \"\"\"Swap the field _id to person_id (this could be done with field alias, by setting the field as \"_id\"\n and the alias as \"contact_id\", but can be quite confusing)\"\"\"\n document_id = data.get(\"_id\")\n if document_id:\n data[\"contact_id\"] = document_id\n return data\n\n @pydantic.root_validator()\n def _set_age(cls, data):\n \"\"\"Calculate the current age of the person from the date of birth, if any\"\"\"\n birth = data.get(\"birth\")\n if birth:\n today = datetime.now().date()\n data[\"age\"] = relativedelta(today, birth).years\n return data\n\n class Config(ContactCreate.Config):\n extra = pydantic.Extra.ignore # if a read document has extra fields, ignore them\n\n\nContactsRead = List[ContactRead]\n"
},
{
"alpha_fraction": 0.6059184074401855,
"alphanum_fraction": 0.6059184074401855,
"avg_line_length": 36.788177490234375,
"blob_id": "cdf2377ac3513bfcf8e5518b8cc99ad6d3e16060",
"content_id": "89363b663411163823f8211b446674e556af9d7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7671,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 203,
"path": "/people_api/repositories.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"REPOSITORIES\nMethods to interact with the database\n\"\"\"\n\n# # Package # #\nfrom people_api.models.alarm_signal_create import AlarmSignalCreate\nfrom .models import *\nfrom .exceptions import *\nfrom .database import collection, symptomCollection\nfrom .utils import get_time, get_uuid\n\n__all__ = (\n \"ContactRepository\",\n \"SymptomsRepository\",\n)\n\n\nclass ContactRepository:\n @staticmethod\n def getByImei(imei: str) -> ContactRead:\n \"\"\"Retrieve a single Person by its unique IMEI\"\"\"\n print(imei)\n document = collection.find_one({\"imei\": imei})\n if not document:\n raise ContactNotFoundException(imei)\n return ContactRead(**document)\n\n @staticmethod\n def get(contact_id: str) -> ContactRead:\n \"\"\"Retrieve a single Person by its unique id\"\"\"\n document = collection.find_one({\"_id\": contact_id})\n print(document)\n if not document:\n raise ContactNotFoundException(contact_id)\n return ContactRead(**document)\n\n @staticmethod\n def list() -> ContactsRead:\n \"\"\"Retrieve all the available persons\"\"\"\n cursor = collection.find()\n # for document in cursor:\n # print(document)\n return [ContactRead(**document) for document in cursor]\n\n @staticmethod\n def create(create: ContactCreate) -> ContactRead:\n \"\"\"Create a person and return its Read object\"\"\"\n print(create)\n document = create.dict()\n document[\"created\"] = document[\"updated\"] = get_time()\n document[\"_id\"] = get_uuid()\n # The time and id could be inserted as a model's Field default factory,\n # but would require having another model for Repository only to implement it\n\n result = collection.insert_one(document)\n assert result.acknowledged\n\n return ContactRepository.get(result.inserted_id)\n\n @staticmethod\n def update(contact_id: str, update: ContactUpdate):\n \"\"\"Update a person by giving only the fields to update\"\"\"\n # record = collection.find_one({\"_id\": person_id})\n # if not record:\n # raise PersonNotFoundException(person_id)\n document = update.dict()\n document[\"updated\"] = get_time()\n # symptoms = record.pop(\"symptoms\")\n # print(symptoms)\n # symptoms.append(document)\n # document[\"symptoms\"] = symptoms\n # print(document)\n result = collection.update_one({\"_id\": contact_id}, {\"$set\": document})\n if not result.modified_count:\n raise ContactNotFoundException(identifier=contact_id)\n\n @staticmethod\n def addSymptom(contact_id: str, update: SymptomUpdate):\n \"\"\"Add a person symptom by giving only the fields to update\"\"\"\n # record = collection.find_one({\"_id\": person_id})\n # if not record:\n # raise PersonNotFoundException(person_id)\n document = update.dict()\n document[\"updated\"] = get_time()\n # symptoms = record.pop(\"symptoms\")\n # print(symptoms)\n # symptoms.append(document)\n # document[\"symptoms\"] = symptoms\n # print(document)\n result = collection.update_one({\"_id\": contact_id},\n {\"$push\": {\n \"symptoms\": document\n }})\n if not result.modified_count:\n raise ContactNotFoundException(identifier=contact_id)\n\n @staticmethod\n def addAlarmSignal(contact_id: str, update: AlarmSignalCreate):\n \"\"\"Add a person symptom by giving only the fields to update\"\"\"\n # record = collection.find_one({\"_id\": person_id})\n # if not record:\n # raise PersonNotFoundException(person_id)\n document = update.dict()\n document[\"updated\"] = get_time()\n # symptoms = record.pop(\"symptoms\")\n # print(symptoms)\n # symptoms.append(document)\n # document[\"symptoms\"] = symptoms\n # print(document)\n result = collection.update_one({\"_id\": contact_id},\n {\"$set\": {\n \"symptoms.alarm_signal\": document\n }})\n if not result.modified_count:\n raise ContactNotFoundException(identifier=contact_id)\n\n @staticmethod\n def delete(contact_id: str):\n \"\"\"Delete a person given its unique id\"\"\"\n result = collection.delete_one({\"_id\": contact_id})\n if not result.deleted_count:\n raise ContactNotFoundException(identifier=contact_id)\n\n\nclass SymptomsRepository:\n @staticmethod\n def get(symptom_id: str) -> SymptomRead:\n \"\"\"Retrieve a single Symptom by its unique id\"\"\"\n document = symptomCollection.find_one({\"_id\": symptom_id})\n if not document:\n raise SymptomNotFoundException(symptom_id)\n return SymptomRead(**document)\n\n @staticmethod\n def list(person_id: str) -> SymptomsRead:\n \"\"\"Retrieve all the available symptoms\"\"\"\n print(\"person_id\", person_id)\n cursor = symptomCollection.find({\"person_id\": person_id})\n return [SymptomRead(**document) for document in cursor]\n\n @staticmethod\n def create(create: SymptomCreate) -> SymptomRead:\n \"\"\"Create a symptom and return its Read object\"\"\"\n document = create.dict()\n document[\"created\"] = document[\"updated\"] = get_time()\n document[\"_id\"] = get_uuid()\n # The time and id could be inserted as a model's Field default factory,\n # but would require having another model for Repository only to implement it\n\n result = symptomCollection.insert_one(document)\n assert result.acknowledged\n\n return SymptomsRepository.get(result.inserted_id)\n\n @staticmethod\n def update(symptom_id: str, update: SymptomUpdate):\n \"\"\"Update a symptom by giving only the fields to update\"\"\"\n # record = collection.find_one({\"_id\": person_id})\n # if not record:\n # raise PersonNotFoundException(person_id)\n document = update.dict()\n document[\"updated\"] = get_time()\n # symptoms = record.pop(\"symptoms\")\n # print(symptoms)\n # symptoms.append(document)\n # document[\"symptoms\"] = symptoms\n # print(document)\n result = symptomCollection.update_one({\"_id\": symptom_id},\n {\"$set\": document})\n if not result.modified_count:\n raise SymptomNotFoundException(identifier=symptom_id)\n\n @staticmethod\n def delete(symptom_id: str):\n \"\"\"Delete a symptom given its unique id\"\"\"\n result = symptomCollection.delete_one({\"_id\": symptom_id})\n if not result.deleted_count:\n raise SymptomNotFoundException(identifier=symptom_id)\n\n\n# class ComorbidityRespository:\n# @staticmethod\n# def create(create: ComorbidityCreate) -> ComorbidityCreate:\n# \"\"\"Create a comorbidity and return its Read object\"\"\"\n# document = create.dict()\n# document[\"created\"] = document[\"updated\"] = get_time()\n# document[\"_id\"] = get_uuid()\n# result = collection.insert_one(document)\n# assert result.acknowledged\n\n# return result\n\n# class SymptomsRepository:\n# @staticmethod\n# def create(create: SymptomsCreate) -> SymptomsCreate:\n# \"\"\"Create a symptoms and return its Read object\"\"\"\n# document = create.dict()\n# document[\"created\"] = document[\"updated\"] = get_time()\n# document[\"_id\"] = get_uuid()\n# result = collection.insert_one(document)\n# assert result.acknowledged\n\n# return result\n"
},
{
"alpha_fraction": 0.8703703880310059,
"alphanum_fraction": 0.8703703880310059,
"avg_line_length": 9.800000190734863,
"blob_id": "19a225af405c1e5e4c559a451bc7542c84ed69c8",
"content_id": "4ff7b99601dc5af492650921747b7e3596d51ed2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 54,
"license_type": "no_license",
"max_line_length": 15,
"num_lines": 5,
"path": "/requirements.txt",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "fastapi\nuvicorn\npymongo\npython-dateutil\npython-dotenv\n"
},
{
"alpha_fraction": 0.7490683197975159,
"alphanum_fraction": 0.7490683197975159,
"avg_line_length": 35.59090805053711,
"blob_id": "aec69e2f9f0c42d8c4545a63cb59931330975e17",
"content_id": "db5e4ed5c15ad9a3b5e2a20d0f9ffedbf245f9aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 805,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 22,
"path": "/people_api/models/person_create.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON - CREATE\nPerson Create model. Inherits from PersonUpdate, but all the required fields must be re-defined\n\"\"\"\nfrom typing import Optional, List\n\n# # Package # #\nfrom .person_update import ContactUpdate\nfrom .person_address import Address\nfrom .fields import ContactFields, ComorbidityFields, AddressFields\n\n__all__ = (\"ContactCreate\", )\n\n\nclass ContactCreate(ContactUpdate):\n \"\"\"Body of Person POST requests\"\"\"\n name: str = ContactFields.name\n first_name: str = ContactFields.first_name\n last_name: Optional[str] = ContactFields.last_name\n alternative_cellphone_number: str = ContactFields.alternative_cellphone_number\n doc_type: str = ContactFields.doc_type\n doc_number: str = ContactFields.doc_number\n # Birth remains Optional, so is not required to re-declare\n"
},
{
"alpha_fraction": 0.6855104565620422,
"alphanum_fraction": 0.6975850462913513,
"avg_line_length": 32.12727355957031,
"blob_id": "a86ad5139010d753d0b10c07c9594cc6c6b308dd",
"content_id": "cfbf8fb721fb72d40582e09c838e9e5f04f3e876",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1822,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 55,
"path": "/people_api/models/symptom_read.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON - READ\nPerson Read model. Inherits from PersonCreate and adds the person_id field, which is the _id field on Mongo documents\n\"\"\"\n\n# # Native # #\nfrom datetime import date, datetime\n\nfrom typing import Optional, List\nfrom people_api.models.alarm_signal_update import AlarmSignal\n\n# # Installed # #\nimport pydantic\nfrom dateutil.relativedelta import relativedelta\n\n# # Package # #\nfrom .symptom_create import SymptomCreate\nfrom .fields import SymptomFields\n\n__all__ = (\"SymptomRead\", \"SymptomsRead\")\n\n\nclass SymptomRead(SymptomCreate):\n \"\"\"Body of Symptom GET and POST responses\"\"\"\n person_id: str = SymptomFields.person_id\n symptom_id: str = SymptomFields.symptom_id\n q1: str = SymptomFields.q1\n q2: str = SymptomFields.q2\n q3: str = SymptomFields.q3\n q4: str = SymptomFields.q4\n q5: str = SymptomFields.q5\n q6: str = SymptomFields.q6\n q7: str = SymptomFields.q7\n q8: str = SymptomFields.q8\n q9: str = SymptomFields.q9\n q10: str = SymptomFields.q10\n is_suspicious: bool = SymptomFields.is_suspicious\n latitude: Optional[str] = SymptomFields.latitude\n longitude: Optional[str] = SymptomFields.longitude\n createt_at : Optional[date] = SymptomFields.created_at\n alarm_signal: Optional[AlarmSignal]\n \n @pydantic.root_validator(pre=True)\n def _set_symptom_id(cls, data):\n \"\"\"Swap the field _id to symptom_id (this could be done with field alias, by setting the field as \"_id\"\n and the alias as \"symptom_id\", but can be quite confusing)\"\"\"\n document_id = data.get(\"_id\")\n if document_id:\n data[\"symptom_id\"] = document_id\n return data\n\n class Config(SymptomCreate.Config):\n extra = pydantic.Extra.ignore # if a read document has extra fields, ignore them\n\n\nSymptomsRead = List[SymptomRead]\n"
},
{
"alpha_fraction": 0.7016706466674805,
"alphanum_fraction": 0.7016706466674805,
"avg_line_length": 19.950000762939453,
"blob_id": "25c5365fda3e28aa5f4d807510470d8ce47c546f",
"content_id": "f19bd20a1a174e3413b38ea874a11de15eceb68c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 419,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 20,
"path": "/people_api/models/person_eess.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"MODELS - PERSON SYMPTOMS\nThe symptoms of a person is part of the Person model\n\"\"\"\n\n# # Native # #\nfrom datetime import date\nfrom typing import Optional\nfrom contextlib import suppress\n\n# # Package # #\nfrom .common import BaseModel\nfrom .fields import EessFields\n\n__all__ = (\"Eess\", )\n\n\nclass Eess(BaseModel):\n \"\"\"The EESS information of a person\"\"\"\n code: str = EessFields.code\n name: str = EessFields.name\n"
},
{
"alpha_fraction": 0.8350515365600586,
"alphanum_fraction": 0.8350515365600586,
"avg_line_length": 23.125,
"blob_id": "eab24e1a4c403219298e405ae1d22819e5b338a5",
"content_id": "5869b12b859805d56414d8e8eb94d23ac15177a8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 194,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 8,
"path": "/people_api/models/alarm_signal_create.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "from typing import Optional\nfrom people_api.models.alarm_signal_update import AlarmSignal\n\nfrom people_api.models.fields import AlarmSignalFields\n\n\nclass AlarmSignalCreate(AlarmSignal):\n pass\n\n"
},
{
"alpha_fraction": 0.6474575996398926,
"alphanum_fraction": 0.6689265370368958,
"avg_line_length": 22.289474487304688,
"blob_id": "3e5bc117196b973e8fae9483c9bdb8cb7f4816ed",
"content_id": "0573b3cd3dfee6b16c5e7f96222949ab2197d454",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 885,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 38,
"path": "/people_api/settings.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"SETTINGS\nSettings loaders using Pydantic BaseSettings classes (load from environment variables / dotenv file)\n\"\"\"\n\n# # Installed # #\nimport pydantic\n\n__all__ = (\"api_settings\", \"mongo_settings\")\n\n\nclass BaseSettings(pydantic.BaseSettings):\n class Config:\n env_file = \".env\"\n\n\nclass APISettings(BaseSettings):\n title: str = \"People API\"\n host: str = \"0.0.0.0\"\n port: int = 5000\n log_level: str = \"INFO\"\n\n class Config(BaseSettings.Config):\n env_prefix = \"API_\"\n\n\nclass MongoSettings(BaseSettings):\n uri: str = \"mongodb://127.0.0.1:27017\"\n database: str = \"fastapi+pydantic+mongo-example\"\n collection: str = \"people\"\n symptoms_collection: str = \"symptoms\"\n comorbidity_collection: str = \"comorbidities\"\n\n class Config(BaseSettings.Config):\n env_prefix = \"MONGO_\"\n\n\napi_settings = APISettings()\nmongo_settings = MongoSettings()\n"
},
{
"alpha_fraction": 0.6681034564971924,
"alphanum_fraction": 0.6745689511299133,
"avg_line_length": 22.200000762939453,
"blob_id": "c1a89149464d334f7ec1c418a79fd7fc2e1b5282",
"content_id": "694bc9800a98b894d46640ec821577203083e9a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 464,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 20,
"path": "/people_api/utils.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"UTILS\nMisc helpers/utils functions\n\"\"\"\n\n# # Native # #\nfrom time import time\nfrom uuid import uuid4\nfrom typing import Union\n\n__all__ = (\"get_time\", \"get_uuid\")\n\n\ndef get_time(seconds_precision=True) -> Union[int, float]:\n \"\"\"Returns the current time as Unix/Epoch timestamp, seconds precision by default\"\"\"\n return time() if not seconds_precision else int(time())\n\n\ndef get_uuid() -> str:\n \"\"\"Returns an unique UUID (UUID4)\"\"\"\n return str(uuid4())\n"
},
{
"alpha_fraction": 0.6780309081077576,
"alphanum_fraction": 0.682687520980835,
"avg_line_length": 31.67934799194336,
"blob_id": "fa509bb7895e68646eeccef3c3261ac5d62d2cf9",
"content_id": "9f9feba3facf7d7aed6f12b4d81ff09429e8ac9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6013,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 184,
"path": "/people_api/app.py",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": "\"\"\"APP\nFastAPI app definition, initialization and definition of routes\n\"\"\"\n\n# # Installed # #\nfrom people_api.models.alarm_signal_create import AlarmSignalCreate\nimport uvicorn\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi import status as statuscode\nfrom fastapi.responses import JSONResponse\n\n# # Package # #\nfrom .models import *\nfrom .exceptions import *\nfrom .repositories import ContactRepository, SymptomsRepository\nfrom .middlewares import request_handler\nfrom .settings import api_settings as settings\n\n__all__ = (\"app\", \"run\")\n\napp = FastAPI(title=settings.title)\napp.middleware(\"http\")(request_handler)\n\norigins = [\n \"http://localhost\",\n \"http://localhost:8080\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\[email protected](\"/imei/{imei}\",\n response_model=ContactRead,\n description=\"Get a single person by its unique IMEI\",\n responses=get_exception_responses(ContactNotFoundException),\n tags=[\"people\"])\ndef _get_contact(imei: str):\n return ContactRepository.getByImei(imei)\n\n\[email protected](\"/people\",\n response_model=ContactsRead,\n description=\"List all the available persons\",\n tags=[\"people\"])\ndef _list_contacts():\n # TODO Filters\n return ContactRepository.list()\n\n\[email protected](\"/people/{contact_id}\",\n response_model=ContactRead,\n description=\"Get a single person by its unique ID\",\n responses=get_exception_responses(ContactNotFoundException),\n tags=[\"people\"])\ndef _get_contact(contact_id: str):\n return ContactRepository.get(contact_id)\n\n\[email protected](\"/people\",\n description=\"Create a new person\",\n response_model=ContactRead,\n status_code=statuscode.HTTP_201_CREATED,\n responses=get_exception_responses(ContactAlreadyExistsException),\n tags=[\"people\"])\ndef _create_person(create: ContactCreate):\n print(create)\n return ContactRepository.create(create)\n\n\[email protected](\n \"/people/{contact_id}\",\n description=\"Update a single person by its unique ID, providing the fields to update\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(ContactNotFoundException,\n ContactAlreadyExistsException),\n tags=[\"people\"])\ndef _update_contact(contact_id: str, update: ContactUpdate):\n ContactRepository.update(contact_id, update)\n\n\[email protected](\n \"/people-symptom/{contact_id}\",\n description=\"Add a single symptom object for person by its unique ID, providing the fields to update\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(ContactNotFoundException,\n ContactAlreadyExistsException),\n tags=[\"people\"])\ndef _add_symptom(contact_id: str, update: SymptomUpdate):\n ContactRepository.addSymptom(contact_id, update)\n\[email protected](\n \"/people-symptom-alarmsignal/{contact_id}\",\n description=\"Add a single symptom object for person by its unique ID, providing the fields to update\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(ContactNotFoundException,\n ContactAlreadyExistsException),\n tags=[\"people\"])\ndef _add_alarmsignal(contact_id: str, update: AlarmSignalCreate):\n ContactRepository.addAlarmSignal(contact_id, update)\n\n\n# Symtoms\n\n\[email protected](\"/person-symptoms/{person_id}\",\n response_model=SymptomsRead,\n description=\"List all the available symptoms\",\n tags=[\"symptoms\"])\ndef _list_person_symptoms(contact_id: str):\n # TODO Filters\n print(contact_id)\n return SymptomsRepository.list(contact_id)\n\n\[email protected](\"/symptoms\",\n response_model=SymptomsRead,\n description=\"List all the available symptoms\",\n tags=[\"symptoms\"])\ndef _list_symptoms():\n # TODO Filters\n return SymptomsRepository.list()\n\n\[email protected](\"/symptoms/{symptom_id}\",\n response_model=SymptomRead,\n description=\"Get a single symptom by its unique ID\",\n responses=get_exception_responses(SymptomNotFoundException),\n tags=[\"symptoms\"])\ndef _get_symptom(symptom_id: str):\n return SymptomRepository.get(symptom_id)\n\n\[email protected](\"/symptoms\",\n description=\"Create a new symptom\",\n response_model=SymptomRead,\n status_code=statuscode.HTTP_201_CREATED,\n responses=get_exception_responses(SymptomAlreadyExistsException),\n tags=[\"symptoms\"])\ndef _create_symptom(create: SymptomCreate):\n return SymptomsRepository.create(create)\n\n\[email protected](\n \"/symptoms/{symptoms_id}\",\n description=\"Update a single symptom by its unique ID, providing the fields to update\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(SymptomNotFoundException,\n SymptomAlreadyExistsException),\n tags=[\"symptoms\"])\ndef _update_symptom(symptom_id: str, update: SymptomUpdate):\n SymptomRepository.update(symptom_id, update)\n\n\[email protected](\"/symptoms/{symptom_id}\",\n description=\"Delete a single symptom by its unique ID\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(SymptomNotFoundException),\n tags=[\"symptoms\"])\ndef _delete_symptom(symptom_id: str):\n SymptomsRepository.delete(symptom_id)\n\n\[email protected](\"/people/{person_id}\",\n description=\"Delete a single person by its unique ID\",\n status_code=statuscode.HTTP_204_NO_CONTENT,\n responses=get_exception_responses(ContactNotFoundException),\n tags=[\"people\"])\ndef _delete_person(contact_id: str):\n ContactRepository.delete(contact_id)\n\n\ndef run():\n \"\"\"Run the API using Uvicorn\"\"\"\n uvicorn.run(app,\n host=settings.host,\n port=settings.port,\n log_level=settings.log_level.lower())\n"
},
{
"alpha_fraction": 0.7241379022598267,
"alphanum_fraction": 0.7339901328086853,
"avg_line_length": 28,
"blob_id": "2b7acfcf0432cd9339e2cc0c31cfb34a58ba53b1",
"content_id": "8c1639b689319f2387070db1dfce39c391965e55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1015,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 35,
"path": "/Makefile",
"repo_name": "DevHerles/minsa_viajeros",
"src_encoding": "UTF-8",
"text": ".DEFAULT_GOAL := help\n\ninstall-requirements: ## pip install requirements for app\n\tpip install -r requirements.txt\n\ninstall-test-requirements: ## pip install requirements for tests\n\tpip install -r requirements-test.txt\n\ninstall-all-requirements: ## pip install requirements for app & tests\n\tmake install-requirements\n\tmake install-test-requirements\n\ntest: ## run tests\n\tpytest -sv .\n\nrun: ## python run app\n\tpython .\n\nrun-docker: ## start running through docker-compose\n\tdocker-compose up\n\nrun-docker-background: ## start running through docker-compose, detached\n\tdocker-compose up -d\n\nteardown-docker: ## remove from docker through docker-compose\n\tdocker-compose down\n\nstart-test-mongo: ## start mongodb in docker for tests\n\tdocker run -d --rm --name=fastapi_mongodb_tests -p 27017:27017 --tmpfs=/data/db mongo\n\nstop-test-mongo: ## stop dockerized mongodb for tests\n\tdocker stop fastapi_mongodb_tests\n\nhelp: ## show this help.\n\t@fgrep -h \"##\" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\\\$$//' | sed -e 's/##//'\n"
}
] | 25 |
renansantosmendes/PhD_2019_01
|
https://github.com/renansantosmendes/PhD_2019_01
|
4f1c3717a84c67ab4cc3638edac29cf0eb3e1cde
|
5d2e65436830b576ba3085227ca3b1259c22f291
|
cdadf6fe9ef011b07c2eb848ccd5960781695f55
|
refs/heads/master
| 2022-07-13T22:05:22.163969 | 2021-06-10T15:32:26 | 2021-06-10T15:32:26 | 180,044,929 | 1 | 0 | null | 2019-04-08T01:09:27 | 2020-11-17T00:02:37 | 2020-11-17T00:02:06 |
Jupyter Notebook
|
[
{
"alpha_fraction": 0.5528141856193542,
"alphanum_fraction": 0.5902081727981567,
"avg_line_length": 24.940000534057617,
"blob_id": "1f8a5fe68dd4ec797b80d9570a78e080efa1dd7f",
"content_id": "e53481caf470cde21a41041eb0ce30e7c168162c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 2604,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 100,
"path": "/PhD_2019_01/hierarchical_clustering_solution.R",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "# load the lavaan package (only needed once per session)\nlibrary(lavaan)\n\n# set file path\nsetwd(\"/home/renansantos/Área de Trabalho/Doutorado/PhD_2019_01/PhD_2019_01/RandomSolutions\")\n\n# loading the data\ndados <- read.table(\"random_solutions.txt\", header=TRUE, sep=',')\nlibrary(\"ggplot2\")\nlibrary(\"ggdendro\")\nattach(dados)\nhead(dados)\n\n# normalizing the data\nobj <- dados\n\nfor(i in 1:length(obj)){\n obj$f1 <- (obj$f1 - mean(obj$f1))/(sd(obj$f1) )\n obj$f2 <- (obj$f2 - mean(obj$f2))/(sd(obj$f2) )\n obj$f3 <- (obj$f3 - mean(obj$f3))/(sd(obj$f3) )\n obj$f4 <- (obj$f4 - mean(obj$f4))/(sd(obj$f4) )\n obj$f5 <- (obj$f5 - mean(obj$f5))/(sd(obj$f5) )\n obj$f6 <- (obj$f6 - mean(obj$f6))/(sd(obj$f6) )\n obj$f7 <- (obj$f7 - meakendalln(obj$f7))/(sd(obj$f7) )\n obj$f8 <- (obj$f8 - mean(obj$f8))/(sd(obj$f8) )\n}\n\n# Cálculo da correlação para formulação do problema com 5 funções objetivo\nFO <- cbind(obj$f1,obj$f2,obj$f3,obj$f4,obj$f5,obj$f6,obj$f7,obj$f8)\n\nd <- cor(FO, method='pearson')\n# Determinando a similaridade\nI <- diag(rep(1,dim(d)[1]))\n#D <- d - I\n\n#min_value = D[which.min(D)]\n#max_value = D[which.max(D)]\nD <- d\nfor(i in 1:length(D)){\n D[i] = (D[i] - min(D)) / (max(D) - min(D))\n}\n\nD <- d - I\n\noutput_cluster<-hclust(as.dist(d),method='single')\ndendograma_output_cluster<-plclust(output_cluster,ylab='Correlation')\n\n# daqui pra baixo que está melhor pra plotar\na <- cbind(f1,f2,f3,f4,f5,f6,f7,f8)\ndissimilarity_kendall <- 1 - abs(cor(a, method='kendall'))\ndissimilarity_pearson <- 1 - abs(cor(a, method='pearson'))\ndistance_kendall <- as.dist(dissimilarity_kendall)\ndistance_pearson <- as.dist(dissimilarity_pearson)\n\nplot(hclust(distance_kendall, method = 'single'),\n main=\"\",\n xlab=\"\",\n ylab=\"\",\n sub = \"\",\n hang = -1,\n cex = 1.5,\n lwd = 1.5)\n\nplot(hclust(distance_pearson, method = 'single'),\n main=\"\",\n xlab=\"\",\n ylab=\"\",\n sub = \"\",\n hang = -1,\n cex = 1.5,\n lwd = 1.5)\n\na <- cbind(f1,f2,f3,f4,f5,f6,f7,f8)\na <- head(a)\ndissimilarity_kendall <- 1 - abs(cor(a, method='kendall'))\n\nb <- cbind(a[f1])\n\ndissimilarity_kendall\ndistance_kendall <- as.dist(dissimilarity_kendall)\n\nplot(hclust(distance_kendall, method = 'single'),\n main=\"\",\n xlab=\"\",\n ylab=\"\",\n sub = \"\",\n hang = -1,\n cex = 1.5,\n lwd = 1.5)\n\n#hc <- hclust(distance, method = 'single')\n# USAR ESTE AQUI PARA IMPRIMIR O DENDOGRAMA -> FOI O MELHOR ATÉ AGORA\n#ggdendrogram(hc,\n# main=\"\",\n# xlab=\"\",\n# ylab=\"\",\n# sub = \"\",\n# hang = -1,\n# cex = 1.5,\n# lwd = 2)\n"
},
{
"alpha_fraction": 0.6367605924606323,
"alphanum_fraction": 0.6411274075508118,
"avg_line_length": 36.78499984741211,
"blob_id": "6fcb6b11c00eb6e3d5c4f3c8b057c52e1a115f2d",
"content_id": "73a73adfdbb491f27ebdb102e9ef46bc2c1d5e90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7557,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 200,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/filter/unsupervised/RSM.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.filter.unsupervised;\n\nimport KFST.util.ArraysFunc;\nimport java.util.Arrays;\nimport java.util.Random;\nimport KFST.featureSelection.filter.FilterApproach;\nimport KFST.gui.featureSelection.filter.rsm.MultivariateMethodType;\n\n/**\n * This java class is used to implement the random subspace method(RSM) method.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.filter.FilterApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class RSM extends FilterApproach {\n\n private final int NUM_ITERATION;\n private final int SIZE_SUB_SPACE;\n private final int THRESHOLD_ELIMINATION;\n private final MultivariateMethodType NAME_MULTI_APPROACH;\n private int[] featureScore;\n\n /**\n * initializes the parameters\n *\n * @param arguments array of parameters contains\n * (<code>sizeSelectedFeatureSubset</code>, <code>numIter</code>,\n * <code>size</code>, <code>threshold</code>, <code>nameApproach</code>) in\n * which <code><b><i>sizeSelectedFeatureSubset</i></b></code> is the number\n * of selected features, <code><b><i>numIter</i></b></code> is the number of\n * iteration in the RSM method, <code><b><i>size</i></b></code> is the size\n * of the subspace, <code><b><i>threshold</i></b></code> is the number of\n * selected features in each subspace, and\n * <code><b><i>nameApproach</i></b></code> is the name of the multivariate\n * approach used in the RSM\n */\n public RSM(Object... arguments) {\n super((int) arguments[0]);\n NUM_ITERATION = (int) arguments[1];\n SIZE_SUB_SPACE = (int) arguments[2];\n THRESHOLD_ELIMINATION = (int) arguments[3];\n NAME_MULTI_APPROACH = (MultivariateMethodType) arguments[4];\n }\n\n /**\n * initializes the parameters\n *\n * @param sizeSelectedFeatureSubset the number of selected features\n * @param numIter the number of iteration in the RSM method\n * @param size the size of the subspace\n * @param threshold the number of selected features in each subspace\n * @param nameApproach the name of the multivariate approach used in the RSM\n */\n public RSM(int sizeSelectedFeatureSubset, int numIter, int size, int threshold, MultivariateMethodType nameApproach) {\n super(sizeSelectedFeatureSubset);\n NUM_ITERATION = numIter;\n SIZE_SUB_SPACE = size;\n THRESHOLD_ELIMINATION = threshold;\n NAME_MULTI_APPROACH = nameApproach;\n }\n\n /**\n * permutes the index of features\n *\n * @param indexFeat the array of the index of features\n * @param seed determines the index of the seed\n */\n private void permutation(int[] indexFeat, int seed) {\n Random rand = new Random(seed);\n for (int i = 0; i < indexFeat.length; i++) {\n int index1 = rand.nextInt(indexFeat.length);\n int index2 = rand.nextInt(indexFeat.length);\n\n //swap the two values of the indexFeat array\n int temp = indexFeat[index1];\n indexFeat[index1] = indexFeat[index2];\n indexFeat[index2] = temp;\n }\n }\n\n /**\n * selects the top feature with size THRESHOLD_ELIMINATION by given method\n *\n * @param data the new dataset\n *\n * @return the top feature with size THRESHOLD_ELIMINATION\n */\n private int[] multivariateApproach(double[][] data) {\n int[] resultSelectedFeature;\n if (NAME_MULTI_APPROACH == MultivariateMethodType.MUTUAL_CORRELATION) {\n MutualCorrelation mc = new MutualCorrelation(THRESHOLD_ELIMINATION);\n mc.loadDataSet(data, SIZE_SUB_SPACE, numClass);\n mc.evaluateFeatures();\n resultSelectedFeature = mc.getSelectedFeatureSubset();\n } else {\n resultSelectedFeature = new int[THRESHOLD_ELIMINATION];\n }\n return resultSelectedFeature;\n }\n\n /**\n * creates a new dataset based on the given indeces of the features\n *\n * @param index an array of the indeces of features\n *\n * @return a new dataset\n */\n private double[][] createNewDataset(int[] index) {\n double[][] newData = new double[trainSet.length][SIZE_SUB_SPACE + 1];\n\n for (int i = 0; i < trainSet.length; i++) {\n for (int j = 0; j < SIZE_SUB_SPACE; j++) {\n newData[i][j] = trainSet[i][index[j]];\n }\n newData[i][SIZE_SUB_SPACE] = trainSet[i][numFeatures];\n }\n\n return newData;\n }\n\n /**\n * starts the feature selection process by random subspace method(RSM)\n */\n @Override\n public void evaluateFeatures() {\n featureScore = new int[numFeatures];\n int[] indexFeatures = new int[numFeatures];\n int[] indecesFeatScore;\n\n //initializes the feature index values\n for (int i = 0; i < indexFeatures.length; i++) {\n indexFeatures[i] = i;\n }\n\n for (int i = 0; i < NUM_ITERATION; i++) {\n// System.out.println(\"\\nIteration \" + i + \":\\n\\n\");\n permutation(indexFeatures, i);\n\n int[] featSpace = Arrays.copyOfRange(indexFeatures, 0, SIZE_SUB_SPACE);\n ArraysFunc.sortArray1D(featSpace, false);\n\n //creates a new dataset based on featSpace array\n double[][] newDataset = createNewDataset(featSpace);\n\n //selects the top feature with size THRESHOLD_ELIMINATION by given method\n int[] featSelected = multivariateApproach(newDataset);\n\n //updates the score of the feature selected by mutual correlation\n for (int j = 0; j < THRESHOLD_ELIMINATION; j++) {\n featureScore[featSpace[featSelected[j]]]++;\n }\n }\n\n indecesFeatScore = ArraysFunc.sortWithIndex(Arrays.copyOf(featureScore, featureScore.length), true);\n// for (int i = 0; i < numFeatures; i++) {\n// System.out.println(i + \") = \" + featureScore[i]);\n// }\n\n selectedFeatureSubset = Arrays.copyOfRange(indecesFeatScore, 0, numSelectedFeature);\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String validate() {\n if (SIZE_SUB_SPACE > numFeatures || THRESHOLD_ELIMINATION > SIZE_SUB_SPACE) {\n return \"The parameter values of RSM (size of subspace or elimination threshold) are incorred.\";\n }\n return \"\";\n }\n}\n"
},
{
"alpha_fraction": 0.6709034442901611,
"alphanum_fraction": 0.6738234162330627,
"avg_line_length": 43.78461456298828,
"blob_id": "cd44b75405155f03a091791bba01e08ce00a9c68",
"content_id": "f16c0e9d044e0a379a1448c6bdabd30aa2a0081e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5822,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 130,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/HGAFS/HGAFS.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods.HGAFS;\n\nimport KFST.featureSelection.wrapper.GABasedMethods.BasicGA;\nimport KFST.util.ArraysFunc;\nimport java.util.ArrayList;\n\n/**\n * This java class is used to implement feature selection method based on hybrid\n * genetic algorithm for feature selection using local search (HGAFS) in which\n * the type of Population is extended from Population class.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.GABasedMethods.BasicGA\n * @see KFST.featureSelection.wrapper.WrapperApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class HGAFS extends BasicGA<Population> {\n\n /**\n * initializes the parameters\n *\n * @param arguments array of parameters contains ( <code>path</code>,\n * <code>numFeatures</code>, <code>classifierType</code>,\n * <code>selectedClassifierPan</code>, <code>selectionType</code>,\n * <code>crossoverType</code>, <code>mutationType</code>,\n * <code>replacementType</code>, <code>numIteration</code>\n * <code>populationSize</code>, <code>crossoverRate</code>,\n * <code>mutationRate</code>, <code>kFolds</code> , <code>epsilon</code> ,\n * <code>mu</code> ) in which <code><b><i>path</i></b></code> is the path of\n * the project, <code><b><i>numFeatures</i></b></code> is the number of\n * original features in the dataset,\n * <code><b><i>classifierType</i></b></code> is the classifier type for\n * evaluating the fitness of a solution,\n * <code><b><i>selectedClassifierPan</i></b></code> is the selected\n * classifier panel, <code><b><i>selectionType</i></b></code> is used for\n * selecting parents from the individuals of a population according to their\n * fitness, <code><b><i>crossoverType</i></b></code> is used for recombining\n * the parents to generate new offsprings based on crossover rate,\n * <code><b><i>mutationType</i></b></code> is used for mutating new\n * offsprings by changing the value of some genes in them based on mutation\n * rate, <code><b><i>replacementType</i></b></code> is used for handling\n * populations from one generation to the next generation,\n * <code><b><i>numIteration</i></b></code> is the maximum number of allowed\n * iterations that algorithm repeated,\n * <code><b><i>populationSize</i></b></code> is the size of population of\n * candidate solutions, <code><b><i>crossoverRate</i></b></code> is the\n * probability of crossover operation, <code><b><i>mutationRate\n * </i></b></code> is the probability of mutation operation,\n * <code><b><i>kFolds</i></b></code> is the number of equal sized subsamples\n * that is used in k-fold cross validation,\n * <code><b><i>epsilon</i></b></code> is the epsilon parameter used in the\n * subset size determining scheme, and <code><b><i>mu</i></b></code> is the\n * mu parameter used in the local search operation\n */\n public HGAFS(Object... arguments) {\n super(arguments);\n population = new Population((double) arguments[13], (double) arguments[14]);\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n protected int[] createSelectedFeatureSubset() {\n ArrayList<Integer> featSubset = new ArrayList();\n population.evaluateFitness();\n Individual fittestIndividual = population.getFittestIndividual();\n\n for (int i = 0; i < Population.PROBLEM_DIMENSION; i++) {\n if (fittestIndividual.genes[i]) {\n featSubset.add(i);\n }\n }\n return featSubset.stream().mapToInt(i -> i).toArray();\n }\n\n /**\n * starts the feature selection process by hybrid genetic algorithm for\n * feature selection using local search (HGAFS)\n */\n @Override\n public void evaluateFeatures() {\n Population.fitnessEvaluator.createTempDirectory();\n Population.fitnessEvaluator.setDataInfo(trainSet, nameFeatures, classLabel);\n population.setDataInfo(trainSet);\n population.initialization();\n for (int i = 0; i < NUM_ITERATION; i++) {\n System.out.println(\"\\nIteration \" + i + \":\\n\\n\");\n population.evaluateFitness();\n population.operateSelection();\n population.operateCrossOver();\n population.operateMutation();\n population.operateLocalSearch();\n population.operateGenerationReplacement();\n }\n\n selectedFeatureSubset = createSelectedFeatureSubset();\n numSelectedFeature = selectedFeatureSubset.length;\n\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n Population.fitnessEvaluator.deleteTempDirectory();\n }\n}\n"
},
{
"alpha_fraction": 0.6607547402381897,
"alphanum_fraction": 0.6643396019935608,
"avg_line_length": 42.08943176269531,
"blob_id": "05da79f0e0c5f5794aa27114477924ba5e16b005",
"content_id": "5a14805e4c3f3bb547517ac2fa6317df3d37e265",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5300,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 123,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/PSOBasedMethods/CPSO/CPSO.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.PSOBasedMethods.CPSO;\n\nimport KFST.featureSelection.wrapper.PSOBasedMethods.BasicPSO;\nimport KFST.util.ArraysFunc;\nimport java.util.ArrayList;\n\n/**\n * This java class is used to implement feature selection method based on\n * continuous particle swarm optimization (CPSO) in which the type of Swarm is\n * extended from Swarm class.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.PSOBasedMethods.BasicPSO\n * @see KFST.featureSelection.wrapper.WrapperApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class CPSO extends BasicPSO<Swarm> {\n\n /**\n * initializes the parameters\n *\n * @param arguments array of parameters contains ( <code>path</code>,\n * <code>numFeatures</code>, <code>classifierType</code>,\n * <code>selectedClassifierPan</code>, <code>numIteration</code>\n * <code>populationSize</code>, <code>inertiaWeight</code>,\n * <code>parameter c1</code>, <code>parameter c2</code>,\n * <code>startPosInterval</code>, <code>endPosInterval</code>,\n * <code>minVelocity</code>, <code>maxVelocity</code>, <code>kFolds</code>,\n * <code>theta</code>) in which <code><b><i>path</i></b></code> is the path\n * of the project, <code><b><i>numFeatures</i></b></code> is the number of\n * original features in the dataset,\n * <code><b><i>classifierType</i></b></code> is the classifier type for\n * evaluating the fitness of a solution,\n * <code><b><i>selectedClassifierPan</i></b></code> is the selected\n * classifier panel, <code><b><i>numIteration</i></b></code> is the maximum\n * number of allowed iterations that algorithm repeated,\n * <code><b><i>populationSize</i></b></code> is the size of population of\n * candidate solutions, <code><b><i>inertiaWeight</i></b></code> is the\n * inertia weight in the velocity updating rule, <code><b><i>parameter\n * c1</i></b></code> is the acceleration constant in the velocity updating\n * rule, <code><b><i>parameter c2</i></b></code> is the acceleration\n * constant in the velocity updating rule,\n * <code><b><i>startPosInterval</i></b></code> is the position interval\n * start value, <code><b><i>endPosInterval</i></b></code> is the position\n * interval end value, <code><b><i>minVelocity</i></b></code> is the\n * velocity interval start value, <code><b><i>maxVelocity</i></b></code> is\n * the velocity interval end value, <code><b><i>kFolds</i></b></code> is the\n * number of equal sized subsamples that is used in k-fold cross validation,\n * and <code><b><i>theta</i></b></code> is the threshold used to determine\n * whether a feature is selected or not\n */\n public CPSO(Object... arguments) {\n super(arguments);\n swarm = new Swarm((double) arguments[14]);\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n protected int[] createSelectedFeatureSubset() {\n ArrayList<Integer> featSubset = new ArrayList();\n for (int i = 0; i < Swarm.PROBLEM_DIMENSION; i++) {\n if (swarm.getGBest()[i] > Particle.THETA) {\n featSubset.add(i);\n }\n }\n return featSubset.stream().mapToInt(i -> i).toArray();\n }\n\n /**\n * starts the feature selection process by continuous particle swarm\n * optimization (CPSO) method\n */\n @Override\n public void evaluateFeatures() {\n Swarm.fitnessEvaluator.createTempDirectory();\n Swarm.fitnessEvaluator.setDataInfo(trainSet, nameFeatures, classLabel);\n swarm.initialization();\n for (int i = 0; i < NUM_ITERATION; i++) {\n System.out.println(\"\\nIteration \" + i + \":\\n\\n\");\n swarm.evaluateFitness();\n swarm.updatePersonalBest();\n swarm.updateGlobalBest();\n swarm.updateParticleVelocity();\n swarm.updateParticlePosition();\n }\n\n selectedFeatureSubset = createSelectedFeatureSubset();\n numSelectedFeature = selectedFeatureSubset.length;\n\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n\n Swarm.fitnessEvaluator.deleteTempDirectory();\n }\n}\n"
},
{
"alpha_fraction": 0.6572712659835815,
"alphanum_fraction": 0.6617646813392639,
"avg_line_length": 31.210525512695312,
"blob_id": "c6f0666c0da48b1b0e4ab591c7d53f83791c2b47",
"content_id": "219f8e459a3d590d102a3140a13580bb9362d2e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2448,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 76,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/PSOBasedMethods/HPSO_LS/Particle.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.PSOBasedMethods.HPSO_LS;\n\nimport KFST.featureSelection.wrapper.PSOBasedMethods.BasicParticle;\nimport java.util.ArrayList;\n\n/**\n * This java class is used to represent a particle in hybrid particle swarm\n * optimization method using local search (HPSO-LS) in which the type of\n * position vector is boolean and the type of velocity vector is double.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.PSOBasedMethods.BasicParticle\n */\npublic class Particle extends BasicParticle<Boolean, Double> {\n\n /**\n * initializes the parameters\n *\n * @param dimension the dimension of problem which equals to total number of\n * features in the dataset\n */\n public Particle(int dimension) {\n super(Boolean.class, Double.class, dimension);\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public int numSelectedFeatures() {\n int count = 0;\n for (Boolean x : this.position) {\n if (x) {\n count++;\n }\n }\n return count;\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public int[] selectedFeaturesSubset() {\n ArrayList<Integer> list = new ArrayList<>();\n for (int i = 0; i < this.position.length; i++) {\n if (this.position[i]) {\n list.add(i);\n }\n }\n return list.stream().mapToInt(i -> i).toArray();\n }\n}\n"
},
{
"alpha_fraction": 0.7246963381767273,
"alphanum_fraction": 0.7269737124443054,
"avg_line_length": 33.97344970703125,
"blob_id": "db2ca00628260dc9bd6f5b7b331e7563de7f9342",
"content_id": "681968845a47296c94b9bcba5560bd78526393cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3952,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 113,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/BasicPopulation.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods;\n\nimport KFST.featureSelection.FitnessEvaluator;\nimport KFST.gui.featureSelection.wrapper.GABased.CrossOverType;\nimport KFST.gui.featureSelection.wrapper.GABased.MutationType;\nimport KFST.gui.featureSelection.wrapper.GABased.ReplacementType;\nimport KFST.gui.featureSelection.wrapper.GABased.SelectionType;\nimport java.lang.reflect.Array;\n\n/**\n * The abstract class contains the main methods and fields that are used in all\n * GA-based feature selection methods. This class is used to implement a\n * population of individuals in GA algorithm.\n *\n * @param <IndividualType> the type of individual implemented in GA algorithm\n *\n * @author Sina Tabakhi\n */\npublic abstract class BasicPopulation<IndividualType> {\n\n protected IndividualType[] population;\n public static FitnessEvaluator fitnessEvaluator;\n public static int PROBLEM_DIMENSION;\n protected static int POPULATION_SIZE;\n protected static double CROSS_OVER_RATE;\n protected static double MUTATION_RATE;\n protected static SelectionType SELECTION_TYPE;\n protected static CrossOverType CROSSOVER_TYPE;\n protected static MutationType MUTATION_TYPE;\n protected static ReplacementType REPLACEMENT_TYPE;\n\n /**\n * initializes the parameters\n *\n * @param individual the type of individual implemented in GA algorithm\n */\n public BasicPopulation(Class<IndividualType> individual) {\n population = (IndividualType[]) Array.newInstance(individual, POPULATION_SIZE);\n }\n\n /**\n * This method initializes each individual in the population.\n */\n public abstract void initialization();\n\n /**\n * This method evaluates the fitness of each individual in the population by\n * predefined fitness function.\n */\n public abstract void evaluateFitness();\n\n /**\n * This method selects parents from the individuals of a population\n * according to their fitness that will recombine for next generation.\n */\n public abstract void operateSelection();\n\n /**\n * This method recombines (cross over) the parents to generate new\n * offsprings.\n */\n public abstract void operateCrossOver();\n\n /**\n * This method mutates new offsprings by changing the value of some genes in\n * them.\n */\n public abstract void operateMutation();\n\n /**\n * This method handles populations from one generation to the next\n * generation.\n */\n public abstract void operateGenerationReplacement();\n\n /**\n * This method returns the fittest individual in the population\n *\n * @return the fittest individual in the population\n */\n public abstract IndividualType getFittestIndividual();\n\n /**\n * This method returns an array of fitness values of individuals in a\n * population\n *\n * @return an array of fitness values of individuals\n */\n public abstract double[] getFitness();\n}\n"
},
{
"alpha_fraction": 0.6454046368598938,
"alphanum_fraction": 0.6481481194496155,
"avg_line_length": 41.882354736328125,
"blob_id": "1b0835d2bd164a7a0294100ade659dd1517c9502",
"content_id": "ba51be47306cc472886e90a126a886c074b3d1e3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7290,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 170,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/embedded/TreeBasedMethods/RandomForestMethod.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "///*\n// * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n// * completely in Java, for performing feature selection process in different\n// * areas of research.\n// * For more information about KFST, please visit:\n// * http://kfst.uok.ac.ir/index.html\n// *\n// * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n// * Sanandaj, Iran.\n// *\n// * This program 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// * This program is distributed in the hope that it will be useful,\n// * but WITHOUT ANY WARRANTY; without even the implied warranty of\n// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// * GNU General Public License for more details.\n// *\n// * You should have received a copy of the GNU General Public License\n// * along with this program. If not, see <http://www.gnu.org/licenses/>.\n// */\n//package KFST.featureSelection.embedded.TreeBasedMethods;\n//\n//import KFST.gui.featureSelection.embedded.decisionTreeBased.TreeType;\n//import KFST.util.ArraysFunc;\n//import KFST.util.FileFunc;\n//import java.io.BufferedReader;\n//import java.io.FileReader;\n//import java.util.Arrays;\n//import java.util.logging.Level;\n//import java.util.logging.Logger;\n//import weka.classifiers.trees.RandomForest;\n//import weka.core.Instances;\n//import weka.core.Utils;\n//\n///**\n// * This java class is used to implement the random forest based method for\n// * feature selection.\n// *\n// * @author Sina Tabakhi\n// * @see KFST.featureSelection.embedded.TreeBasedMethods\n// * @see KFST.featureSelection.embedded.EmbeddedApproach\n// * @see KFST.featureSelection.FeatureSelection\n// */\n//public class RandomForestMethod extends TreeBasedMethods {\n//\n// private int randomForestNumFeatures;\n// private int randomForestMaxDepth;\n// private int randomForestNumIterations;\n//\n// /**\n// * initializes the parameters\n// *\n// * @param arguments array of parameter contains (<code>path</code>,\n// * <code>tree type</code>, <code>NumFeatures</code>, <code>MaxDepth</code>,\n// * <code>NumIterations</code>) in which <code><b><i>path</i></b></code> is\n// * the path of the project, <code><b><i>tree type</i></b></code> is the type\n// * of tree, <code><b><i>NumFeatures</i></b></code> is the number of randomly\n// * selected features, <code><b><i>MaxDepth</i></b></code> is the maximum\n// * depth of the tree, <code><b><i>NumIterations</i></b></code> is the number\n// * of iterations to be performed\n// */\n// public RandomForestMethod(Object... arguments) {\n// super(arguments);\n// randomForestNumFeatures = (int) arguments[2];\n// randomForestMaxDepth = (int) arguments[3];\n// randomForestNumIterations = (int) arguments[4];\n// }\n//\n// /**\n// * initializes the parameters\n// *\n// * @param path the path of the project\n// * @param randomForestNumFeatures the number of randomly selected features\n// * @param randomForestMaxDepth the maximum depth of the tree\n// * @param randomForestNumIterations the number of iterations to be performed\n// */\n// public RandomForestMethod(String path, int randomForestNumFeatures, int randomForestMaxDepth, int randomForestNumIterations) {\n// super(path, TreeType.RANDOM_FOREST);\n// this.randomForestNumFeatures = randomForestNumFeatures;\n// this.randomForestMaxDepth = randomForestMaxDepth;\n// this.randomForestNumIterations = randomForestNumIterations;\n// }\n//\n// /**\n// * find the feature subset from the nodes of the created tree (Used for\n// * Random Forest)\n// *\n// * @param tree the generated tree based on the train set\n// */\n// @Override\n// protected void selectedFeatureSubset(String tree) {\n// String[] lines = tree.split(\" \");\n// int[] featureIndices = new int[numFeatures];\n//\n// for (int i = 0; i < featureIndices.length; i++) {\n// featureIndices[i] = Integer.parseInt(lines[i]);\n//// System.out.println(\"\" + featureIndices[i]);\n// }\n//\n// selectedFeatureSubset = Arrays.copyOfRange(featureIndices, 0, numSelectedFeature);\n// ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n//\n//// for (int i = 0; i < numSelectedFeature; i++) {\n//// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n//// }\n// }\n//\n// /**\n// * {@inheritDoc }\n// */\n// @Override\n// protected String buildClassifier(Instances dataTrain) {\n// try {\n// RandomForest decisionTreeRandomForest = new RandomForest();\n// decisionTreeRandomForest.setNumFeatures(randomForestNumFeatures);\n// decisionTreeRandomForest.setMaxDepth(randomForestMaxDepth);\n// decisionTreeRandomForest.setNumIterations(randomForestNumIterations);\n// decisionTreeRandomForest.setComputeAttributeImportance(true);\n// decisionTreeRandomForest.buildClassifier(dataTrain);\n//\n// /**\n// * Creating an array of indices of the features based on descending\n// * order of features' importance\n// */\n// double[] nodeCounts = new double[numFeatures + 1];\n// double[] impurityScores = decisionTreeRandomForest.computeAverageImpurityDecreasePerAttribute(nodeCounts);\n// int[] sortedIndices = Utils.sort(impurityScores);\n// String sortedIndicesToString = \"\";\n// for (int i = sortedIndices.length - 1; i >= 0; i--) {\n// if (sortedIndices[i] != numFeatures) {\n// sortedIndicesToString += String.valueOf(sortedIndices[i]) + \" \";\n// }\n// }\n//\n// return sortedIndicesToString.trim();\n// //return decisionTreeRandomForest.toString();\n// } catch (Exception ex) {\n// Logger.getLogger(RandomForestMethod.class.getName()).log(Level.SEVERE, null, ex);\n// }\n// return \"\";\n// }\n//\n// /**\n// * starts the feature selection process by Random Forest based method\n// */\n// @Override\n// public void evaluateFeatures() {\n// FileFunc.createDirectory(TEMP_PATH);\n// String nameDataCSV = TEMP_PATH + \"dataCSV.csv\";\n// String nameDataARFF = TEMP_PATH + \"dataARFF.arff\";\n//\n// FileFunc.createCSVFile(trainSet, originalFeatureSet(), nameDataCSV, nameFeatures, classLabel);\n// FileFunc.convertCSVtoARFF(nameDataCSV, nameDataARFF, TEMP_PATH, numFeatures, numFeatures, nameFeatures, numClass, classLabel);\n//\n// try {\n// BufferedReader readerTrain = new BufferedReader(new FileReader(nameDataARFF));\n// Instances dataTrain = new Instances(readerTrain);\n// readerTrain.close();\n// dataTrain.setClassIndex(dataTrain.numAttributes() - 1);\n//\n// selectedFeatureSubset(buildClassifier(dataTrain));\n// } catch (Exception ex) {\n// Logger.getLogger(RandomForestMethod.class.getName()).log(Level.SEVERE, null, ex);\n// }\n// FileFunc.deleteDirectoryWithAllFiles(TEMP_PATH);\n// }\n//}\n"
},
{
"alpha_fraction": 0.6710684299468994,
"alphanum_fraction": 0.6779711842536926,
"avg_line_length": 40.650001525878906,
"blob_id": "2b7fd80648e5e5c0e88f5c64a67172959b202e61",
"content_id": "bf2a0761db9db5a10695403b46ecb9a7e654772e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3332,
"license_type": "no_license",
"max_line_length": 135,
"num_lines": 80,
"path": "/PhD_2019_01/src/main/java/InformationTheory/MutualInformation.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage InformationTheory;\n\nimport java.util.Map.Entry;\n\n/**\n *\n * @author renan\n */\npublic class MutualInformation {\n\n// public MutualInformation() {\n// }\n\n /**\n * Calculates the Mutual Information I(X;Y) between two random variables.\n * Uses histograms to estimate the probability distributions, and thus the\n * information. The mutual information is bounded 0 ≤ I(X;Y) ≤\n * min(H(X),H(Y)). It is also symmetric, so I(X;Y) = I(Y;X).\n *\n * @param firstVector Input vector (X). It is discretised to the floor of\n * each value before calculation.\n * @param secondVector Input vector (Y). It is discretised to the floor of\n * each value before calculation.\n * @return The Mutual Information I(X;Y).\n */\n public double calculateMutualInformation(double[] firstVector, double[] secondVector) {\n JointProbabilityState state = new JointProbabilityState(firstVector, secondVector);\n\n double jointValue, firstValue, secondValue;\n\n double mutualInformation = 0.0;\n for (Entry<Pair<Integer, Integer>, Double> e : state.jointProbMap.entrySet()) {\n jointValue = e.getValue();\n firstValue = state.firstProbMap.get(e.getKey().a);\n secondValue = state.secondProbMap.get(e.getKey().b);\n\n if ((jointValue > 0) && (firstValue > 0) && (secondValue > 0)) {\n mutualInformation += jointValue * Math.log((jointValue / firstValue) / secondValue);\n }\n }\n\n mutualInformation /= Math.log(Entropy.LOG_BASE);\n\n return mutualInformation;\n }//calculateMutualInformation(double [], double [])\n\n /**\n * Calculates the conditional Mutual Information I(X;Y|Z) between two random\n * variables, conditioned on a third. Uses histograms to estimate the\n * probability distributions, and thus the information. The conditional\n * mutual information is bounded 0 ≤ I(X;Y) ≤\n * min(H(X|Z),H(Y|Z)). It is also symmetric, so I(X;Y|Z) = I(Y;X|Z).\n *\n * @param firstVector Input vector (X). It is discretised to the floor of\n * each value before calculation.\n * @param secondVector Input vector (Y). It is discretised to the floor of\n * each value before calculation.\n * @param conditionVector Input vector (Z). It is discretised to the floor\n * of each value before calculation.\n * @return The conditional Mutual Information I(X;Y|Z).\n */\n public static double calculateConditionalMutualInformation(double[] firstVector, double[] secondVector, double[] conditionVector) {\n //first create the vector to hold *outputVector\n double[] mergedVector = new double[firstVector.length];\n\n ProbabilityState.mergeArrays(firstVector, conditionVector, mergedVector);\n\n double firstCondEnt = Entropy.calculateConditionalEntropy(secondVector, conditionVector);\n double secondCondEnt = Entropy.calculateConditionalEntropy(secondVector, mergedVector);\n\n double answer = firstCondEnt - secondCondEnt;\n\n return answer;\n }//calculateConditionalMutualInformation(double [], double [], double [])\n}\n"
},
{
"alpha_fraction": 0.5845310091972351,
"alphanum_fraction": 0.5993759632110596,
"avg_line_length": 35.34364318847656,
"blob_id": "1c30ad7046274c947c44ebe917e02ef1dc2cbe12",
"content_id": "c8c7959f2e9f8790393d330ddb0d6fa6072840b5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 10576,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 291,
"path": "/PhD_2019_01/src/main/java/KFST/gui/menu/PreprocessPanel.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.gui.menu;\n\nimport java.awt.Color;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.swing.BorderFactory;\nimport javax.swing.ButtonGroup;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JCheckBox;\nimport javax.swing.JFileChooser;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JRadioButton;\nimport javax.swing.JTextField;\n//import javax.swing.UIManager;\n//import javax.swing.UnsupportedLookAndFeelException;\n\n/**\n * This java class is used to create and show a panel for preprocessing of the\n * datasets.\n *\n * @author Shahin Salavati\n * @author Sina Tabakhi\n */\npublic class PreprocessPanel extends JFrame\n implements ActionListener {\n\n JLabel lbl_about, lbl_inputFile;\n JTextField txt_inputFile;\n JButton btn_selectFile, btn_save, btn_close;\n JPanel panel_about, panel_delimiter;\n JRadioButton rd_tab, rd_semicolon, rd_space, rd_comma;\n ButtonGroup btnGroup;\n JCheckBox ch_convert, ch_transpose;\n\n /**\n * Creates new form PreprocessPanel. This method is called from within the\n * constructor to initialize the form.\n */\n public PreprocessPanel() {\n\n panel_about = new JPanel();\n panel_about.setBounds(10, 30, 465, 60);\n panel_about.setLayout(null);\n panel_about.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), \"About\"));\n lbl_about = new JLabel(\"This screen lets you prepare the dataset in the KFST format.\");\n lbl_about.setBounds(15, 2, 455, 60);\n\n panel_about.add(lbl_about);\n\n /////////////////////// input file section ////////////////////////////\n lbl_inputFile = new JLabel(\"Select input file:\");\n lbl_inputFile.setBounds(30, 110, 110, 22);\n txt_inputFile = new JTextField();\n txt_inputFile.setBounds(120, 110, 200, 21);\n txt_inputFile.setEditable(false);\n txt_inputFile.setBackground(Color.WHITE);\n btn_selectFile = new JButton(\"Open file...\");\n btn_selectFile.setBounds(340, 108, 100, 23);\n btn_selectFile.addActionListener(this);\n\n /////////////////////// Delimiter panel ///////////////////////////////\n panel_delimiter = new JPanel();\n panel_delimiter.setBounds(30, 160, 105, 130);\n panel_delimiter.setLayout(null);\n panel_delimiter.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), \"Delimiter\"));\n\n rd_tab = new JRadioButton(\"Tab\");\n rd_tab.setBounds(10, 25, 85, 22);\n rd_semicolon = new JRadioButton(\"Semicolon\");\n rd_semicolon.setBounds(10, 50, 85, 22);\n rd_space = new JRadioButton(\"Space\");\n rd_space.setBounds(10, 75, 85, 22);\n rd_comma = new JRadioButton(\"Comma\");\n rd_comma.setBounds(10, 100, 85, 22);\n rd_tab.setSelected(true);\n btnGroup = new ButtonGroup();\n btnGroup.add(rd_tab);\n btnGroup.add(rd_semicolon);\n btnGroup.add(rd_space);\n btnGroup.add(rd_comma);\n\n panel_delimiter.add(rd_tab);\n panel_delimiter.add(rd_semicolon);\n panel_delimiter.add(rd_space);\n panel_delimiter.add(rd_comma);\n\n /////////////////////// check box section /////////////////////////////\n ch_convert = new JCheckBox(\"Convert to Comma delimited\");\n ch_convert.setBounds(150, 200, 230, 22);\n\n ch_transpose = new JCheckBox(\"Transpose (rotate) dataset from rows to columns or vice versa\");\n ch_transpose.setBounds(150, 230, 380, 22);\n\n btn_save = new JButton(\"Save file...\");\n btn_save.setBounds(140, 310, 90, 23);\n btn_save.setEnabled(false);\n btn_save.addActionListener(this);\n\n btn_close = new JButton(\"Close\");\n btn_close.setBounds(250, 310, 90, 23);\n btn_close.addActionListener(this);\n\n add(panel_about);\n\n add(lbl_inputFile);\n add(txt_inputFile);\n add(btn_selectFile);\n\n add(panel_delimiter);\n\n add(ch_convert);\n add(ch_transpose);\n add(btn_save);\n add(btn_close);\n\n setLayout(null);\n setSize(490, 380);\n setLocationRelativeTo(null);\n setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n setIconImage(new ImageIcon(getClass().getResource(\"/KFST/gui/icons/small_logo.png\")).getImage());\n setTitle(\"Preprocessing Panel\");\n setResizable(false);\n setVisible(true);\n }\n\n /**\n * The listener method for receiving action events. Invoked when an action\n * occurs.\n *\n * @param e an action event\n */\n @Override\n public void actionPerformed(ActionEvent e) {\n if (e.getSource().equals(btn_selectFile)) {\n btn_selectFileActionPerformed(e);\n } else if (e.getSource().equals(btn_save)) {\n btn_saveActionPerformed(e);\n } else if (e.getSource().equals(btn_close)) {\n btn_closeActionPerformed(e);\n }\n }\n\n /**\n * This method sets an action for the btn_selectFile button.\n *\n * @param e an action event\n */\n private void btn_selectFileActionPerformed(ActionEvent e) {\n JFileChooser jfch = new JFileChooser();\n jfch.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n if (jfch.showOpenDialog(btn_selectFile) == JFileChooser.APPROVE_OPTION) {\n txt_inputFile.setText(jfch.getSelectedFile().getPath());\n btn_save.setEnabled(true);\n }\n }\n\n /**\n * This method sets an action for the btn_save button.\n *\n * @param e an action event\n */\n private void btn_saveActionPerformed(ActionEvent e) {\n char delimiter;\n String oldPath = txt_inputFile.getText();\n String newPath = \"\";\n\n JFileChooser jfch = new JFileChooser();\n jfch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n if (jfch.showSaveDialog(btn_save) == JFileChooser.APPROVE_OPTION) {\n newPath = jfch.getSelectedFile().getAbsolutePath() + \"\\\\NewData.data\";\n }\n\n if (rd_tab.isSelected()) {\n delimiter = '\t';\n } else if (rd_semicolon.isSelected()) {\n delimiter = ';';\n } else if (rd_space.isSelected()) {\n delimiter = ' ';\n } else {\n delimiter = ',';\n }\n\n if (ch_convert.isSelected() && !ch_transpose.isSelected()) {\n try {\n BufferedReader br = new BufferedReader(new FileReader(oldPath));\n PrintWriter pw = new PrintWriter(new FileWriter(newPath, false));\n while (br.ready()) {\n pw.println(br.readLine().replace(delimiter, ','));\n }\n br.close();\n pw.close();\n } catch (IOException ex) {\n Logger.getLogger(PreprocessPanel.class.getName()).log(Level.SEVERE, null, ex);\n }\n } else if (ch_transpose.isSelected()) {\n int numRow = 1;\n int numCol = 0;\n //counts the number of lines in the input file\n try {\n BufferedReader br = new BufferedReader(new FileReader(oldPath));\n numCol = br.readLine().split(Character.toString(delimiter)).length;\n while (br.ready()) {\n br.readLine();\n numRow++;\n }\n br.close();\n } catch (IOException ex) {\n Logger.getLogger(PreprocessPanel.class.getName()).log(Level.SEVERE, null, ex);\n }\n\n //transpose (rotate) dataset from rows to columns or vice versa\n try {\n BufferedReader br = new BufferedReader(new FileReader(oldPath));\n PrintWriter pw = new PrintWriter(new FileWriter(newPath, false));\n String[][] tempArray = new String[numRow][numCol];\n int counter = 0;\n\n while (br.ready()) {\n tempArray[counter++] = br.readLine().split(Character.toString(delimiter));\n }\n br.close();\n\n //if the original data are separated by comma delimiter\n if (ch_convert.isSelected()) {\n delimiter = ',';\n }\n for (int i = 0; i < numCol; i++) {\n for (int j = 0; j < numRow - 1; j++) {\n pw.print(tempArray[j][i] + delimiter);\n }\n pw.println(tempArray[numRow - 1][i]);\n }\n pw.close();\n } catch (IOException ex) {\n Logger.getLogger(PreprocessPanel.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }\n\n /**\n * This method sets an action for the btn_close button.\n *\n * @param e an action event\n */\n private void btn_closeActionPerformed(ActionEvent e) {\n dispose();\n }\n\n// public static void main(String[] arg) {\n// try {\n// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {\n// System.out.println(\"Error setting native LAF: \" + e);\n// }\n//\n// PreprocessPanel processPanel = new PreprocessPanel();\n// }\n}\n"
},
{
"alpha_fraction": 0.483146071434021,
"alphanum_fraction": 0.5280898809432983,
"avg_line_length": 9,
"blob_id": "627344355c15d61d7e838d218968620cee95e205",
"content_id": "089ebea25aab4fa8a855c422efeeac8bb7adc0d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 89,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 9,
"path": "/PhD_2019_01/scripts_for_cluster_executions/script_2.sh",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "#!/bin/bash \n\nfor i in 50\ndo\n\tcd .//DR_50//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\ndone"
},
{
"alpha_fraction": 0.6216216087341309,
"alphanum_fraction": 0.7387387156486511,
"avg_line_length": 21.200000762939453,
"blob_id": "094ce55de0184624d9ffaaa735cdf1fabe624ee9",
"content_id": "53477e59ffe4e3120b53d262daacea29fe403326",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 111,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 5,
"path": "/PhD_2019_01/primeira tentativa/DR_1/50/scripts_for_cluster_executions/script_r050n12tw10k4s.sh",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "#!/bin/bash \n#SBATCH --qos=qos-7d\n#SBATCH --partition=lamho-0\nmodule load jdk8_32\njava -jar r050n12tw10k4s.jar\n"
},
{
"alpha_fraction": 0.6402544975280762,
"alphanum_fraction": 0.6448814272880554,
"avg_line_length": 41.17073059082031,
"blob_id": "50386e8890dfa7fff0a64b1d1feeae2cc53bebdf",
"content_id": "888a97ed4760d382cd9970908adb62e0c68d8928",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1729,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 41,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/filter/FilterApproach.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "package KFST.featureSelection.filter;\n\nimport KFST.featureSelection.*;\nimport KFST.featureSelection.filter.supervised.*;\nimport KFST.featureSelection.filter.unsupervised.*;\n\npublic abstract class FilterApproach extends FeatureSelection {\n\n public FilterApproach(int sizeSelectedFeatureSubset) {\n super();\n this.numSelectedFeature = sizeSelectedFeatureSubset;\n this.selectedFeatureSubset = new int[this.numSelectedFeature];\n }\n\n public static FilterApproach newMethod(FilterType type, boolean isSupervised, Object... arguments) {\n if (type == FilterType.MRMR) {\n return new MRMR(arguments);\n } else if (type == FilterType.RRFS && isSupervised) {\n return new KFST.featureSelection.filter.supervised.RRFS(arguments);\n } else if (type == FilterType.RRFS && !isSupervised) {\n return new KFST.featureSelection.filter.unsupervised.RRFS(arguments);\n } else if (type == FilterType.MUTUAL_CORRELATION) {\n return new MutualCorrelation(arguments);\n } else if (type == FilterType.RSM) {\n return new RSM(arguments);\n } else if (type == FilterType.UFSACO) {\n return new UFSACO(arguments);\n } else if (type == FilterType.RRFSACO_1) {\n return new RRFSACO_1(arguments);\n } else if (type == FilterType.RRFSACO_2) {\n return new RRFSACO_2(arguments);\n } else if (type == FilterType.IRRFSACO_1) {\n return new IRRFSACO_1(arguments);\n } else if (type == FilterType.IRRFSACO_2) {\n return new IRRFSACO_2(arguments);\n } else if (type == FilterType.MGSACO) {\n return new MGSACO(arguments);\n }\n return null;\n }\n}\n"
},
{
"alpha_fraction": 0.5978400111198425,
"alphanum_fraction": 0.6042557954788208,
"avg_line_length": 35.24806213378906,
"blob_id": "e421082d6889762117625e78a94f236f1efefe4f",
"content_id": "6f8d84654f5e2e72d4ad3b69103726d6f604de12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 9352,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 258,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/filter/supervised/LaplacianScore.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.filter.supervised;\n\nimport KFST.util.ArraysFunc;\nimport KFST.util.MathFunc;\nimport java.util.Arrays;\nimport KFST.featureSelection.filter.WeightedFilterApproach;\n\n/**\n * This java class is used to implement the Laplacian score method. Also, it is\n * the supervised version of the Laplacian score.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.filter.WeightedFilterApproach\n * @see KFST.featureSelection.FeatureWeighting\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class LaplacianScore extends WeightedFilterApproach {\n\n private final double CONSTANT_VALUE;\n private final double ERROR_DENOMINATOR = 0.0001;\n\n /**\n * initializes the parameters\n *\n * @param arguments array of parameters contains \n * (<code>sizeSelectedFeatureSubset</code>, <code>constant</code>) in which \n * <code><b><i>sizeSelectedFeatureSubset</i></b></code> is the number of \n * selected features, and <code><b><i>kNNValue</i></b></code> is the \n * k-nearest neighbor value\n */\n public LaplacianScore(Object... arguments) {\n super((int)arguments[0]);\n CONSTANT_VALUE = (double)arguments[1];\n }\n \n /**\n * initializes the parameters\n *\n * @param sizeSelectedFeatureSubset the number of selected features\n * @param constant the constant value used in the similarity measure\n */\n public LaplacianScore(int sizeSelectedFeatureSubset, double constant) {\n super(sizeSelectedFeatureSubset);\n CONSTANT_VALUE = constant;\n }\n\n /**\n * construct nearest neighbor graph (G) of the data space\n * \n * @return the nearest neighbor graph\n */\n private boolean[][] constructNeighborGraph() {\n boolean[][] tempMatrix = new boolean[trainSet.length][trainSet.length];\n\n for (int i = 0; i < trainSet.length; i++) {\n for (int j = 0; j <= i; j++) {\n if (trainSet[i][numFeatures] == trainSet[j][numFeatures]) {\n tempMatrix[i][j] = tempMatrix[j][i] = true;\n } else {\n tempMatrix[i][j] = tempMatrix[j][i] = false;\n }\n }\n }\n return tempMatrix;\n }\n\n /**\n * construct weight matrix(S) which models the local structure of the data space\n *\n * @param neighborGraph the nearest neighbor graph (G)\n * \n * @return the weight matrix\n */\n private double[][] constructWeightMatrix(boolean[][] neighborGraph) {\n double[][] tempMatrix = new double[trainSet.length][trainSet.length];\n\n for (int i = 0; i < trainSet.length; i++) {\n for (int j = 0; j <= i; j++) {\n if (neighborGraph[i][j] == true) {\n // computes euclidean distance value between data i-th and j-th\n double euclideanDistance = 0.0;\n for (int k = 0; k < numFeatures; k++) {\n euclideanDistance += Math.pow(trainSet[i][k] - trainSet[j][k], 2);\n }\n tempMatrix[i][j] = tempMatrix[j][i] = Math.pow(Math.E, -(euclideanDistance / CONSTANT_VALUE));\n } else {\n tempMatrix[i][j] = tempMatrix[j][i] = 0;\n }\n }\n }\n return tempMatrix;\n }\n\n /**\n * construct the diagonal matrix (D) based on the weight matrix\n *\n * @param simMatrix the weight matrix(S)\n * \n * @return the diagonal matrix\n */\n private double[][] constructDiagonalMatrix(double[][] simMatrix) {\n double[][] tempMatrix = new double[trainSet.length][trainSet.length];\n\n for (int i = 0; i < tempMatrix.length; i++) {\n for (int j = 0; j < tempMatrix.length; j++) {\n tempMatrix[i][i] += simMatrix[i][j];\n }\n }\n return tempMatrix;\n }\n\n /**\n * estimates each feature values\n *\n * @param diag the diagonal matrix(D)\n * @param index the index of the feature\n * \n * @return the estimation of the features\n */\n private double[][] estimateFeatureMatrix(double[][] diag, int index) {\n double numeratorValue = 0;\n double denominatorValue = 0;\n double fractionResult;\n double[][] estFeature = new double[trainSet.length][1];\n\n //f(index) * diagonal matrix(D) * identity matrix(1)\n for (int i = 0; i < trainSet.length; i++) {\n numeratorValue += trainSet[i][index] * diag[i][i];\n }\n\n //transpose identity matrix(1) * diagonal matrix(D) * identity matrix(1)\n for (int i = 0; i < diag.length; i++) {\n denominatorValue += diag[i][i];\n }\n if (denominatorValue == 0) {\n fractionResult = numeratorValue / ERROR_DENOMINATOR;\n } else {\n fractionResult = numeratorValue / denominatorValue;\n }\n\n for (int i = 0; i < trainSet.length; i++) {\n estFeature[i][0] = trainSet[i][index] - fractionResult;\n }\n\n return estFeature;\n }\n\n /**\n * checks the values of data corresponding to a given feature\n *\n * @param index the index of the feature\n * \n * @return true if the all values is equal to zero\n */\n private boolean isZeroFeat(int index) {\n for (double[] sample : trainSet) {\n if (sample[index] != 0) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * chaining multiple three matrix\n *\n * @param matrix1 the first matrix\n * @param matrix2 the second matrix\n * @param matrix3 the third matrix\n * \n * @return the result of the chaining multiple\n */\n private double multThreeMatrix(double[][] matrix1, double[][] matrix2, double[][] matrix3) {\n double[][] result = MathFunc.multMatrix(MathFunc.multMatrix(matrix1, matrix2), matrix3);\n return result[0][0];\n }\n\n /**\n * starts the feature selection process by Laplacian score(LS) method\n */\n @Override\n public void evaluateFeatures() {\n boolean[][] nearestNeighborGraph; // nearest neighbor graph\n double[][] weightMatrix; // weight matrix of the data space\n double[][] identityMatrix = new double[trainSet.length][1]; // identity matrix\n double[][] diagonalMatrix; // diagonal matrix\n double[][] graphLaplacian; // graph Laplacian\n featureValues = new double[numFeatures];\n int[] indecesLS;\n\n //constructs an identity matrix\n for (double[] row : identityMatrix) {\n row[0] = 1;\n }\n\n //constructs nearest neighbor graph\n nearestNeighborGraph = constructNeighborGraph();\n\n //constructs weight matrix\n weightMatrix = constructWeightMatrix(nearestNeighborGraph);\n\n //construct diagonal matrix\n diagonalMatrix = constructDiagonalMatrix(weightMatrix);\n\n //computes the graph Laplacian\n graphLaplacian = MathFunc.subMatrix(diagonalMatrix, weightMatrix);\n\n //computs the Laplacian score values for the features\n for (int i = 0; i < numFeatures; i++) {\n if (!isZeroFeat(i)) {\n double[][] estimateFeature = estimateFeatureMatrix(diagonalMatrix, i);\n double numeratorValue = multThreeMatrix(MathFunc.transMatrix(estimateFeature), graphLaplacian, estimateFeature);\n double denominatorValue = multThreeMatrix(MathFunc.transMatrix(estimateFeature), diagonalMatrix, estimateFeature);\n if (denominatorValue == 0) {\n featureValues[i] = numeratorValue / ERROR_DENOMINATOR;\n } else {\n featureValues[i] = numeratorValue / denominatorValue;\n }\n } else {\n featureValues[i] = 1 / ERROR_DENOMINATOR;\n }\n }\n\n indecesLS = ArraysFunc.sortWithIndex(Arrays.copyOf(featureValues, featureValues.length), false);\n// for (int i = 0; i < numFeatures; i++) {\n// System.out.println(i + \") = \" + featureValues[i]);\n// }\n\n selectedFeatureSubset = Arrays.copyOfRange(indecesLS, 0, numSelectedFeature);\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n }\n}\n"
},
{
"alpha_fraction": 0.6742323040962219,
"alphanum_fraction": 0.6772363185882568,
"avg_line_length": 31.21505355834961,
"blob_id": "b3f35cdb61e57a482d6ce844a384e86f0faa062d",
"content_id": "f94bda830f07af4f989b273076f53b5d97e9d175",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2996,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 93,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/BasicIndividual.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods;\n\nimport java.lang.reflect.Array;\n\n/**\n * The abstract class contains the main methods and fields that are used in all\n * GA-based feature selection methods. This class is used to represent a\n * individual in GA algorithm.\n *\n * @param <GeneType> the type of genes of each individual\n *\n * @author Sina Tabakhi\n */\npublic abstract class BasicIndividual<GeneType> {\n\n public GeneType[] genes;\n private double fitness;\n\n /**\n * initializes the parameters\n *\n * @param gene the type of genes of each individual\n * @param dimension the dimension of problem which equals to total number of\n * features in the dataset\n */\n public BasicIndividual(Class<GeneType> gene, Integer dimension) {\n genes = (GeneType[]) Array.newInstance(gene, dimension);\n }\n\n /**\n * This method returns the number of selected features by the individual\n * based on its gene vector.\n *\n * @return number of selected features by the individual\n */\n public abstract int numSelectedFeatures();\n\n /**\n * This method returns the indices of selected features by the individual\n * based on its gene vector.\n *\n * @return the array of indices of the selected features by the individual\n */\n public abstract int[] selectedFeaturesSubset();\n\n /**\n * This method returns the fitness value of the individual.\n *\n * @return the fitness value of the individual\n */\n public double getFitness() {\n return fitness;\n }\n\n /**\n * This method sets the fitness value of the individual.\n *\n * @param fitness the fitness value of the individual\n */\n public void setFitness(double fitness) {\n this.fitness = fitness;\n }\n\n// public void showIndividual() {\n// for (GeneType entry : genes) {\n// System.out.print(entry + \",\");\n// }\n// System.out.println(\" = \" + fitness);\n// }\n}\n"
},
{
"alpha_fraction": 0.673937976360321,
"alphanum_fraction": 0.6789131164550781,
"avg_line_length": 32.93506622314453,
"blob_id": "3377d93abf10466026df5a7a8807e97ee2f4337b",
"content_id": "afb23d5a03c9d27823ff6f28b8989bc3a1483cd9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2613,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 77,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/filter/NonWeightedFilterType.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.filter;\n\nimport java.util.Arrays;\n\n/**\n * This java class is used to define the names of non weighted filter-based\n * feature selection methods.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.filter.FilterType\n */\npublic class NonWeightedFilterType extends FilterType {\n\n /**\n * Creates new NonWeightedFilterType. This method is called from within the\n * constructor to initialize the parameter.\n *\n * @param name the name of non weighted filter method\n */\n private NonWeightedFilterType(String name) {\n super(name);\n }\n\n /**\n * Return the names of filter-based feature selection methods that are not\n * feature weighting\n *\n * @return an array of names of methods\n */\n public static String[] asList() {\n return new String[]{MRMR.toString(),\n RRFS.toString(),\n MUTUAL_CORRELATION.toString(),\n RSM.toString(),\n UFSACO.toString(),\n RRFSACO_1.toString(),\n RRFSACO_2.toString(),\n IRRFSACO_1.toString(),\n IRRFSACO_2.toString(),\n MGSACO.toString()};\n }\n\n /**\n * Check whether the method is filter-based feature weighting method or not\n *\n * @param type the name of feature selection method\n *\n * @return true if method is filter-based method(Methods that are not\n * classified as feature weighting method)\n */\n public static boolean isNonWeightedFilterMethod(String type) {\n return Arrays.asList(NonWeightedFilterType.asList()).contains(type);\n }\n}\n"
},
{
"alpha_fraction": 0.6631321310997009,
"alphanum_fraction": 0.6668025851249695,
"avg_line_length": 30.84415626525879,
"blob_id": "cd10411ea6a8f226e384c652970de191e94b223e",
"content_id": "67eb64678f523350536a6883c2e6a8b0be4d42ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2452,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 77,
"path": "/PhD_2019_01/src/main/java/KFST/gui/menu/selectMode/SelectModeType.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.gui.menu.selectMode;\n\nimport KFST.featureSelection.EnumType;\n\n/**\n * This java class is used to define the names of select mode used in the result\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.EnumType\n */\npublic class SelectModeType extends EnumType {\n\n public static final SelectModeType NONE = new SelectModeType(\"none\");\n public static final SelectModeType AVERAGE = new SelectModeType(\"Average\");\n public static final SelectModeType TOTAL = new SelectModeType(\"Total\");\n\n /**\n * Creates new SelectModeType. This method is called from within the\n * constructor to initialize the parameter.\n *\n * @param name the name of select mode\n */\n private SelectModeType(String name) {\n super(name);\n }\n\n /**\n * Returns the names of select mode\n *\n * @return an array of names of select mode\n */\n public static String[] asList() {\n return new String[]{AVERAGE.toString(),\n TOTAL.toString()};\n }\n\n /**\n * Converts the select mode name to SelectModeType\n *\n * @param type the name of select mode as string\n *\n * @return the select mode type\n */\n public static SelectModeType parse(String type) {\n switch (type) {\n case \"Average\":\n return AVERAGE;\n case \"Total\":\n return TOTAL;\n default:\n return NONE;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6855507493019104,
"alphanum_fraction": 0.6885116696357727,
"avg_line_length": 43.438594818115234,
"blob_id": "bc3b0dcfd769fb238f1c7938f3cebb1af73a8f02",
"content_id": "131c4557a8ca7d1a65ced0581c117f10bb117226",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5066,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 114,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/ACOBasedMethods/OptimalACO/OptimalACO.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.ACOBasedMethods.OptimalACO;\n\nimport KFST.featureSelection.wrapper.ACOBasedMethods.BasicACO;\nimport KFST.featureSelection.wrapper.ACOBasedMethods.BasicColony;\nimport KFST.util.ArraysFunc;\n\n/**\n * This java class is used to implement feature selection method based on\n * optimal ant colony optimization (Optimal ACO) in which the type of Colony is\n * extended from Colony class.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.ACOBasedMethods.BasicACO\n * @see KFST.featureSelection.wrapper.WrapperApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class OptimalACO extends BasicACO<Colony> {\n\n /**\n * Initializes the parameters\n *\n * @param arguments array of parameters contains (<code>path</code>,\n * <code>numFeatures</code>, <code>classifierType</code>,\n * <code>selectedClassifierPan</code>, <code>numIteration</code>,\n * <code>colonySize</code>, <code>alphaParameter</code>,\n * <code>betaParameter</code>, <code>evaporationRate</code>,\n * <code>kFolds</code>, <code>initPheromone</code>,\n * <code>phiParameter</code>) in which <code><b><i>path</i></b></code> is\n * the path of the project, <code><b><i>numFeatures</i></b></code> is the\n * number of original features in the dataset,\n * <code><b><i>classifierType</i></b></code> is the classifier type for\n * evaluating the fitness of a solution,\n * <code><b><i>selectedClassifierPan</i></b></code> is the selected\n * classifier panel, <code><b><i>numIteration</i></b></code> is the maximum\n * number of allowed iterations that algorithm repeated,\n * <code><b><i>colonySize</i></b></code> is the size of colony of candidate\n * solutions, <code><b><i>alphaParameter</i></b></code> is the alpha\n * parameter used in the state transition rule that shows the relative\n * importance of the pheromone, <code><b><i>betaParameter</i></b></code> is\n * the beta parameter used in the state transition rule that shows the\n * relative importance of heuristic information,\n * <code><b><i>evaporationRate</i></b></code> is the evaporation rate of the\n * pheromone, <code><b><i>kFolds</i></b></code> is the number of equal sized\n * subsamples that is used in k-fold cross validation,\n * <code><b><i>initPheromone</i></b></code> is the initial value of the\n * pheromone, and <code><b><i>phiParameter</i></b></code> is the phi\n * parameter used in the pheromone update rule for controlling the relative\n * weight of classifier performance and feature subset length\n */\n public OptimalACO(Object... arguments) {\n super(arguments);\n BasicColony.graphRepresentation = new GraphRepresentation(1, BasicColony.NUM_ORIGINAL_FEATURE);\n colony = new Colony((double) arguments[11]);\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n protected int[] createSelectedFeatureSubset() {\n Ant betsAnt = colony.getBestAnt();\n return ArraysFunc.convertArrayListToInt(betsAnt.getFeatureSubset());\n }\n\n /**\n * starts the feature selection process by optimal ant colony optimization\n * (Optimal ACO) method\n */\n @Override\n public void evaluateFeatures() {\n Colony.fitnessEvaluator.createTempDirectory();\n Colony.fitnessEvaluator.setDataInfo(trainSet, nameFeatures, classLabel);\n colony.initialization();\n for (int i = 0; i < NUM_ITERATION; i++) {\n System.out.println(\"\\nIteration \" + i + \":\\n\\n\");\n colony.setInitialState();\n colony.constructSolution();\n colony.operatePheromoneUpdateRule();\n }\n\n selectedFeatureSubset = createSelectedFeatureSubset();\n numSelectedFeature = selectedFeatureSubset.length;\n\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n Colony.fitnessEvaluator.deleteTempDirectory();\n }\n}\n"
},
{
"alpha_fraction": 0.6170651912689209,
"alphanum_fraction": 0.6404903531074524,
"avg_line_length": 34.20940017700195,
"blob_id": "c090cc9889144ef7910a445c93d990146d4ffa39",
"content_id": "b2db1ebb6d48102a165f47ee65c473c2d76baf6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8239,
"license_type": "no_license",
"max_line_length": 217,
"num_lines": 234,
"path": "/PhD_2019_01/src/main/java/KFST/gui/menu/AboutPanel.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.gui.menu;\n\nimport java.awt.Color;\nimport java.awt.Cursor;\nimport java.awt.Desktop;\n//import java.awt.Dialog;\nimport java.awt.Font;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.MouseListener;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport javax.swing.ImageIcon;\nimport javax.swing.JDialog;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\n//import javax.swing.UIManager;\n//import javax.swing.UnsupportedLookAndFeelException;\n\n/**\n * This java class is used to create and show a panel for description of the\n * tool.\n *\n * @author Sina Tabakhi\n */\npublic class AboutPanel extends JDialog implements MouseListener {\n\n JLabel lbl_logo, lbl_name, lbl_descrip, lbl_ver, lbl_verVal,\n lbl_author, lbl_authorVal, lbl_home, lbl_homVal, lbl_footer_1,\n lbl_footer_2, lbl_footer_3, lbl_nameUni, lbl_License;\n JPanel panel_footer;\n\n /**\n * Creates new form AboutPanel. This method is called from within the\n * constructor to initialize the form.\n */\n public AboutPanel() {\n super();\n lbl_logo = new JLabel(new ImageIcon(getClass().getResource(\"/KFST/gui/icons/logo.png\")));\n lbl_logo.setBounds(1, 1, 240, 240);\n\n lbl_name = new JLabel(new ImageIcon(getClass().getResource(\"/KFST/gui/icons/logo_name.png\")));\n lbl_name.setBounds(240, 10, 270, 90);\n\n lbl_descrip = new JLabel(\"<html>Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed completely in Java, for performing feature selection processes in different areas of research.<html>\");\n lbl_descrip.setBounds(260, 100, 375, 50);\n\n lbl_ver = new JLabel(\"Version:\");\n lbl_ver.setFont(new Font(\"Tahoma\", Font.BOLD, 11));\n lbl_ver.setBounds(260, 160, 70, 15);\n\n lbl_verVal = new JLabel(\"0.2.0\");\n lbl_verVal.setBounds(340, 160, 100, 15);\n\n lbl_author = new JLabel(\"Author:\");\n lbl_author.setFont(new Font(\"Tahoma\", Font.BOLD, 11));\n lbl_author.setBounds(260, 185, 70, 15);\n\n lbl_authorVal = new JLabel(\"<html><a href=\\\"\\\">KFST team</a></html>\");\n lbl_authorVal.setBounds(340, 185, 100, 15);\n lbl_authorVal.setCursor(new Cursor(Cursor.HAND_CURSOR));\n lbl_authorVal.addMouseListener(this);\n\n lbl_home = new JLabel(\"Home Page:\");\n lbl_home.setFont(new Font(\"Tahoma\", Font.BOLD, 11));\n lbl_home.setBounds(260, 210, 70, 15);\n\n lbl_homVal = new JLabel(\"<html><a href=\\\"\\\">http://kfst.uok.ac.ir</a></html>\");\n lbl_homVal.setBounds(340, 210, 100, 15);\n lbl_homVal.setCursor(new Cursor(Cursor.HAND_CURSOR));\n lbl_homVal.addMouseListener(this);\n\n panel_footer = new JPanel();\n panel_footer.setBounds(0, 250, 670, 45);\n panel_footer.setLayout(null);\n panel_footer.setBackground(new Color(225, 225, 225));\n\n lbl_footer_1 = new JLabel(\"KFST is developed at \");\n lbl_footer_1.setBounds(50, 20, 104, 15);\n\n lbl_nameUni = new JLabel(\"<html><a href=\\\"\\\">University of Kurdistan</a></html>\");\n lbl_nameUni.setBounds(154, 20, 109, 15);\n lbl_nameUni.setCursor(new Cursor(Cursor.HAND_CURSOR));\n lbl_nameUni.addMouseListener(this);\n\n lbl_footer_2 = new JLabel(\", Iran, and distributed under the terms of the \");\n lbl_footer_2.setBounds(262, 20, 223, 15);\n\n lbl_License = new JLabel(\"<html><a href=\\\"\\\">GNU General Public License</a></html>\");\n lbl_License.setBounds(483, 20, 129, 15);\n lbl_License.setCursor(new Cursor(Cursor.HAND_CURSOR));\n lbl_License.addMouseListener(this);\n\n lbl_footer_3 = new JLabel(\".\");\n lbl_footer_3.setBounds(612, 20, 5, 15);\n\n panel_footer.add(lbl_footer_1);\n panel_footer.add(lbl_nameUni);\n panel_footer.add(lbl_footer_2);\n panel_footer.add(lbl_License);\n panel_footer.add(lbl_footer_3);\n\n setModalityType(ModalityType.APPLICATION_MODAL);\n setSize(670, 323);\n setLayout(null);\n\n add(lbl_logo);\n add(lbl_name);\n add(lbl_descrip);\n add(lbl_ver);\n add(lbl_verVal);\n add(lbl_author);\n add(lbl_authorVal);\n add(lbl_home);\n add(lbl_homVal);\n add(panel_footer);\n\n setIconImage(new ImageIcon(getClass().getResource(\"/KFST/gui/icons/small_logo.png\")).getImage());\n setDefaultCloseOperation(DISPOSE_ON_CLOSE);\n setLocationRelativeTo(null);\n setResizable(false);\n setTitle(\"About KFST\");\n }\n\n /**\n * opens default browser using the given URL\n *\n * @param url the url of a webpage\n */\n private void openURL(String url) {\n try {\n Desktop.getDesktop().browse(new URI(url));\n } catch (URISyntaxException | IOException ex) {\n Logger.getLogger(AboutPanel.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n /**\n * The listener method for receiving interesting mouse events on a\n * component. Invoked when the mouse button has been clicked on a component.\n *\n * @param e an mouse event\n */\n @Override\n public void mouseClicked(MouseEvent e) {\n if (e.getSource().equals(lbl_authorVal)) {\n openURL(\"http://kfst.uok.ac.ir/people.html\");\n } else if (e.getSource().equals(lbl_homVal)) {\n openURL(\"http://kfst.uok.ac.ir\");\n } else if (e.getSource().equals(lbl_nameUni)) {\n openURL(\"http://international.uok.ac.ir/\");\n } else if (e.getSource().equals(lbl_License)) {\n openURL(\"http://www.gnu.org/licenses/gpl.html\");\n }\n }\n\n /**\n * The listener method for receiving interesting mouse events on a\n * component. Invoked when the mouse button has been pressed on a component.\n *\n * @param e an mouse event\n */\n @Override\n public void mousePressed(MouseEvent e) {\n }\n\n /**\n * The listener method for receiving interesting mouse events on a\n * component. Invoked when the mouse button has been released on a\n * component.\n *\n * @param e an mouse event\n */\n @Override\n public void mouseReleased(MouseEvent e) {\n }\n\n /**\n * The listener method for receiving interesting mouse events on a\n * component. Invoked when the mouse enters a component.\n *\n * @param e an mouse event\n */\n @Override\n public void mouseEntered(MouseEvent e) {\n }\n\n /**\n * The listener method for receiving interesting mouse events on a\n * component. Invoked when the mouse exits a component.\n *\n * @param e an mouse event\n */\n @Override\n public void mouseExited(MouseEvent e) {\n }\n\n// public static void main(String[] args) {\n// try {\n// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {\n// System.out.println(\"Error setting native LAF: \" + e);\n// }\n//\n// AboutPanel mop = new AboutPanel();\n// Dialog dlg = new Dialog(mop);\n// mop.setVisible(true);\n// }\n}\n"
},
{
"alpha_fraction": 0.6075106859207153,
"alphanum_fraction": 0.614165723323822,
"avg_line_length": 35.47977066040039,
"blob_id": "51da2fa452e509d29ee1eb33385cf5c9a62a2468",
"content_id": "e8835935d2c94e96b640fce2570dc2c66b281b1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 6311,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 173,
"path": "/PhD_2019_01/src/main/java/KFST/result/performanceMeasure/PerformanceMeasures.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.result.performanceMeasure;\n\nimport KFST.util.MathFunc;\n\n/**\n * This java class is used to save all performance measure values obtained from\n * different runs of given feature selection method.\n *\n * @author Sina Tabakhi\n * @see KFST.result.performanceMeasure.Criteria\n */\npublic class PerformanceMeasures {\n\n private Criteria[][] measures;\n private Criteria[] averageValues;\n\n /**\n * initializes the parameters\n *\n * @param numRuns numbers of runs of the feature selection method\n * @param numSelectedSubsets numbers of selected feature subsets\n */\n public PerformanceMeasures(int numRuns, int numSelectedSubsets) {\n measures = new Criteria[numRuns][numSelectedSubsets];\n for (int i = 0; i < measures.length; i++) {\n for (int j = 0; j < measures[i].length; j++) {\n measures[i][j] = new Criteria();\n }\n }\n\n averageValues = new Criteria[numSelectedSubsets];\n for (int i = 0; i < averageValues.length; i++) {\n averageValues[i] = new Criteria();\n }\n }\n\n /**\n * Sets the obtained criteria values from feature selection method\n *\n * @param i the current run of the feature selection method\n * @param j the current subset of the selected features\n * @param criteria values obtained from the feature selection method\n */\n public void setCriteria(int i, int j, Criteria criteria) {\n measures[i][j] = criteria;\n }\n\n /**\n * Computes the average values of all criteria over number of runs\n */\n public void computeAverageValues() {\n for (int j = 0; j < measures[0].length; j++) {\n for (int i = 0; i < measures.length; i++) {\n averageValues[j].setAccuracy(averageValues[j].getAccuracy() + measures[i][j].getAccuracy());\n averageValues[j].setErrorRate(averageValues[j].getErrorRate() + measures[i][j].getErrorRate());\n averageValues[j].setTime(averageValues[j].getTime() + measures[i][j].getTime());\n }\n averageValues[j].setAccuracy(Double.parseDouble(MathFunc.roundDouble(averageValues[j].getAccuracy() / measures.length, 3)));\n averageValues[j].setErrorRate(Double.parseDouble(MathFunc.roundDouble(averageValues[j].getErrorRate() / measures.length, 3)));\n averageValues[j].setTime(Double.parseDouble(MathFunc.roundDouble(averageValues[j].getTime() / measures.length, 3)));\n }\n }\n\n /**\n * Returns the accuracy values of the feature selection method\n *\n * @return an array of the accuracy values\n */\n public double[][] getAccuracyValues() {\n double[][] array = new double[measures.length][measures[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n array[i][j] = measures[i][j].getAccuracy();\n }\n }\n return array;\n }\n\n /**\n * Returns the error rate values of the feature selection method\n *\n * @return an array of the error rate values\n */\n public double[][] getErrorRateValues() {\n double[][] array = new double[measures.length][measures[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n array[i][j] = measures[i][j].getErrorRate();\n }\n }\n return array;\n }\n\n /**\n * Returns the execution time values of the feature selection method\n *\n * @return an array of the execution time values\n */\n public double[][] getTimeValues() {\n double[][] array = new double[measures.length][measures[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n array[i][j] = measures[i][j].getTime();\n }\n }\n return array;\n }\n\n /**\n * Returns the average values of the accuracy of the feature selection\n * method over number of runs\n *\n * @return an array of the average values of the accuracy\n */\n public double[][] getAverageAccuracyValues() {\n double[][] array = new double[1][averageValues.length];\n for (int j = 0; j < array[0].length; j++) {\n array[0][j] = averageValues[j].getAccuracy();\n }\n return array;\n }\n\n /**\n * Returns the average values of the error rate of the feature selection\n * method over number of runs\n *\n * @return an array of the average values of the error rate\n */\n public double[][] getAverageErrorRateValues() {\n double[][] array = new double[1][averageValues.length];\n for (int j = 0; j < array[0].length; j++) {\n array[0][j] = averageValues[j].getErrorRate();\n }\n return array;\n }\n\n /**\n * Returns the average values of the execution time of the feature selection\n * method over number of runs\n *\n * @return an array of the average values of the execution time\n */\n public double[][] getAverageTimeValues() {\n double[][] array = new double[1][averageValues.length];\n for (int j = 0; j < array[0].length; j++) {\n array[0][j] = averageValues[j].getTime();\n }\n return array;\n }\n}\n"
},
{
"alpha_fraction": 0.694187343120575,
"alphanum_fraction": 0.6988152265548706,
"avg_line_length": 45.568965911865234,
"blob_id": "353fd8d61e0cdec44fab14993e685deb0b8e9a2b",
"content_id": "55f80bfd8ce32fa4e93c38ba02f849bd1b5be8eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5402,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 116,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/BasicGA.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods;\n\nimport KFST.classifier.ClassifierType;\nimport KFST.featureSelection.FitnessEvaluator;\nimport KFST.featureSelection.wrapper.WrapperApproach;\nimport KFST.gui.featureSelection.wrapper.GABased.CrossOverType;\nimport KFST.gui.featureSelection.wrapper.GABased.MutationType;\nimport KFST.gui.featureSelection.wrapper.GABased.ReplacementType;\nimport KFST.gui.featureSelection.wrapper.GABased.SelectionType;\n\n/**\n * The abstract class contains the main methods and fields that are used in all\n * GA-based feature selection methods.\n *\n * @param <PopulationType> the type of population implemented in GA algorithm\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.WrapperApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic abstract class BasicGA<PopulationType> extends WrapperApproach {\n\n protected PopulationType population;\n protected final int NUM_ITERATION;\n protected final int K_FOLDS;\n\n /**\n * Initializes the parameters\n *\n * @param arguments array of parameters contains ( <code>path</code>,\n * <code>numFeatures</code>, <code>classifierType</code>,\n * <code>selectedClassifierPan</code>, <code>selectionType</code>,\n * <code>crossoverType</code>, <code>mutationType</code>,\n * <code>replacementType</code>, <code>numIteration</code>\n * <code>populationSize</code>, <code>crossoverRate</code>,\n * <code>mutationRate</code>, <code>kFolds</code>) in which\n * <code><b><i>path</i></b></code> is the path of the project,\n * <code><b><i>numFeatures</i></b></code> is the number of original features\n * in the dataset, <code><b><i>classifierType</i></b></code> is the\n * classifier type for evaluating the fitness of a solution,\n * <code><b><i>selectedClassifierPan</i></b></code> is the selected\n * classifier panel, <code><b><i>selectionType</i></b></code> is used for\n * selecting parents from the individuals of a population according to their\n * fitness, <code><b><i>crossoverType</i></b></code> is used for recombining\n * the parents to generate new offsprings based on crossover rate,\n * <code><b><i>mutationType</i></b></code> is used for mutating new\n * offsprings by changing the value of some genes in them based on mutation\n * rate, <code><b><i>replacementType</i></b></code> is used for handling\n * populations from one generation to the next generation,\n * <code><b><i>numIteration</i></b></code> is the maximum number of allowed\n * iterations that algorithm repeated,\n * <code><b><i>populationSize</i></b></code> is the size of population of\n * candidate solutions, <code><b><i>crossoverRate</i></b></code> is the\n * probability of crossover operation, <code><b><i>mutationRate\n * </i></b></code> is the probability of mutation operation, and\n * <code><b><i>kFolds</i></b></code> is the number of equal sized subsamples\n * that is used in k-fold cross validation\n */\n public BasicGA(Object... arguments) {\n super((String) arguments[0]);\n BasicPopulation.PROBLEM_DIMENSION = (int) arguments[1];\n BasicPopulation.SELECTION_TYPE = (SelectionType) arguments[4];\n BasicPopulation.CROSSOVER_TYPE = (CrossOverType) arguments[5];\n BasicPopulation.MUTATION_TYPE = (MutationType) arguments[6];\n BasicPopulation.REPLACEMENT_TYPE = (ReplacementType) arguments[7];\n this.NUM_ITERATION = (int) arguments[8];\n BasicPopulation.POPULATION_SIZE = (int) arguments[9];\n BasicPopulation.CROSS_OVER_RATE = (double) arguments[10];\n BasicPopulation.MUTATION_RATE = (double) arguments[11];\n this.K_FOLDS = (int) arguments[12];\n BasicPopulation.fitnessEvaluator = new FitnessEvaluator(TEMP_PATH, (ClassifierType) arguments[2],\n arguments[3], this.K_FOLDS);\n }\n\n /**\n * This method creates the selected feature subset based on the fittest\n * individual in the population.\n *\n * @return the array of indices of the selected feature subset\n */\n protected abstract int[] createSelectedFeatureSubset();\n\n /**\n * {@inheritDoc }\n */\n @Override\n public String validate() {\n if (K_FOLDS > trainSet.length) {\n return \"The parameter values of GA-based method (number of folds) are incorred.\";\n }\n return \"\";\n }\n}\n"
},
{
"alpha_fraction": 0.6444665193557739,
"alphanum_fraction": 0.6471173167228699,
"avg_line_length": 40.22950744628906,
"blob_id": "2d99d0b449f429e8d65e148c8050cc21b9430bdb",
"content_id": "0bfedc0865a7d0be067600f98fa3c755dd4cb64f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 15090,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 366,
"path": "/PhD_2019_01/src/main/java/KFST/result/Results.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.result;\n\nimport KFST.classifier.ClassifierType;\nimport KFST.classifier.evaluation.wekaClassifier.TrainTestEvaluation;\nimport KFST.dataset.DatasetInfo;\nimport KFST.gui.classifier.DTClassifierPanel;\nimport KFST.gui.classifier.KNNClassifierPanel;\nimport KFST.gui.classifier.svmClassifier.SVMClassifierPanel;\nimport KFST.result.performanceMeasure.Criteria;\nimport KFST.result.performanceMeasure.PerformanceMeasures;\nimport KFST.util.FileFunc;\nimport KFST.util.MathFunc;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\n/**\n * This java class is used to implement various methods for showing the results\n * in the result panel.\n *\n * @author Sina Tabakhi\n */\npublic class Results {\n\n DatasetInfo data;\n private String PATH_PROJECT;\n private String PATH_DATA_CSV;\n private String PATH_DATA_ARFF;\n private int numRuns;\n private int numSelectedSubsets;\n private String[][] selectedFeatureSubsets;\n private String featureSelectionMethodName;\n private double currentExecutionTime;\n private int[] currentSelectedSubset;\n private double[] currentFeatureValues;\n private Object selectedEvaluationClassifierPanel;\n private ClassifierType classifierType = ClassifierType.NONE;\n private PerformanceMeasures performanceMeasures;\n\n /**\n * initializes the parameters\n *\n * @param data the data class contains all information of the input dataset\n * @param numRuns numbers of runs of the feature selection method\n * @param numSelectedSubsets numbers of selected feature subsets\n * @param projectPath the path of the project\n * @param methodName the name of given feature selection method\n * @param classifierName the name of given classifier\n * @param selectedEvaluationClassifierPanel panel of the selected classifier\n * contained the parameter values\n */\n public Results(DatasetInfo data, int numRuns, int numSelectedSubsets, String projectPath,\n Object methodName, Object classifierName, Object selectedEvaluationClassifierPanel) {\n this.data = data;\n this.numRuns = numRuns;\n this.numSelectedSubsets = numSelectedSubsets;\n this.PATH_PROJECT = projectPath;\n PATH_DATA_CSV = PATH_PROJECT + \"CSV\\\\\";\n PATH_DATA_ARFF = PATH_PROJECT + \"ARFF\\\\\";\n featureSelectionMethodName = methodName.toString();\n this.selectedEvaluationClassifierPanel = selectedEvaluationClassifierPanel;\n this.classifierType = ClassifierType.parse(classifierName.toString());\n\n selectedFeatureSubsets = new String[this.numRuns][this.numSelectedSubsets];\n performanceMeasures = new PerformanceMeasures(this.numRuns, this.numSelectedSubsets);\n }\n\n /**\n * This method returns an empty string\n *\n * @return an empty string\n */\n @Override\n public String toString() {\n return toString(ResultType.NONE);\n }\n\n /**\n * This method converts the obtained results over all runs to the string\n * based on result type for showing in the result panel.\n *\n * @param type type of the result\n *\n * @return a string of the result\n */\n public String toString(ResultType type) {\n if (type == ResultType.DATASET_INFORMATION) {\n return addTextToPanel();\n } else if (type == ResultType.SELECTED_FEATURE_SUBSET) {\n return addTextToPanel(currentSelectedSubset);\n } else if (type == ResultType.FEATURE_VALUES) {\n return addTextToPanel(currentFeatureValues, featureSelectionMethodName);\n } else if (type == ResultType.PERFORMANCE_MEASURES) {\n return addTextToPanel(selectedFeatureSubsets, \"Subsets of selected features in each iteration\")\n + addTextToPanel(performanceMeasures.getAccuracyValues(), \"Classification accuracies\")\n + addTextToPanel(performanceMeasures.getAverageAccuracyValues(), \"Average classification accuracies\", true)\n + addTextToPanel(performanceMeasures.getTimeValues(), \"Execution times\")\n + addTextToPanel(performanceMeasures.getAverageTimeValues(), \"Average execution times\", true);\n }\n return \"\";\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about some information of the dataset.\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n * @see KFST.dataset.DatasetInfo\n */\n private String addTextToPanel() {\n String messages = \"General infomation:\\n\";\n messages += \" Path of the workspace: \" + PATH_PROJECT + \"\\n\";\n messages += \" Number of samples in the training set: \" + data.getNumTrainSet() + \"\\n\";\n messages += \" Number of samples in the test set: \" + data.getNumTestSet() + \"\\n\";\n messages += \" Number of features: \" + data.getNumFeature() + \"\\n\";\n messages += \" Number of classes: \" + data.getNumClass() + \"\\n\";\n messages += \" Name of classes {\";\n for (int i = 0; i < data.getNumClass() - 1; i++) {\n messages += data.getClassLabel()[i] + \", \";\n }\n messages += data.getClassLabel()[data.getNumClass() - 1] + \"}\\n\\n\";\n messages += \"Start feature selection process:\\n\";\n return messages;\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about the subset of selected features.\n *\n * @param array an array of text to insert\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n */\n private String addTextToPanel(int[] array) {\n String messages = \"\\n subset selected {\";\n for (int k = 0; k < array.length - 1; k++) {\n messages += String.valueOf(array[k] + 1) + \", \";\n }\n messages += String.valueOf(array[array.length - 1] + 1) + \"}\\n\\n\";\n return messages;\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about the relevance values of features computed by given\n * feature selection method.\n *\n * @param array an array of text to insert\n * @param nameMethod the name of feature selection method\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n */\n private String addTextToPanel(double[] array, String nameMethod) {\n String messages = \"\";\n for (int k = 0; k < array.length; k++) {\n messages += \" \" + nameMethod + \"(\" + data.getNameFeatures()[k] + \") = \" + MathFunc.roundDouble(array[k], 4) + \"\\n\";\n }\n return messages;\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about the final subsets of selected features.\n *\n * @param array an array of text to insert\n * @param title the name of results\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n */\n private String addTextToPanel(String[][] array, String title) {\n String messages = \"\\n\\n\" + title + \":\\n\";\n for (int i = 0; i < array.length; i++) {\n messages += \" Iteration (\" + String.valueOf(i + 1) + \"):\\n\";\n for (int j = 0; j < array[0].length; j++) {\n messages += \" \" + String.valueOf(array[i][j]) + \"\\n\";\n }\n messages += \"\\n\";\n }\n return messages;\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about the classification accuracy and execution time in each\n * iteration.\n *\n * @param array an array of text to insert\n * @param title the name of results\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n */\n private String addTextToPanel(double[][] array, String title) {\n String messages = \"\\n\\n\" + title + \":\\n\";\n for (int i = 0; i < array.length; i++) {\n messages += \" Iteration (\" + String.valueOf(i + 1) + \"):\";\n for (int j = 0; j < array[0].length; j++) {\n messages += \" \" + MathFunc.roundDouble(array[i][j], 3);\n }\n messages += \"\\n\";\n }\n return messages;\n }\n\n /**\n * creates the given text for showing in the results panel.<br>\n * The text is about the average classification accuracies and average\n * execution times in all iteration.\n *\n * @param array an array of text to insert\n * @param title the name of results\n * @param isAverage shows that the average values must be displayed\n *\n * @return the created message as a string\n *\n * @see KFST.gui.ResultPanel\n */\n private String addTextToPanel(double[][] array, String title, boolean isAverage) {\n String messages = \"\\n\\n\" + title + \":\\n\";\n messages += \" All Iterations: \";\n for (int j = 0; j < array[0].length; j++) {\n messages += MathFunc.roundDouble(array[0][j], 3) + \" \";\n }\n messages += \"\\n\";\n return messages;\n }\n\n /**\n * This method creates a text file of the subsets of selected features\n */\n public void createFeatureFiles() {\n PrintWriter pw = null;\n try {\n pw = new PrintWriter(new FileWriter(PATH_PROJECT + \"FeatureSubsetsFile.txt\"));\n pw.println(\"Subsets of selected features in each iteration:\\n\");\n for (int i = 0; i < selectedFeatureSubsets.length; i++) {\n pw.println(\" Iteration (\" + (i + 1) + \"):\");\n for (int j = 0; j < selectedFeatureSubsets[0].length; j++) {\n pw.println(\" \" + selectedFeatureSubsets[i][j]);\n }\n pw.println();\n }\n pw.close();\n } catch (IOException ex) {\n Logger.getLogger(Results.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n\n /**\n * Sets the execution time of the feature selection method in the current\n * run.\n *\n * @param value execution time of the feature selection method\n */\n public void setTime(double value) {\n currentExecutionTime = value;\n }\n\n /**\n * Sets the subset of selected features in the current run\n *\n * @param i the current run of the feature selection method\n * @param j the current subset of the selected features\n * @param currentSelectedSubset an array of the indices of the selected\n * features\n */\n public void setCurrentSelectedSubset(int i, int j, int[] currentSelectedSubset) {\n this.currentSelectedSubset = currentSelectedSubset;\n selectedFeatureSubsets[i][j] = data.createFeatNames(this.currentSelectedSubset);\n }\n\n /**\n * Sets the values of each feature in the current run over given subset of\n * selected features\n *\n * @param currentFeatureValues an array of the values of each feature\n */\n public void setCurrentFeatureValues(double[] currentFeatureValues) {\n this.currentFeatureValues = currentFeatureValues;\n }\n\n /**\n * Computes the performance measures based on given classifier\n *\n * @param i the current run of the feature selection method\n * @param j the current subset of the selected features\n */\n public void computePerformanceMeasures(int i, int j) {\n Criteria critria = new Criteria();\n String nameTrainDataCSV = PATH_DATA_CSV + \"trainSet[\" + (i + 1) + \"-\" + currentSelectedSubset.length + \"].csv\";\n String nameTrainDataARFF = PATH_DATA_ARFF + \"trainSet[\" + (i + 1) + \"-\" + currentSelectedSubset.length + \"].arff\";\n String nameTestDataCSV = PATH_DATA_CSV + \"testSet[\" + (i + 1) + \"-\" + currentSelectedSubset.length + \"].csv\";\n String nameTestDataARFF = PATH_DATA_ARFF + \"testSet[\" + (i + 1) + \"-\" + currentSelectedSubset.length + \"].arff\";\n\n FileFunc.createCSVFile(data.getTrainSet(), currentSelectedSubset, nameTrainDataCSV, data.getNameFeatures(), data.getClassLabel());\n FileFunc.createCSVFile(data.getTestSet(), currentSelectedSubset, nameTestDataCSV, data.getNameFeatures(), data.getClassLabel());\n FileFunc.convertCSVtoARFF(nameTrainDataCSV, nameTrainDataARFF, PATH_PROJECT, currentSelectedSubset.length, data);\n FileFunc.convertCSVtoARFF(nameTestDataCSV, nameTestDataARFF, PATH_PROJECT, currentSelectedSubset.length, data);\n\n if (classifierType == ClassifierType.SVM) {\n SVMClassifierPanel svmPanel = (SVMClassifierPanel) selectedEvaluationClassifierPanel;\n critria = TrainTestEvaluation.SVM(nameTrainDataARFF, nameTestDataARFF, svmPanel.getKernel(), svmPanel.getParameterC());\n } else if (classifierType == ClassifierType.NB) {\n critria = TrainTestEvaluation.naiveBayes(nameTrainDataARFF, nameTestDataARFF);\n } else if (classifierType == ClassifierType.DT) {\n DTClassifierPanel dtPanel = (DTClassifierPanel) selectedEvaluationClassifierPanel;\n critria = TrainTestEvaluation.dTree(nameTrainDataARFF, nameTestDataARFF, dtPanel.getConfidence(), dtPanel.getMinNum());\n } else if (classifierType == ClassifierType.KNN) {\n KNNClassifierPanel dtPanel = (KNNClassifierPanel) selectedEvaluationClassifierPanel;\n critria = TrainTestEvaluation.kNN(nameTrainDataARFF, nameTestDataARFF, dtPanel.getKNNValue());\n }\n\n critria.setTime(currentExecutionTime);\n performanceMeasures.setCriteria(i, j, critria);\n }\n\n /**\n * Computes the average values of all criteria over number of runs\n */\n public void computeAverageValuesOfPerformanceMeasures() {\n performanceMeasures.computeAverageValues();\n }\n\n /**\n * Returns the performance measures of the obtained result\n *\n * @return measures of the PerformanceMeasures class\n */\n public PerformanceMeasures getPerformanceMeasures() {\n return performanceMeasures;\n }\n}\n"
},
{
"alpha_fraction": 0.605097770690918,
"alphanum_fraction": 0.625,
"avg_line_length": 33.64516067504883,
"blob_id": "7622b8c4cd2478a69aa0ed730599e6d9a1c40155",
"content_id": "051ec8965c2ba7e0267bc3cac9ef73726e6748bf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8592,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 248,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/CrossoverOperator.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods;\n\nimport java.util.Random;\n\n/**\n * This java class is used to implement various crossover operators for\n * recombining the two parents to generate new offsprings\n * <p>\n * The methods in this class is contained brief description of the applications.\n *\n * @author Sina Tabakhi\n */\npublic class CrossoverOperator {\n\n /**\n * changes the values of the two elements in the two arrays identified by\n * index1 and index2\n *\n * @param <GeneType> the type of elements in the input arrays\n * @param parent1 the first input array\n * @param index1 the index of element in the parent1 array that should be\n * changed\n * @param parent2 the second input array\n * @param index2 the index of element in the parent2 array that should be\n * changed\n */\n public static <GeneType> void swap(GeneType[] parent1, int index1, GeneType[] parent2, int index2) {\n GeneType temp = parent1[index1];\n parent1[index1] = parent2[index2];\n parent2[index2] = temp;\n }\n\n /**\n * changes the values of the two elements in the two arrays identified by\n * index1 and index2\n *\n * @param parent1 the first input array\n * @param index1 the index of element in the parent1 array that should be\n * changed\n * @param parent2 the second input array\n * @param index2 the index of element in the parent2 array that should be\n * changed\n */\n public static void swap(boolean[] parent1, int index1, boolean[] parent2, int index2) {\n boolean temp = parent1[index1];\n parent1[index1] = parent2[index2];\n parent2[index2] = temp;\n }\n\n /**\n * changes the values of the two elements in the two arrays identified by\n * index1 and index2\n *\n * @param parent1 the first input array\n * @param index1 the index of element in the parent1 array that should be\n * changed\n * @param parent2 the second input array\n * @param index2 the index of element in the parent2 array that should be\n * changed\n */\n public static void swap(double[] parent1, int index1, double[] parent2, int index2) {\n double temp = parent1[index1];\n parent1[index1] = parent2[index2];\n parent2[index2] = temp;\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * one-point crossover\n *\n * @param <GeneType> the type of elements in the input arrays\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static <GeneType> void onePointCrossover(GeneType[] parent1, GeneType[] parent2) {\n int point = (new Random()).nextInt(parent1.length);\n for (int gene = point; gene < parent1.length; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * one-point crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static void onePointCrossover(boolean[] parent1, boolean[] parent2) {\n int point = (new Random()).nextInt(parent1.length);\n for (int gene = point; gene < parent1.length; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * one-point crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static void onePointCrossover(double[] parent1, double[] parent2) {\n int point = (new Random()).nextInt(parent1.length);\n for (int gene = point; gene < parent1.length; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * two-point crossover\n *\n * @param <GeneType> the type of elements in the input arrays\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static <GeneType> void twoPointCrossover(GeneType[] parent1, GeneType[] parent2) {\n int point1 = (new Random()).nextInt(parent1.length);\n int point2 = (new Random()).nextInt(parent1.length);\n\n if (point2 < point1) {\n int temp = point1;\n point1 = point2;\n point2 = temp;\n }\n\n for (int gene = point1; gene < point2; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * two-point crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static void twoPointCrossover(boolean[] parent1, boolean[] parent2) {\n int point1 = (new Random()).nextInt(parent1.length);\n int point2 = (new Random()).nextInt(parent1.length);\n\n if (point2 < point1) {\n int temp = point1;\n point1 = point2;\n point2 = temp;\n }\n\n for (int gene = point1; gene < point2; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * two-point crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n */\n public static void twoPointCrossover(double[] parent1, double[] parent2) {\n int point1 = (new Random()).nextInt(parent1.length);\n int point2 = (new Random()).nextInt(parent1.length);\n\n if (point2 < point1) {\n int temp = point1;\n point1 = point2;\n point2 = temp;\n }\n\n for (int gene = point1; gene < point2; gene++) {\n swap(parent1, gene, parent2, gene);\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * uniform crossover\n *\n * @param <GeneType> the type of elements in the input arrays\n * @param parent1 the first parent\n * @param parent2 the second parent\n * @param prob the probability of crossover operation\n */\n public static <GeneType> void uniformCrossover(GeneType[] parent1, GeneType[] parent2, double prob) {\n for (int gene = 0; gene < parent1.length; gene++) {\n if (Math.random() <= prob) {\n swap(parent1, gene, parent2, gene);\n }\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * uniform crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n * @param prob the probability of crossover operation\n */\n public static void uniformCrossover(boolean[] parent1, boolean[] parent2, double prob) {\n for (int gene = 0; gene < parent1.length; gene++) {\n if (Math.random() <= prob) {\n swap(parent1, gene, parent2, gene);\n }\n }\n }\n\n /**\n * recombines (cross over) the two parents to generate new offsprings using\n * uniform crossover\n *\n * @param parent1 the first parent\n * @param parent2 the second parent\n * @param prob the probability of crossover operation\n */\n public static void uniformCrossover(double[] parent1, double[] parent2, double prob) {\n for (int gene = 0; gene < parent1.length; gene++) {\n if (Math.random() <= prob) {\n swap(parent1, gene, parent2, gene);\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.5427725315093994,
"alphanum_fraction": 0.5807194709777832,
"avg_line_length": 36.52674865722656,
"blob_id": "163e15e37f02be56290798670c4b5b37da95eb20",
"content_id": "bd1c08c5b61928a38e17f170edfe376f2537843f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9122,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 243,
"path": "/PhD_2019_01/methods_updated.py",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "import os\nimport methods as mt\nimport numpy as np\nimport pandas as pd\nimport matplotlib. pyplot as plt\nfrom pygmo import *\n\nlst = [0.1, 10.0, 12.0, 600.0, 50.0, 12.0, 1.0, 6000.0]\nlambdas = np.array([float(i) for i in lst])\n\ndef plot_hypervolume_convergence(file_path, folder, file, dimension, reference_point=None, plot=True):\n number_of_executions = 10\n file_path = file_path\n hv_df = pd.DataFrame()\n\n for i in range(number_of_executions):\n file_name = file + str(i) + '.txt'\n\n f = open(os.path.join(file_path, folder, file_name),'r',encoding='utf-8')\n print(os.path.join(file_path, folder, file_name))\n data = f.readlines()\n splitted_data = ' '.join([i for i in data]).split('#\\n')\n splitted_data = [i for i in splitted_data if len(i) > 1]\n\n hv_pareto = []\n indexes = []\n for k in range(len(splitted_data)):\n converted = [i.strip().split(',') for i in splitted_data[k].split('\\n') if len(i) > 1]\n pop = [[float(j) for j in i] for i in converted]\n hv = hypervolume(pop)\n if reference_point is None:\n hv_pareto.append(hv.compute([200000,150000,150000,150000,150000,150000,150000,1]))\n else:\n hv_pareto.append(hv.compute(reference_point))\n indexes.append(100*k)\n df = pd.DataFrame(data=[indexes, hv_pareto]).T\n columns_string = 'Evaluation HV'+str(i)\n df.columns = columns_string.split()\n hv_df = pd.concat([hv_df, df[columns_string.split()[1]]], axis=1, sort=False)\n if plot:\n \thv_df.T.mean().plot(x='Evaluation', y='HV',figsize=(10,8))\n return hv_df.T.mean(), hv_df\n\ndef plot_hypervolume_convergence_reduced(file_path, folder, file, dimension, reference_point=None, plot=True):\n number_of_executions = 10\n file_path = file_path\n hv_df = pd.DataFrame()\n\n for i in range(number_of_executions):\n file_name = file + str(i) + '.txt'\n\n f = open(os.path.join(file_path, folder, file_name),'r',encoding='utf-8')\n data = f.readlines()\n splitted_data = ' '.join([i for i in data]).split('#\\n')\n splitted_data = [i for i in splitted_data if len(i) > 1]\n \n hv_pareto = []\n indexes = []\n for k in range(len(splitted_data)):\n converted = [i.strip().split(',') for i in splitted_data[k].split('\\n') if len(i) > 1]\n pop = [[float(j) for j in i] for i in converted]\n pop = [list(line) for line in np.array(pop)*lambdas]\n \n if dimension == 1:\n pop = [[i[0], i[4], i[2]] for i in pop]\n pop = get_nondominated_vectors(pop)\n hv = hypervolume(pop)\n hv_pareto.append(hv.compute([150000,150000,150000])) \n elif dimension == 2:\n pop = [[i[0] + i[3] + i[6] + i[7], i[1] + i[4], i[2] + i[5]] for i in pop]\n pop = get_nondominated_vectors(pop)\n hv = hypervolume(pop)\n hv_pareto.append(hv.compute([150000,150000,150000]))\n indexes.append(100*k)\n df = pd.DataFrame(data=[indexes, hv_pareto]).T\n columns_string = 'Evaluation HV'+str(i)\n df.columns = columns_string.split()\n hv_df = pd.concat([hv_df, df[columns_string.split()[1]]], axis=1, sort=False)\n if plot:\n \thv_df.T.mean().plot(x='Evaluation', y='HV',figsize=(10,8))\n return hv_df.T.mean(), hv_df\n\ndef get_hv(file_name):\n with open(file_name) as file:\n hv = []\n \n for line in file:\n hv.append(float(line))\n \n return pd.DataFrame(data=hv, columns=['HV'])\n\ndef random_test(df1, df2, number_of_samples=30, plot_hist = True):\n DORAND = 2300\n \n spread2 = df2.values\n spread1 = df1.values\n \n medianSpreadDiff = np.median(spread2) - np.median(spread1)\n meanSpreadDiff = np.mean(spread2) - np.mean(spread1)\n \n totalSpread = np.append(spread1.tolist(), spread2.tolist())\n \n randMedianSpreadDiff = np.nan * np.ones((DORAND,1))\n randMeanSpreadDiff = np.nan * np.ones((DORAND,1))\n \n for randPool in range(0, DORAND-1):\n new1Index = np.random.permutation(number_of_samples)\n newSpread1 = totalSpread[new1Index[0:int(number_of_samples/2)]]\n newSpread2 = totalSpread[new1Index[int(number_of_samples/2):number_of_samples]]\n \n randMedianSpreadDiff[randPool] = np.median(newSpread2) - np.median(newSpread1)\n randMeanSpreadDiff[randPool] = np.mean(newSpread2) - np.mean(newSpread1)\n \n randMedianSpreadDiff[DORAND - 1] = medianSpreadDiff\n randMeanSpreadDiff[DORAND - 1] = meanSpreadDiff\n \n z = (meanSpreadDiff - np.mean(randMeanSpreadDiff) )/ np.std(randMeanSpreadDiff)\n \n limiar = 1.96 * np.std(randMeanSpreadDiff) + np.mean(randMeanSpreadDiff)\n \n if z <= -1.96:\n print('H1-')\n elif z >= 1.96:\n print('H1+')\n else:\n print('H0')\n print('Limiar =',limiar)\n print('z =',z)\n print('Mean Spread Diff',meanSpreadDiff)\n if plot_hist:\n plt.figure(figsize=(9,6))\n plt.hist(randMeanSpreadDiff, bins=60,color='gray', label='Distribution')\n plt.scatter(x=meanSpreadDiff,y=0,color='red',s=100,label='Observed Mean Difference')\n plt.scatter(x=limiar,y=0,color='black',s=100,label='Confidence Limiars (95%)')\n plt.scatter(x=-limiar,y=0,color='black',s=100,)\n plt.xticks(fontsize=(20))\n plt.yticks(fontsize=(18))\n plt.legend(fontsize = 'large')\n plt.show()\n\ndef pareto(p,q):#p domina q? a resposta é um booleano\n y = False\n if sum(p >= q) == len(p):\n if sum(p == q) != len(p):\n y = True\n return y\n\ndef set_coverage_metric(X,Y):\n p_is_dominated = 0\n q_is_dominated = 0\n X_bool = np.zeros(X.shape[0])\n Y_bool = np.zeros(Y.shape[0])\n \n #q dominates p?\n for p in range(Y.shape[0]):\n p_ = Y[p]\n for q in X:\n if pareto(p_,q):\n Y_bool[p] = 1\n \n #q dominates p?\n for q in range(X.shape[0]):\n q_ = X[q]\n for p in Y:\n if pareto(q_,p):\n X_bool[q] = 1\n \n print('Returning C(A,B) and C(B,A)')\n return sum(Y_bool)/len(Y), sum(X_bool)/len(X)\n\ndef get_nondominated_vectors(X):\n X = np.array(X)\n p_is_dominated = 0\n q_is_dominated = 0\n X_bool = np.zeros(X.shape[0])\n \n for q in range(X.shape[0]):\n q_ = X[q]\n for p in X:\n if pareto(q_,p):\n X_bool[q] = 1\n return [list(X[i]) for i,j in enumerate(X_bool) if X_bool[i] == 0]\n\ndef get_combined_pareto(path):\n file_path = path #'/home/renansantos/Área de Trabalho/Doutorado/PhD_2019_01/PhD_2019_01/Results_2020/MOEAD/MOEAD_R3_CA/'\n file_name = 'moead-combined_pareto_reduced.csv'\n\n f = open(os.path.join(file_path, file_name), 'r',encoding='utf-8')\n data = [i.split(']')[0].replace('[','').replace(',','').split() for i in f.readlines()]\n data = [(float(i[0]), float(i[1]), float(i[2])) for i in data]\n data = pd.DataFrame(data=data).drop_duplicates()\n\n return data\n\ndef get_combined_pareto_moead_agr(path):\n file_path = path #'/home/renansantos/Área de Trabalho/Doutorado/PhD_2019_01/PhD_2019_01/Results_2020/MOEAD/MOEAD_R3_CA/'\n file_name = 'moead-combined_pareto_reduced.csv'\n\n f = open(os.path.join(file_path, file_name), 'r',encoding='utf-8')\n data = [i.split(']')[0].replace('[','').replace(',','').split() for i in f.readlines()]\n data = [[float(j) for j in line] for line in data]\n\n data = [list(line) for line in np.array(data)*lambdas]\n data = [[i[0] + i[3] + i[6] + i[7], i[1] + i[4], i[2] + i[5]] for i in data]\n\n data = get_nondominated_vectors(data)\n data = pd.DataFrame(data=data).drop_duplicates()\n return data\n\ndef get_combined_pareto_moead_esc(path):\n file_path = path #'/home/renansantos/Área de Trabalho/Doutorado/PhD_2019_01/PhD_2019_01/Results_2020/MOEAD/MOEAD_R3_CA/'\n file_name = 'moead-combined_pareto_reduced.csv'\n\n f = open(os.path.join(file_path, file_name), 'r',encoding='utf-8')\n data = [i.split(']')[0].replace('[','').replace(',','').split() for i in f.readlines()]\n data = [[float(j) for j in line] for line in data]\n\n data = [list(line) for line in np.array(data)*lambdas]\n data = [[i[0], i[4], i[2]] for i in data]\n\n data = get_nondominated_vectors(data)\n data = pd.DataFrame(data=data).drop_duplicates()\n return data\n\ndef plot_combined_pareto(combined_pareto_1, combined_pareto_2, label_1, label_2):\n fig = plt.figure(figsize=(10,8))\n ax = fig.add_subplot(111, projection='3d')\n data_1 = combined_pareto_1\n x_1 = data_1[0].tolist()\n y_1 = data_1[1].tolist()\n z_1 = data_1[2].tolist()\n ax.scatter(x_1, y_1, z_1, c='r', marker='o', label=label_1, s=60)\n data_2 = combined_pareto_2\n x_2 = data_2[0].tolist()\n y_2 = data_2[1].tolist()\n z_2 = data_2[2].tolist()\n ax.scatter(x_2, y_2, z_2, c='b', marker='v', label=label_2, s=60)\n\n ax.set_xlabel('$FO_1$')\n ax.set_ylabel('$FO_2$')\n ax.set_zlabel('$FO_3$')\n plt.legend()\n plt.show()"
},
{
"alpha_fraction": 0.6870503425598145,
"alphanum_fraction": 0.6870503425598145,
"avg_line_length": 18.85714340209961,
"blob_id": "fe56293b63b3abd9cdd348431501873060d4658f",
"content_id": "e353c45a43dbcfcc1be6e6bad8b0504f524ba20d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 278,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 14,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/FeatureWeighting.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "package KFST.featureSelection;\n\npublic abstract class FeatureWeighting extends FeatureSelection {\n\n protected double[] featureValues;\n\n public FeatureWeighting() {\n super();\n }\n\n public double[] getFeatureValues() {\n return this.featureValues;\n }\n}\n"
},
{
"alpha_fraction": 0.6111512184143066,
"alphanum_fraction": 0.6219776272773743,
"avg_line_length": 34.52564239501953,
"blob_id": "1fc00b587fd305f1a529ebe921ec95e5836b5f84",
"content_id": "9c8f5ddbeb9f6794d3d85c8922ab4e4f7ea6182c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5542,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 156,
"path": "/PhD_2019_01/src/main/java/KFST/gui/ProjectPath.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "///*\n// * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n// * completely in Java, for performing feature selection process in different\n// * areas of research.\n// * For more information about KFST, please visit:\n// * http://kfst.uok.ac.ir/index.html\n// *\n// * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n// * Sanandaj, Iran.\n// *\n// * This program 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// * any later version.\n// *\n// * This program is distributed in the hope that it will be useful,\n// * but WITHOUT ANY WARRANTY; without even the implied warranty of\n// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// * GNU General Public License for more details.\n// *\n// * You should have received a copy of the GNU General Public License\n// * along with this program. If not, see <http://www.gnu.org/licenses/>.\n// */\n//package KFST.gui;\n//\n//import KFST.util.FileFunc;\n//import java.awt.Color;\n//import java.awt.event.ActionEvent;\n//import java.awt.event.ActionListener;\n//import javax.swing.ImageIcon;\n//import javax.swing.JButton;\n//import javax.swing.JFileChooser;\n//import javax.swing.JFrame;\n//import javax.swing.JLabel;\n//import javax.swing.JPanel;\n//import javax.swing.JTextField;\n//import javax.swing.SwingUtilities;\n//import javax.swing.UIManager;\n//import javax.swing.UnsupportedLookAndFeelException;\n//\n///**\n// * This java class is used to create and show a panel for the selecting path for\n// * the project.\n// *\n// * @author Shahin Salavati\n// */\n//public class ProjectPath extends JFrame implements ActionListener {\n//\n// JButton btn_browse, btn_select;\n// JLabel lbl_select, lbl_path;\n// JTextField txt_path;\n// String path = \"\";\n// JPanel mainPanel;\n//\n// /**\n// * Creates new form ProjectPath. This method is called from within the\n// * constructor to initialize the form.\n// */\n// public ProjectPath() {\n// mainPanel = new JPanel();\n// mainPanel.setLayout(null);\n//\n// lbl_select = new JLabel(\"Please select a folder for the tool:\");\n// lbl_select.setBounds(20, 30, 204, 14);\n//\n// lbl_path = new JLabel(\"Folder:\");\n// lbl_path.setBounds(20, 70, 34, 14);\n//\n// txt_path = new JTextField();\n// txt_path.setBounds(60, 67, 180, 21);\n// txt_path.setBackground(Color.WHITE);\n// txt_path.setEditable(false);\n//\n// btn_browse = new JButton(\"Browse...\");\n// btn_browse.setBounds(250, 66, 80, 23);\n// btn_browse.addActionListener(this);\n//\n// btn_select = new JButton(\"Ok\");\n// btn_select.setBounds(140, 125, 69, 23);\n// btn_select.addActionListener(this);\n// btn_select.setEnabled(false);\n//\n// mainPanel.add(lbl_select);\n// mainPanel.add(btn_browse);\n// mainPanel.add(btn_select);\n// mainPanel.add(lbl_path);\n// mainPanel.add(txt_path);\n//\n// this.setTitle(\"Workspase Selection\");\n// this.setIconImage(new ImageIcon(getClass().getResource(\"/KFST/gui/icons/small_logo.png\")).getImage());\n// this.setSize(350, 190);\n// this.setLocationRelativeTo(null);\n// this.add(mainPanel);\n// this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n// this.setResizable(false);\n// this.setVisible(true);\n// }\n//\n// /**\n// * The listener method for receiving action events.\n// * Invoked when an action occurs.\n// *\n// * @param e an action event\n// */\n// @Override\n// public void actionPerformed(ActionEvent e) {\n// if (e.getSource().equals(btn_browse)) {\n// btn_browseActionPerformed(e);\n// } else if (e.getSource().equals(btn_select)) {\n// btn_selectActionPerformed(e);\n// }\n// }\n//\n// /**\n// * This method sets an action for the btn_browse button.\n// *\n// * @param e an action event\n// */\n// private void btn_browseActionPerformed(ActionEvent e) {\n// JFileChooser jfch = new JFileChooser();\n// jfch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);\n// if (jfch.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {\n// txt_path.setText(jfch.getSelectedFile().getPath());\n// path = txt_path.getText();\n// btn_select.setEnabled(true);\n// }\n// }\n//\n// /**\n// * This method sets an action for the btn_select button.\n// *\n// * @param e an action event\n// */\n// private void btn_selectActionPerformed(ActionEvent e) {\n// //creates the two folder (CSV - ARFF)in the selected path\n// FileFunc.createDirectory(path + \"\\\\CSV\\\\\");\n// FileFunc.createDirectory(path + \"\\\\ARFF\\\\\");\n//\n// MainPanel ui = new MainPanel(path);\n// ui.createAndShow();\n// this.setVisible(false);\n// }\n//\n// public static void main(String[] args) {\n// try {\n// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n// UIManager.getDefaults().put(\"TextArea.font\", UIManager.getFont(\"TextField.font\"));\n// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {\n// System.out.println(\"Error setting native LAF: \" + e);\n// }\n//\n// SwingUtilities.invokeLater(() -> {\n// ProjectPath sp = new ProjectPath();\n// });\n// }\n//}\n"
},
{
"alpha_fraction": 0.622336745262146,
"alphanum_fraction": 0.6249825954437256,
"avg_line_length": 37.196807861328125,
"blob_id": "617141c6e28548fc178847412e1dd88906fd325f",
"content_id": "167973e2d536b06b3853438b552651729a082b0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 7181,
"license_type": "no_license",
"max_line_length": 138,
"num_lines": 188,
"path": "/PhD_2019_01/src/main/java/KFST/util/FileFunc.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.util;\n\nimport KFST.dataset.DatasetInfo;\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport weka.core.Instances;\nimport weka.core.converters.ArffSaver;\nimport weka.core.converters.CSVLoader;\n\n/**\n * This java class is used to implement various utility methods for manipulating\n * files and directories. The methods in this class is contained brief \n * description of the applications.\n *\n * @author Sina Tabakhi\n */\npublic final class FileFunc {\n \n /**\n * creates a new directory denoted by pathname\n *\n * @param pathname path of the directory \n */\n public static void createDirectory(String pathname) {\n File dir = new File(pathname);\n dir.mkdir();\n }\n\n /**\n * deletes all files in the directory denoted by pathname\n * \n * @param pathname path of the directory \n */\n public static void deleteFilesInDirectory(String pathname) {\n File dir = new File(pathname);\n if (dir.isDirectory()) {\n File[] directory = dir.listFiles();\n for (File directoryPath : directory) {\n directoryPath.delete();\n }\n }\n }\n \n /**\n * deletes the current directory with all files in the directory denoted by \n * pathname\n * \n * @param pathname path of the directory \n */\n public static void deleteDirectoryWithAllFiles(String pathname) {\n deleteFilesInDirectory(pathname);\n File dir = new File(pathname);\n if (dir.isDirectory()) {\n dir.delete();\n }\n }\n \n /**\n * This method creates a CSV (Comma delimited) file of the input data\n *\n * @param oldData the input data\n * @param selectedFeature the list of selected Feature\n * @param name name of the path for created CSV file\n * @param featureNames a string array of features names\n * @param classNames a string array of class labels names\n */\n public static void createCSVFile(double[][] oldData, int[] selectedFeature, String name, String[] featureNames, String[] classNames) {\n int numSamples = oldData.length;\n int sizeFeatureSet = selectedFeature.length;\n int numFeats = oldData[0].length - 1;\n try {\n FileWriter fw = new FileWriter(name, false);\n PrintWriter pw = new PrintWriter(fw);\n for (int i = 0; i < sizeFeatureSet; i++) {\n pw.print(featureNames[selectedFeature[i]] + \",\");\n }\n pw.println(featureNames[numFeats]);\n for (int i = 0; i < numSamples; i++) {\n for (int j = 0; j < sizeFeatureSet; j++) {\n pw.print(oldData[i][selectedFeature[j]] + \",\");\n }\n int index = (int) oldData[i][numFeats];\n pw.println(classNames[index]);\n }\n fw.close();\n } catch (IOException ex) {\n Logger.getLogger(FileFunc.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n \n /**\n * This method converts CSV file to ARFF file for the Weka Software\n *\n * @param nameCSV the path of the CSV file\n * @param nameARFF the path for the created ARFF file\n * @param pathProject the path of the project\n * @param sizeFeatureSubset the number of selected features\n * @param ob the object of the DatasetInfo\n */\n public static void convertCSVtoARFF(String nameCSV, String nameARFF, String pathProject, int sizeFeatureSubset, DatasetInfo ob) {\n convertCSVtoARFF(nameCSV, nameARFF, pathProject, sizeFeatureSubset,\n ob.getNumFeature(), ob.getNameFeatures(), ob.getNumClass(), ob.getClassLabel());\n }\n \n /**\n * This method converts CSV file to ARFF file for the Weka Software\n *\n * @param nameCSV the path of the CSV file\n * @param nameARFF the path for the created ARFF file\n * @param pathProject the path of the project\n * @param sizeFeatureSubset the number of selected features\n * @param numFeature the number of original features with class\n * @param nameFeatures the array of features' names\n * @param numClass the number of classes\n * @param classLabel the array of class labels' names\n */\n public static void convertCSVtoARFF(String nameCSV, String nameARFF, String pathProject, int sizeFeatureSubset,\n int numFeature, String[] nameFeatures, int numClass, String[] classLabel) {\n int selectLine = sizeFeatureSubset + 3;\n File tempFile = new File(pathProject + \"tempFile.arff\");\n\n String createLabelString = \"@attribute \" + nameFeatures[numFeature] + \" {\";\n for (int i = 0; i < numClass - 1; i++) {\n createLabelString += classLabel[i] + \",\";\n }\n createLabelString += classLabel[numClass - 1] + \"}\";\n try {\n FileInputStream fis = new FileInputStream(nameCSV);\n //load CSV File\n CSVLoader loader = new CSVLoader();\n loader.setSource(fis);\n Instances data = loader.getDataSet();\n //load ARFF File\n ArffSaver saver = new ArffSaver();\n saver.setInstances(data);\n saver.setFile(tempFile);\n saver.writeBatch();\n //Refine Header ARFF File\n BufferedReader br = new BufferedReader(new FileReader(tempFile));\n FileWriter fw = new FileWriter(nameARFF, false);\n PrintWriter pw = new PrintWriter(fw);\n while (selectLine-- > 1) {\n pw.println(br.readLine());\n }\n pw.println(createLabelString);\n br.readLine();\n while (br.ready()) {\n pw.println(br.readLine());\n }\n br.close();\n fw.close();\n fis.close();\n tempFile.delete();\n } catch (IOException ex) {\n Logger.getLogger(FileFunc.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6719424724578857,
"alphanum_fraction": 0.6762589812278748,
"avg_line_length": 34.33898162841797,
"blob_id": "da45a6a9a8b2ca06e6dcb2862a12497932eb01d9",
"content_id": "2f09006d76607f81832967ad2b05b439c52fe88b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2085,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 59,
"path": "/PhD_2019_01/src/main/java/KFST/classifier/WekaSVMKernel.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.classifier;\n\nimport KFST.gui.classifier.svmClassifier.SVMKernelType;\nimport weka.classifiers.functions.supportVector.*;\n\n/**\n * This java class is used to convert SVM kernel implemented in KFST tool to SVM\n * kernel implemented in weka software.\n *\n * @author Sina Tabakhi\n */\npublic final class WekaSVMKernel {\n\n /**\n * This method return the weka SVM kernel type according to the KFST SVM\n * kernel type.\n *\n * @param type KFST SVM kernel type\n *\n * @return weka SVM kernel type\n */\n public static Kernel parse(SVMKernelType type) {\n try {\n if (type == SVMKernelType.POLYNOMIAL) {\n return PolyKernel.class.newInstance();\n } else if (type == SVMKernelType.RBF) {\n return RBFKernel.class.newInstance();\n } else if (type == SVMKernelType.PEARSON_VII) {\n return Puk.class.newInstance();\n }\n return null;\n } catch (InstantiationException | IllegalAccessException ex) {\n return null;\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6114152669906616,
"alphanum_fraction": 0.6172393560409546,
"avg_line_length": 35.68803405761719,
"blob_id": "d83c8e2432cf3b52aabafc7ee5a4803205115145",
"content_id": "958b526a7c8c4a37680bf5081c9b5d8169fc06c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8585,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 234,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/ACOBasedMethods/OptimalACO/Colony.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.ACOBasedMethods.OptimalACO;\n\nimport KFST.featureSelection.wrapper.ACOBasedMethods.BasicColony;\nimport KFST.featureSelection.wrapper.GABasedMethods.SelectionOperator;\nimport KFST.result.performanceMeasure.Criteria;\nimport KFST.util.ArraysFunc;\nimport KFST.util.MathFunc;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n\n/**\n * This java class is used to implement a colony of ants in optimal ant colony\n * optimization (Optimal ACO) method in which the type of ant is extended from\n * Ant class.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.wrapper.GABasedMethods.BasicPopulation\n */\npublic class Colony extends BasicColony<Ant> {\n\n public static double PHI;\n\n /**\n * Initializes the parameters\n *\n * @param phi the phi parameter used in the pheromone update rule for\n * controlling the relative weight of classifier performance and feature\n * subset length\n */\n public Colony(double phi) {\n super(Ant.class);\n Colony.PHI = phi;\n for (int i = 0; i < COLONY_SIZE; i++) {\n colony[i] = new Ant();\n }\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public void initialization() {\n graphRepresentation.fillPheromoneArray(INIT_PHEROMONE_VALUE);\n// System.out.println(graphRepresentation.toString());\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public void setInitialState() {\n Boolean[] checkListFeatures = new Boolean[NUM_ORIGINAL_FEATURE];\n Arrays.fill(checkListFeatures, false);\n\n for (int ant = 0; ant < COLONY_SIZE; ant++) {\n colony[ant].emptyFeatureSubset();\n colony[ant].setFitness(0);\n colony[ant].setCountSteps(0);\n }\n\n for (int feat = 0; feat < COLONY_SIZE; feat++) {\n checkListFeatures[feat] = true;\n }\n MathFunc.randomize(checkListFeatures);\n\n for (int feat = 0, ant = 0; feat < NUM_ORIGINAL_FEATURE; feat++) {\n if (checkListFeatures[feat]) {\n colony[ant++].addFeature(feat);\n }\n }\n\n// for (int ant = 0; ant < COLONY_SIZE; ant++) {\n// System.out.println(colony[ant].toString());\n// }\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public Criteria evaluateCurrentSolution(int antIndex) {\n int[] featureSet = ArraysFunc.convertArrayListToInt(colony[antIndex].getFeatureSubset());\n ArraysFunc.sortArray1D(featureSet, false);\n \n return fitnessEvaluator.crossValidation(featureSet);\n }\n\n /**\n * {@inheritDoc }\n * <p>\n * Classifier performance is used as heuristic desirability.\n */\n @Override\n public void operateStateTransitionRule(int antIndex) {\n ArrayList<Integer> feasibleFeatureSet = colony[antIndex].getFeasibleFeatureSet();\n double[] probabilities = new double[feasibleFeatureSet.size()];\n double[] fitnessValues = new double[feasibleFeatureSet.size()];\n double sumProb = 0;\n\n for (int feat = 0; feat < probabilities.length; feat++) {\n int currFeasible = feasibleFeatureSet.get(feat);\n colony[antIndex].addFeature(currFeasible);\n \n fitnessValues[feat] = evaluateCurrentSolution(antIndex).getAccuracy() / 100.0;\n double pheromone = graphRepresentation.getPheromone(0, currFeasible);\n probabilities[feat] = Math.pow(pheromone, ALPHA) * Math.pow(fitnessValues[feat], BETA);\n sumProb += probabilities[feat];\n \n colony[antIndex].removeFeature(currFeasible);\n }\n\n for (int feat = 0; feat < probabilities.length; feat++) {\n probabilities[feat] = probabilities[feat] / sumProb;\n }\n\n int selectedIndex = SelectionOperator.rouletteWheel(probabilities);\n int selectedFeat = feasibleFeatureSet.get(selectedIndex);\n colony[antIndex].addFeature(selectedFeat);\n colony[antIndex].setFitness(fitnessValues[selectedIndex]);\n\n// System.out.println(colony[antIndex].toString());\n }\n\n /**\n * {@inheritDoc }\n */\n @Override\n public void constructSolution() {\n for (int ant = 0; ant < COLONY_SIZE; ant++) {\n while (colony[ant].getFeatureSubsetSize() < NUM_ORIGINAL_FEATURE\n && colony[ant].getCountSteps() < 10) {\n double beforeFitness = colony[ant].getFitness();\n operateStateTransitionRule(ant);\n double afterFitness = colony[ant].getFitness();\n if (afterFitness <= beforeFitness) {\n colony[ant].increaseCountSteps();\n } else {\n colony[ant].setCountSteps(0);\n }\n }\n }\n\n// System.out.println(this.toString());\n }\n\n /**\n * {@inheritDoc }\n * <p>\n * Best ant deposits additional pheromone on nodes of the best solution.\n */\n @Override\n public void operatePheromoneUpdateRule() {\n /**\n * Pheromone evaporation on all nodes is triggered\n */\n for (int feat = 0; feat < NUM_ORIGINAL_FEATURE; feat++) {\n double evaporatedValue = (1.0 - RHO) * graphRepresentation.getPheromone(0, feat);\n graphRepresentation.setPheromone(evaporatedValue, 0, feat);\n }\n\n /**\n * Best ant deposits additional pheromone on nodes of the best solution\n */\n Ant bestAnt = getBestAnt();\n double firstValue = PHI * bestAnt.getFitness();\n double secondValue = ((1.0 - PHI) * (NUM_ORIGINAL_FEATURE - bestAnt.getFeatureSubsetSize())) / NUM_ORIGINAL_FEATURE;\n ArrayList<Integer> featureSet = bestAnt.getFeatureSubset();\n for (int i = 0; i < featureSet.size(); i++) {\n double prevValue = graphRepresentation.getPheromone(0, featureSet.get(i));\n graphRepresentation.setPheromone(prevValue + firstValue + secondValue, 0, featureSet.get(i));\n }\n\n /**\n * Each ant deposit a quantity of pheromone on each node that it has\n * used\n */\n for (int ant = 0; ant < COLONY_SIZE; ant++) {\n firstValue = PHI * colony[ant].getFitness();\n secondValue = ((1.0 - PHI) * (NUM_ORIGINAL_FEATURE - colony[ant].getFeatureSubsetSize())) / NUM_ORIGINAL_FEATURE;\n featureSet = colony[ant].getFeatureSubset();\n for (int i = 0; i < featureSet.size(); i++) {\n double prevValue = graphRepresentation.getPheromone(0, featureSet.get(i));\n graphRepresentation.setPheromone(prevValue + firstValue + secondValue, 0, featureSet.get(i));\n }\n }\n }\n\n /**\n * {@inheritDoc }\n * <p>\n * Best ant is selected based on classifier performance and length of\n * selected subsets.\n */\n @Override\n public Ant getBestAnt() {\n int fittestIndex = 0;\n double fittestValue = colony[0].getFitness();\n int subsetSize = colony[0].getFeatureSubsetSize();\n for (int ant = 1; ant < COLONY_SIZE; ant++) {\n if ((colony[ant].getFitness() > fittestValue)\n || ((colony[ant].getFitness() == fittestValue)\n && (colony[ant].getFeatureSubsetSize() < subsetSize))) {\n fittestIndex = ant;\n fittestValue = colony[ant].getFitness();\n subsetSize = colony[ant].getFeatureSubsetSize();\n }\n }\n// System.out.println(colony[fittestIndex].toString());\n return colony[fittestIndex];\n }\n}\n"
},
{
"alpha_fraction": 0.6647923588752747,
"alphanum_fraction": 0.6695501804351807,
"avg_line_length": 34.56922912597656,
"blob_id": "a403634a1c96c5d0a5c958149914093306b05133",
"content_id": "12bf5e1c3f41cfe3d7f4e8df22842d28fe65ff6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2312,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 65,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/wrapper/GABasedMethods/MutationOperator.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.wrapper.GABasedMethods;\n\n/**\n * This java class is used to implement various mutation operators for mutating\n * new offsprings by changing the value of some genes in them.\n * <p>\n * The methods in this class is contained brief description of the applications.\n *\n * @author Sina Tabakhi\n */\npublic class MutationOperator {\n\n /**\n * mutates new offsprings by changing the value of some genes in them using\n * bitwise mutation\n *\n * @param parent the first parent\n * @param prob the probability of mutation operation\n */\n public static void bitwiseMutation(boolean[] parent, double prob) {\n for (int gene = 0; gene < parent.length; gene++) {\n if (Math.random() <= prob) {\n parent[gene] = !parent[gene];\n }\n }\n }\n\n /**\n * mutates new offsprings by changing the value of some genes in them using\n * bitwise mutation\n *\n * @param parent the first parent\n * @param prob the probability of mutation operation\n */\n public static void bitwiseMutation(Boolean[] parent, double prob) {\n for (int gene = 0; gene < parent.length; gene++) {\n if (Math.random() <= prob) {\n parent[gene] = !parent[gene];\n }\n }\n }\n}\n"
},
{
"alpha_fraction": 0.42391303181648254,
"alphanum_fraction": 0.49637681245803833,
"avg_line_length": 10.541666984558105,
"blob_id": "5f1c10c7aa987da05b847e56b9cad85edb718ded",
"content_id": "549916beffc61ded7a5934f8ab722001e27ce571",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 276,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 24,
"path": "/PhD_2019_01/primeira tentativa/script.sh",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "#!/bin/bash \n\nfor i in 50 100 150 200 250\ndo\n\tcd .//DR_1//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//DR_25//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//VAR_1//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//VAR_25//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\ndone"
},
{
"alpha_fraction": 0.5869965553283691,
"alphanum_fraction": 0.5957708358764648,
"avg_line_length": 37.503379821777344,
"blob_id": "409d430ada3e62f4352efbb5cf169a88817894d6",
"content_id": "c9283965c500265d112023e40a859d058016fb38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 11397,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 296,
"path": "/PhD_2019_01/src/main/java/KFST/featureSelection/filter/supervised/MRMR.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.featureSelection.filter.supervised;\n\nimport KFST.util.ArraysFunc;\nimport KFST.util.MathFunc;\nimport KFST.featureSelection.filter.FilterApproach;\n\n/**\n * This java class is used to implement the minimal redundancy maximal\n * relevance (mRMR) method.\n *\n * @author Sina Tabakhi\n * @see KFST.featureSelection.filter.FilterApproach\n * @see KFST.featureSelection.FeatureSelection\n */\npublic class MRMR extends FilterApproach {\n\n private double[][] probFeature;\n private double[][] valuesFeature;\n //private double ERROR_DENOMINATOR = 0.0001;\n\n /**\n * initializes the parameters\n *\n * @param arguments array of parameters contains \n * (<code>sizeSelectedFeatureSubset</code>) in which \n * <code><b><i>sizeSelectedFeatureSubset</i></b></code> is the number of \n * selected features\n */\n public MRMR(Object... arguments) {\n super((int)arguments[0]);\n }\n \n /**\n * initializes the parameters\n *\n * @param sizeSelectedFeatureSubset the number of selected features\n */\n public MRMR(int sizeSelectedFeatureSubset) {\n super(sizeSelectedFeatureSubset);\n }\n\n /**\n * computes the number of different values of each feature\n *\n * @param index the index of the feature\n *\n * @return the number of different values\n */\n private int computeNumValue(int index) {\n int count = 0;\n\n for (int i = 1; i < trainSet.length; i++) {\n if (trainSet[i][index] != trainSet[i - 1][index]) {\n count++;\n }\n }\n\n return count + 1;\n }\n\n /**\n * saves the different values of each feature\n *\n * @param index the index of the feature\n */\n private void computeDifferentValue(int index) {\n int count = 0;\n\n for (int i = 1; i < trainSet.length; i++) {\n if (trainSet[i][index] != trainSet[i - 1][index]) {\n valuesFeature[index][count++] = trainSet[i - 1][index];\n }\n }\n valuesFeature[index][count] = trainSet[trainSet.length - 1][index];\n }\n\n /**\n * computes the probabilities values of each feature\n *\n * @param index the index of the feature\n */\n private void computeProbFeat(int index) {\n int count = 0;\n int indexStart = 0;\n\n for (int i = 1; i < trainSet.length; i++) {\n if (trainSet[i][index] != trainSet[i - 1][index]) {\n probFeature[index][count++] = (i - indexStart) / (double) trainSet.length; // probability of the feature based on its given value\n// if (probFeature[index][count - 1] == 0) {\n// probFeature[index][count - 1] = ERROR_DENOMINATOR;\n// }\n indexStart = i;\n }\n }\n probFeature[index][count] = (trainSet.length - indexStart) / (double) trainSet.length; // probability of the feature based on its given value\n// if (probFeature[index][count] == 0) {\n// probFeature[index][count] = ERROR_DENOMINATOR;\n// }\n }\n\n /**\n * computes the joint probabilities values between two features\n *\n * @param indexFeat2 the index of the second feature\n * @param indexStartData the start index of the dataset\n * @param indexEndData the end index of the dataset\n *\n * @return an array of the joint probabilities values\n */\n private double[] computeJointProb(int indexFeat2, int indexStartData, int indexEndData) {\n double[] jointProbValue = new double[probFeature[indexFeat2].length];\n ArraysFunc.sortArray2D(trainSet, indexFeat2, indexStartData, indexEndData); //sorts the dataset values corresponding to a given feature(feature indexFeat2)\n int indexStart = indexStartData;\n int j = -1;\n\n for (int i = indexStartData + 1; i < indexEndData; i++) {\n if (trainSet[i][indexFeat2] != trainSet[i - 1][indexFeat2]) {\n for (j = j + 1; j < valuesFeature[indexFeat2].length; j++) {\n if (valuesFeature[indexFeat2][j] == trainSet[i - 1][indexFeat2]) {\n jointProbValue[j] = (i - indexStart) / (double) trainSet.length; //probability of the feature based on its given value\n break;\n }\n }\n indexStart = i;\n }\n }\n\n for (j = j + 1; j < valuesFeature[indexFeat2].length; j++) {\n if (valuesFeature[indexFeat2][j] == trainSet[indexEndData - 1][indexFeat2]) {\n jointProbValue[j] = (indexEndData - indexStart) / (double) trainSet.length; //probability of the feature based on its given value\n break;\n }\n }\n\n return jointProbValue;\n }\n\n /**\n * computes the mutual information values between two features\n *\n * @param index1 the index of the first feature\n * @param index2 the index of the second feature\n *\n * @return the mutual information value\n */\n private double computeMutualInfo(int index1, int index2) {\n double mutualInfoValue = 0;\n ArraysFunc.sortArray2D(trainSet, index1); //sorts the dataset values corresponding to a given feature(feature index1)\n int indexStart = 0;\n\n for (int i = 1; i < trainSet.length; i++) {\n if (trainSet[i][index1] != trainSet[i - 1][index1]) {\n double probFeat1 = (i - indexStart) / (double) trainSet.length; //probability of the feature based on its given value\n double[] jointProb = computeJointProb(index2, indexStart, i); //joint probabilitis values between feature index1 and index2\n\n //update mutual information value of the given feature\n for (int j = 0; j < jointProb.length; j++) {\n if (jointProb[j] != 0) {\n double denominatorValue = probFeat1 * probFeature[index2][j];\n mutualInfoValue += jointProb[j] * MathFunc.log2(jointProb[j] / denominatorValue);\n }\n }\n\n indexStart = i;\n }\n }\n\n double probFeat1 = (trainSet.length - indexStart) / (double) trainSet.length; //probability of the feature based on its given value\n double[] jointProb = computeJointProb(index2, indexStart, trainSet.length); //joint probabilitis values between feature index1 and index2\n\n //update mutual information value of the given feature\n for (int j = 0; j < jointProb.length; j++) {\n if (jointProb[j] != 0) {\n double denominatorValue = probFeat1 * probFeature[index2][j];\n mutualInfoValue += jointProb[j] * MathFunc.log2(jointProb[j] / denominatorValue);\n }\n }\n\n return mutualInfoValue;\n }\n\n /**\n * finds the maximum value in the array and returns its index\n *\n * @param array the input array\n *\n * @return the index of the maximum value in the array\n */\n private int findMaxWithIndex(double[] array) {\n int index = 0;\n double max = array[index];\n\n for (int i = 1; i < array.length; i++) {\n if (array[i] > max) {\n max = array[i];\n index = i;\n }\n }\n return index;\n }\n\n /**\n * checks that is the current feature (index) available in the subset of\n * selected feature\n *\n * @param index the index of the feature\n * @param currentSize the current size of the selected features subset\n *\n * @return true if the current feature has been selected\n */\n private boolean isSelectedFeature(int index, int currentSize) {\n for (int i = 0; i < currentSize; i++) {\n if (selectedFeatureSubset[i] == index) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * starts the feature selection process by minimal redundancy\n * maximal relevance (mRMR) method\n */\n @Override\n public void evaluateFeatures() {\n double[] mutualInfoFeatClass = new double[numFeatures]; //mutual information values between features and class\n probFeature = new double[numFeatures + 1][]; //probabilities values of the features (+ class feature)\n valuesFeature = new double[numFeatures + 1][]; //different values of the features (+ class feature)\n\n //computes the probabilities values of each feature\n for (int i = 0; i <= numFeatures; i++) {\n ArraysFunc.sortArray2D(trainSet, i); //sorts the dataset values corresponding to a given feature(feature i)\n probFeature[i] = new double[computeNumValue(i)]; //computes the number of different values in feature i\n valuesFeature[i] = new double[probFeature[i].length];\n computeDifferentValue(i); //saves the different values of each feature\n computeProbFeat(i); //computes the probabilities values of each feature\n }\n\n //computes the mutual information values between features and class\n for (int i = 0; i < numFeatures; i++) {\n mutualInfoFeatClass[i] = computeMutualInfo(i, numFeatures);\n }\n\n //starts the feature selection process\n selectedFeatureSubset[0] = findMaxWithIndex(mutualInfoFeatClass); //finds a feature with the maximum mutual information value\n for (int i = 1; i < numSelectedFeature; i++) {\n double maxValue = -Double.MAX_VALUE;\n int indexMaxValue = -1;\n\n //finds the relevant feature from the current features set\n for (int j = 0; j < numFeatures; j++) {\n if (!isSelectedFeature(j, i)) {\n double result = 0;\n for (int k = 0; k < i; k++) {\n result += computeMutualInfo(j, selectedFeatureSubset[k]);\n }\n result /= i;\n result = mutualInfoFeatClass[j] - result;\n if (result > maxValue) {\n maxValue = result;\n indexMaxValue = j;\n }\n }\n }\n selectedFeatureSubset[i] = indexMaxValue;\n }\n\n ArraysFunc.sortArray1D(selectedFeatureSubset, false);\n// for (int i = 0; i < numSelectedFeature; i++) {\n// System.out.println(\"ranked = \" + selectedFeatureSubset[i]);\n// }\n }\n}\n"
},
{
"alpha_fraction": 0.43209877610206604,
"alphanum_fraction": 0.5037037134170532,
"avg_line_length": 10.941176414489746,
"blob_id": "90159e7a27898f42b84422721de603dc59f682ca",
"content_id": "2de425d5e4303e2b50f4a9d4bee46c6cc1fd735a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 405,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 34,
"path": "/PhD_2019_01/scripts_for_cluster_executions/script.sh",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "#!/bin/bash \n\nfor i in 50 100 150 200 250\ndo\n\tcd .//DR_50//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//DR_100//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//VAR_50//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//VAR_100//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//PEARSON_50//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\n\n\tcd .//PEARSON_100//$i\n\tnohup java -jar *.jar &\n\tcd ..\n\tcd ..\ndone"
},
{
"alpha_fraction": 0.6466681957244873,
"alphanum_fraction": 0.6498740315437317,
"avg_line_length": 54.63057327270508,
"blob_id": "f9152327afe3950f7bb674506d55a1b2ad7c5336",
"content_id": "36e58b1963baddca3c5781cfab59960a5a86efaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 8734,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 157,
"path": "/PhD_2019_01/src/main/java/KFST/gui/featureSelection/wrapper/GABased/SimpleGAPanel.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.gui.featureSelection.wrapper.GABased;\n\n//import KFST.classifier.ClassifierType;\n//import KFST.gui.classifier.DTClassifierPanel;\n//import KFST.gui.classifier.KNNClassifierPanel;\n//import KFST.gui.classifier.svmClassifier.SVMClassifierPanel;\nimport java.awt.Container;\n//import java.awt.Dialog;\nimport java.awt.Rectangle;\n//import javax.swing.UIManager;\n//import javax.swing.UnsupportedLookAndFeelException;\n\n/**\n * This java class is used to create and show a panel for the parameter settings\n * of the simple genetic algorithm (Simple GA).\n *\n * @author Sina Tabakhi\n * @see KFST.gui.ParameterPanel\n * @see KFST.featureSelection.wrapper.GABasedMethods.SimpleGA.SimpleGA\n */\npublic class SimpleGAPanel extends BasicGAPanel {\n\n /**\n * Creates new form SimpleGAPanel. This method is called from within the\n * constructor to initialize the form.\n */\n public SimpleGAPanel() {\n super();\n Container contentPane = getContentPane();\n\n this.setMethodTitle(\"Simple GA method settings:\");\n this.setMethodDescription(\"<html> Simple genetic algorithm (Simple GA) \"\n + \"is a version of GA in which each individual is randomly initialized. Additionally, \"\n + \"k-fold cross validation on training set is used for evaluating the classification \"\n + \"performance of a selected feature subset during feature selection process. </html>\");\n\n this.setMethodDescriptionPosition(new Rectangle(10, 35, 545, 90));\n \n contentPane.validate();\n// contentPane.revalidate();\n contentPane.repaint();\n// this.pack();\n }\n\n// public static void main(String[] arg) {\n// try {\n// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n// UIManager.getDefaults().put(\"TextArea.font\", UIManager.getFont(\"TextField.font\"));\n// } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {\n// System.out.println(\"Error setting native LAF: \" + e);\n// }\n//\n// SimpleGAPanel dtpanel = new SimpleGAPanel();\n// Dialog dlg = new Dialog(dtpanel);\n// dtpanel.setVisible(true);\n//\n// System.out.println(\"classifier type = \" + dtpanel.getClassifierType().toString());\n// if (dtpanel.getClassifierType() == ClassifierType.SVM) {\n// SVMClassifierPanel pan = (SVMClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: kernel = \" + pan.getKernel().toString()\n// + \" C = \" + pan.getParameterC());\n// } else if (dtpanel.getClassifierType() == ClassifierType.DT) {\n// DTClassifierPanel pan = (DTClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: min num = \" + pan.getMinNum()\n// + \" confidence = \" + pan.getConfidence());\n// } else if (dtpanel.getClassifierType() == ClassifierType.KNN) {\n// KNNClassifierPanel pan = (KNNClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: KNN Value = \" + pan.getKNNValue());\n// }\n//\n// System.out.println(\"selection type = \" + dtpanel.getSelectionType().toString());\n// System.out.println(\"crossover type = \" + dtpanel.getCrossOverType().toString());\n// System.out.println(\"mutation type = \" + dtpanel.getMutationType().toString());\n// System.out.println(\"replacement type = \" + dtpanel.getReplacementType().toString());\n// System.out.println(\"num iteration = \" + dtpanel.getNumIteration());\n// System.out.println(\"population size = \" + dtpanel.getPopulationSize());\n// System.out.println(\"crossover rate = \" + dtpanel.getCrossoverRate());\n// System.out.println(\"mutation rate = \" + dtpanel.getMutationRate());\n// System.out.println(\"K fold = \" + dtpanel.getKFolds());\n//\n// dtpanel.setDefaultValue();\n//\n// System.out.println(\"classifier type = \" + dtpanel.getClassifierType().toString());\n// if (dtpanel.getClassifierType() == ClassifierType.SVM) {\n// SVMClassifierPanel pan = (SVMClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: kernel = \" + pan.getKernel().toString()\n// + \" C = \" + pan.getParameterC());\n// } else if (dtpanel.getClassifierType() == ClassifierType.DT) {\n// DTClassifierPanel pan = (DTClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: min num = \" + pan.getMinNum()\n// + \" confidence = \" + pan.getConfidence());\n// } else if (dtpanel.getClassifierType() == ClassifierType.KNN) {\n// KNNClassifierPanel pan = (KNNClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: KNN Value = \" + pan.getKNNValue());\n// }\n// System.out.println(\"selection type = \" + dtpanel.getSelectionType().toString());\n// System.out.println(\"crossover type = \" + dtpanel.getCrossOverType().toString());\n// System.out.println(\"mutation type = \" + dtpanel.getMutationType().toString());\n// System.out.println(\"replacement type = \" + dtpanel.getReplacementType().toString());\n// System.out.println(\"num iteration = \" + dtpanel.getNumIteration());\n// System.out.println(\"population size = \" + dtpanel.getPopulationSize());\n// System.out.println(\"crossover rate = \" + dtpanel.getCrossoverRate());\n// System.out.println(\"mutation rate = \" + dtpanel.getMutationRate());\n// System.out.println(\"K fold = \" + dtpanel.getKFolds());\n//\n// dtpanel.setUserValue(ClassifierType.SVM, new SVMClassifierPanel(),\n// SelectionType.RANK_BASED_SELECTION, CrossOverType.UNIFORM_CROSS_OVER,\n// MutationType.BITWISE_MUTATION, ReplacementType.TOTAL_REPLACEMENT,\n// 20, 10, 0.2, 0.02, 4);\n//\n// System.out.println(\"classifier type = \" + dtpanel.getClassifierType().toString());\n// if (dtpanel.getClassifierType() == ClassifierType.SVM) {\n// SVMClassifierPanel pan = (SVMClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: kernel = \" + pan.getKernel().toString()\n// + \" C = \" + pan.getParameterC());\n// } else if (dtpanel.getClassifierType() == ClassifierType.DT) {\n// DTClassifierPanel pan = (DTClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: min num = \" + pan.getMinNum()\n// + \" confidence = \" + pan.getConfidence());\n// } else if (dtpanel.getClassifierType() == ClassifierType.KNN) {\n// KNNClassifierPanel pan = (KNNClassifierPanel) dtpanel.getSelectedClassifierPan();\n// System.out.println(\"user: KNN Value = \" + pan.getKNNValue());\n// }\n// System.out.println(\"selection type = \" + dtpanel.getSelectionType().toString());\n// System.out.println(\"crossover type = \" + dtpanel.getCrossOverType().toString());\n// System.out.println(\"mutation type = \" + dtpanel.getMutationType().toString());\n// System.out.println(\"replacement type = \" + dtpanel.getReplacementType().toString());\n// System.out.println(\"num iteration = \" + dtpanel.getNumIteration());\n// System.out.println(\"population size = \" + dtpanel.getPopulationSize());\n// System.out.println(\"crossover rate = \" + dtpanel.getCrossoverRate());\n// System.out.println(\"mutation rate = \" + dtpanel.getMutationRate());\n// System.out.println(\"K fold = \" + dtpanel.getKFolds());\n// }\n}\n"
},
{
"alpha_fraction": 0.6160714030265808,
"alphanum_fraction": 0.7410714030265808,
"avg_line_length": 21.399999618530273,
"blob_id": "eee76ef3692c1440b9fbc2d887fcc58f03999547",
"content_id": "223b228dd63900a3373a4322bbef3e0b30b6ffe8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 112,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 5,
"path": "/PhD_2019_01/primeira tentativa/VAR_25/250/script_r250n12tw10k4s.sh",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "#!/bin/bash \n#SBATCH --qos=qos-30d\n#SBATCH --partition=lamho-0\nmodule load jdk8_32\njava -jar r250n12tw10k4s.jar\n"
},
{
"alpha_fraction": 0.6321568489074707,
"alphanum_fraction": 0.6368627548217773,
"avg_line_length": 24.5,
"blob_id": "cd9918e4af341c8e8d7508f78f13985d355298ec",
"content_id": "6a5ab480ad114e50845c540ade9f3282f734ad81",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2550,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 100,
"path": "/PhD_2019_01/src/main/java/KFST/result/performanceMeasure/Criteria.java",
"repo_name": "renansantosmendes/PhD_2019_01",
"src_encoding": "UTF-8",
"text": "/*\n * Kurdistan Feature Selection Tool (KFST) is an open-source tool, developed\n * completely in Java, for performing feature selection process in different\n * areas of research.\n * For more information about KFST, please visit:\n * http://kfst.uok.ac.ir/index.html\n *\n * Copyright (C) 2016-2018 KFST development team at University of Kurdistan,\n * Sanandaj, Iran.\n *\n * This program 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 * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npackage KFST.result.performanceMeasure;\n\n/**\n * This java class is used to set different criteria values used in the feature\n * selection area of research.\n *\n * @author Sina Tabakhi\n */\npublic class Criteria {\n\n private double accuracy;\n private double errorRate;\n private double time;\n\n /**\n * initializes the parameters\n */\n public Criteria() {\n accuracy = 0;\n errorRate = 0;\n time = 0;\n }\n\n /**\n * This method sets the accuracy value.\n *\n * @param accuracy the accuracy value\n */\n public void setAccuracy(double accuracy) {\n this.accuracy = accuracy;\n }\n\n /**\n * This method returns the accuracy.\n *\n * @return the <code>accuracy</code> value\n */\n public double getAccuracy() {\n return accuracy;\n }\n\n /**\n * This method sets the error rate value.\n *\n * @param errorRate the error rate value\n */\n public void setErrorRate(double errorRate) {\n this.errorRate = errorRate;\n }\n\n /**\n * This method returns the error rate.\n *\n * @return the <code>error rate</code> value\n */\n public double getErrorRate() {\n return errorRate;\n }\n\n /**\n * This method sets the time value.\n *\n * @param time the time value\n */\n public void setTime(double time) {\n this.time = time;\n }\n\n /**\n * This method returns the time.\n *\n * @return the <code>time</code> value\n */\n public double getTime() {\n return time;\n }\n}\n"
}
] | 35 |
DrMorro228Pek/all_vk_reposts
|
https://github.com/DrMorro228Pek/all_vk_reposts
|
b0b558cc72e98ac57b7ff3e7fba2c7c6d3eba5b8
|
270a71d1611505a9f17e65ff17fa58dd65fc1d1b
|
ba17aba108df881740c38cea626829077c722e08
|
refs/heads/master
| 2020-12-03T06:52:34.942744 | 2020-01-09T04:28:10 | 2020-01-09T04:28:10 | 231,232,676 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4283595383167267,
"alphanum_fraction": 0.4512014091014862,
"avg_line_length": 32.75257873535156,
"blob_id": "cc748021c2bf880838efc0103d56554e9a77e781",
"content_id": "aa823f9cab002e0b65fd6162f0e43fecc7e822c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3908,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 97,
"path": "/all_vk_repost.py",
"repo_name": "DrMorro228Pek/all_vk_reposts",
"src_encoding": "UTF-8",
"text": "# coding: utf8\r\nimport vk_api\r\nimport re\r\nimport random\r\nimport time\r\nimport os\r\n\r\n# Группы которы чекаем\r\nvk_groups = [\"-97758272\", \"-109933725\", \"-126239339\", \"-105737219\", \"-125914421\"]\r\n\r\n# Кол-во записей которые проверяются, начиная сверху\r\ncount = 10\r\n\r\n# Авторизация\r\nvk_session = vk_api.VkApi(os.environ.get(\"LOGIN\"), os.environ.get(\"PASS\"))\r\nvk_session.auth()\r\n\r\n# Перебираем группы\r\nwhile True:\r\n for i in range(len(vk_groups)):\r\n \r\n result = vk_session.method(\"wall.get\",{\"owner_id\" : vk_groups[i], \"count\" : count, \"filter\" : \"owner\"})\r\n\r\n # Перебираем записи\r\n for j in range(count):\r\n \r\n # Получаем текст записи и id записи\r\n result_text = result[\"items\"][j][\"text\"].lower()\r\n result_id = result[\"items\"][j][\"id\"]\r\n \r\n # Видоизменяем для вк\r\n right_format_post_id = \"wall\" + vk_groups[i] + \"_\" + str(result_id)\r\n \r\n # Проверка на повторение\r\n f1 = open(\"yetUsed.txt\",\"r+\", encoding=\"utf-8\")\r\n flag = False\r\n for line in f1:\r\n if right_format_post_id == line.strip():\r\n flag = True\r\n print(right_format_post_id + \" уже репостилось\")\r\n break\r\n if flag:\r\n continue\r\n \r\n # Проверка на присутствие слов из белого списка\r\n f2 = open(\"whiteList.txt\", \"r+\", encoding=\"utf-8\")\r\n for line in f2:\r\n if result_text.find(line.strip()) == -1:\r\n flag = True\r\n else:\r\n flag = False\r\n print(\"Есть слово \" + line)\r\n break\r\n if flag:\r\n continue\r\n \r\n # Если не прошла проверки, переходим к следующей записе\r\n f2.close()\r\n \r\n # Если запись прошла проверки на повторение, то добавляем в уже зарепощенные\r\n f1.write(right_format_post_id + \"\\n\")\r\n f1.close()\r\n \r\n # Ищем спонсорскую группу и подписываемся на нее и делаем репост\r\n r = r\"\\d{9}\"\r\n try:\r\n sponsor_group_id = re.findall(r, result_text)[0]\r\n except:\r\n print(\"Отсутствует спонсораская группа: не конкурс - пропуск.\")\r\n continue\r\n \r\n # Вступаем\r\n try:\r\n vk_session.method(\"groups.join\", {\"group_id\" : sponsor_group_id})\r\n except:\r\n pass\r\n \r\n # Вывод доп инфы\r\n print(\"=======================================\")\r\n print(result_text + \"\\n\\n\")\r\n print(\"=======================================\") \r\n \r\n # Делаем репост\r\n try:\r\n vk_session.method(\"wall.repost\", {\"object\" : right_format_post_id })\r\n except:\r\n print(\"Достигнут лимит записей (>50)\")\r\n time.sleep(7200)\r\n continue\r\n \r\n print(\"Репостнул \" + right_format_post_id + \"и вступил в группу \" + sponsor_group_id + \"\\n\" )\r\n \r\n # Кд для записей\r\n time.sleep(120.0+random.random()*200.0)\r\n \r\n # Чекать раз в час \r\n time.sleep(3600)\r\n"
}
] | 1 |
ipe08291982/PythonCodes
|
https://github.com/ipe08291982/PythonCodes
|
c23c1782dbeb461d9e741dccfd65443bb6adce63
|
9f123c9bcd12bbca6261ab9c6d5631c1af7e2c85
|
d444b0b7d75112feca94c9566025c7f8421104f3
|
refs/heads/master
| 2020-06-06T11:28:28.439250 | 2019-06-19T12:47:28 | 2019-06-19T12:47:28 | 192,728,029 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5075075030326843,
"alphanum_fraction": 0.5135135054588318,
"avg_line_length": 19.8125,
"blob_id": "bbac3cd1754832fba3d23d33ee7f75d1da147dc2",
"content_id": "a6da4a63b1cc89cf299cfb802d657691922c7fb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 333,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 16,
"path": "/OddOrEven.py",
"repo_name": "ipe08291982/PythonCodes",
"src_encoding": "UTF-8",
"text": "\nmarker = False\nwhile marker == False:\n num = int(input(\"Enter a number: \"))\n ans = num % 2\n\n if ans == 0:\n print(\"The number is even\")\n else:\n print(\"The number is odd\")\n\n ask = input(\"Do you want to try again? [Y/N]: \")\n\n if ask.upper() == \"Y\":\n marker = False\n else:\n marker = True"
},
{
"alpha_fraction": 0.5175120830535889,
"alphanum_fraction": 0.5332125425338745,
"avg_line_length": 39.39024353027344,
"blob_id": "958dc0e00b18f5bcc907893b3019fabb9b4e14fe",
"content_id": "9530fb2baffb2f6d7b0a8be8ab81a0724ca6c6ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1656,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 41,
"path": "/RockPaperScissors.py",
"repo_name": "ipe08291982/PythonCodes",
"src_encoding": "UTF-8",
"text": "\nmarker = False\n\nname1 = input(\"Enter 1st player's name:\")\nname2 = input(\"Enter 2nd player's name:\")\n\nwhile marker == False:\n p1 = input(\"Enter your bet [(R)ROCK / (P)PAPER/ (S)SCISSORS]: \")\n p2 = input(\"Enter your bet [(R)ROCK / (P)PAPER/ (S)SCISSORS]: \")\n\n if p1.upper() == p2.upper():\n print(\"It's a Tie!!\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"R\" and p2.upper() == \"P\":\n print(name2.upper() + \" wins (Rock against Paper)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"R\" and p2.upper() == \"S\":\n print(name1.upper() + \" wins (Rock against Scissors)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"P\" and p2.upper() == \"R\":\n print(name1.upper() +\" wins (Paper against Rock)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"P\" and p2.upper() == \"S\":\n print(name2.upper() + \" wins (Paper against Scissors)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"S\" and p2.upper() == \"R\":\n print(name2.upper() + \" wins (Scissors against Rock)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n elif p1.upper() == \"S\" and p2.upper() == \"P\":\n print(name1.upper() + \" wins (Scissors against Paper)\\n\")\n ask = input(\"Want to play again? [Y / N]:\")\n else:\n print(\"Invalid Input!! You did not enter 'R' for Rock, 'S' for Scissors or 'P' for Paper!!\")\n\n if ask.upper() == \"Y\":\n marker = False\n elif ask.upper() == \"N\":\n marker = True\n else:\n marker = True\n\nprint(\"Thank you for playing! \")"
},
{
"alpha_fraction": 0.4447806477546692,
"alphanum_fraction": 0.4689863920211792,
"avg_line_length": 22.571428298950195,
"blob_id": "972528de8ead7ecfb5632c7981932e3abea457cf",
"content_id": "9683a38a757a8b77312413ee7ef8955436b63a68",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 661,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 28,
"path": "/MultipleAndDivisor.py",
"repo_name": "ipe08291982/PythonCodes",
"src_encoding": "UTF-8",
"text": "\ndef miltiple(num, num1):\n if num > num1:\n z = num\n else:\n z = num1\n\n while (True):\n if z%num==0 and z%num1==0:\n lcm=z\n break;\n z += 1\n return lcm\n\ndef divisor(num, num1):\n x = []\n i = 1\n j = min(num, num1)\n while i != j:\n if (num % i) == 0 and (num1 % i) == 0:\n x.append(i)\n i += 1\n return max(x)\n\na = int(input(\"Enter 1st number: \"))\nb = int(input(\"Enter 2nd number: \"))\n\nprint(\"The Least common multiple of \" + str(a) + \" and \" + str(b) + \" is: \",miltiple(a, b))\nprint(\"The Greatest common divisor of \" + str(a) + \" and \" + str(b) + \" is: \",divisor(a, b))\n"
}
] | 3 |
apfeiffer1/iCMS_testing
|
https://github.com/apfeiffer1/iCMS_testing
|
6bca86a2cab2eee9535dfb7354fb40a2d970b07a
|
d7c453693bda2ddc3e34db25d7fc40c8bacc9be5
|
0becad7d15766d936cd8e72295e0af90d7a4704d
|
refs/heads/main
| 2023-04-18T10:00:55.695817 | 2021-04-25T15:53:41 | 2021-04-25T15:53:41 | 353,250,903 | 0 | 0 | null | 2021-03-31T06:30:51 | 2021-03-31T06:30:41 | 2021-03-29T20:33:46 | null |
[
{
"alpha_fraction": 0.4875311851501465,
"alphanum_fraction": 0.49697184562683105,
"avg_line_length": 35.93421173095703,
"blob_id": "ed27e30f957e5940a7e8aec1629b02bdc609c331",
"content_id": "51c501f9910b6311b21dbb14a22a75c7c021c4f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 5614,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 152,
"path": "/cypress/support/commands.js",
"repo_name": "apfeiffer1/iCMS_testing",
"src_encoding": "UTF-8",
"text": "// ***********************************************\n// This example commands.js shows you how to\n// create various custom commands and overwrite\n// existing commands.\n//\n// For more comprehensive examples of custom\n// commands please read more here:\n// https://on.cypress.io/custom-commands\n// ***********************************************\n//\n//\n// -- This is a parent command --\n// Cypress.Commands.add(\"login\", (email, password) => { ... })\n\nCypress.Commands.add(\"login\", (login, password) => {\n cy.get(\"#kc-form-login\").within(() => {\n cy.get(\"input[tabindex=1]\").type(login);\n cy.get(\"input[tabindex=2]\").type(password);\n cy.get(\"input[tabindex=4]\").click();\n })\n})\n\nCypress.Commands.add(\"get_stat_dur\", (link, site_state) => {\n cy.request(link).then((resp) => {\n if (expect(resp).to.have.property(\"status\")) {\n site_state.status = resp.status;\n }\n if (expect(resp).to.have.property(\"duration\")) {\n site_state.duration = resp.duration;\n }\n })\n site_state.url = link;\n site_state.testing_date = Cypress.moment().format('MMM DD, YYYY');\n})\n\nCypress.Commands.add(\"check_tables\", (site_state) => {\n cy.get(\"main\").then(($body, $site_state) => {\n let t = [];\n let site = site_state;\n if ($body.find(\"table\").length) {\n if ($body.find(\".v-slide-group__wrapper\").length) {\n cy.get(\".v-slide-group__wrapper .v-tab\").as(\"tab_buttons\").click({\n multiple: true\n });\n cy.get(\"main table > tbody\").each(($tab, index0, $tables) => {\n cy.get(\"main table > tbody\").children().then((tr1) => {\n if (tr1.length <= 2) t.push(\"Table number \" + (index0 + 1) + \" is empty\");\n else t.push(\"Table number \" + (index0 + 1) + \" has content\");\n })\n })\n site.table = t;\n } else {\n cy.get(\"main table > tbody\").each(($tab, index0, $tables) => {\n cy.get(\"main table > tbody\").children().then((tr1) => {\n if (tr1.length <= 2) t.push(\"Table number \" + (index0 + 1) + \" is empty\");\n else t.push(\"Table number \" + (index0 + 1) + \" has content\");\n })\n })\n site.table = t;\n }\n } else {\n site_state.table = \"None\";\n }\n })\n})\n\nCypress.Commands.add(\"check_tables_epr\", (site_state) => {\n cy.get(\"div.container\").then(($body, $site_state) => {\n var t = [];\n var site = site_state;\n if ($body.find(\"table\").length) {\n cy.get(\"div.container table > tbody\").as(\"table_body\");\n cy.get(\"@table_body\").each(($tabs, index0, $tab) => {\n cy.get(\"@table_body\").eq(index0).children().then((tr) => {\n cy.get(\"@table_body\").eq(index0).children();\n if (tr.length <= 1) t.push(\"Table number \" + (index0 + 1) + \" is empty\");\n else t.push(\"Table number \" + (index0 + 1) + \" has content\");\n })\n site.table = t;\n })\n } else {\n site_state.table = \"None\";\n }\n })\n})\n\nCypress.Commands.add(\"wait_for_requests\", (alias, site_state) => {\n cy.wait(alias, {\n timeout: 40000\n }).then((xhr) => {\n if (xhr.status < 600 && xhr.status > 400) {\n site_state.late_errors.push(xhr.url + \" : \" + xhr.status + \" \" + xhr.statusMessage);\n }\n });\n})\n\nCypress.Commands.add(\"find_errors\", (site_state) => {\n cy.window().then((win) => {\n cy.stub(win.console, 'error', ($obj) => {\n\t if($obj.message != undefined){\n \t site_state.late_errors.push($obj.name + \" : \" + $obj.message);\n\t }\n\t else{\n\t\tsite_state.late_errors.push($obj);\n\t }\n });\n });\n})\n\nCypress.Commands.add(\"find_popup_alerts\", (site_state) => {\n cy.on('window:alert', ($obj) => {\n site_state.late_errors.push($obj);\n });\n})\n\nCypress.on('uncaught:exception', (err, runnable) => {\n // returning false here prevents Cypress from\n // failing the test\n return false;\n})\n\nCypress.Commands.add(\"select_year\", (alias = \"GET\", site_state, year_index) => {\n cy.get(\"div.navbar-collapse\").first().get(\"ul.navbar-nav\").first().as(\"header_menu\");\n cy.get(\"@header_menu\").children().eq(0).as(\"curr_opt\").click();\n cy.get(\"@curr_opt\").children().last().then(() => {\n\tcy.get(\"@curr_opt\").children().last().children(\"li\").not(\".required\").eq(year_index).click();\n });\n})\n\nCypress.Commands.add(\"click_navbar_elems\", (alias = \"GET\", site_state) => {\n cy.get(\"div.navbar-collapse\").first().get(\"ul.navbar-nav\").first().as(\"header_menu\");\n cy.get(\"@curr_opt\").click();\n cy.wait(2000);\n cy.get(\"@header_menu\").get(\"ul.nav > li.dropdown\", {\n timeout: 40000\n }).children().each(($li, index_li, $ul) => {\n $li[0].click();\n });\n})\n\nCypress.Commands.add(\"save_data\", (obj, base, year = 2021) => {\n var suburl = obj.url.replace(base, \"\");\n base = base.replace(\"//\", \"\");\n base = base.replaceAll(\"/\", \"_\");\n suburl = suburl.replaceAll(\"/\", \"_\")\n var path = \"data/\" + base;\n var json_path = path + \"/\" + suburl + \"/\" + String(year) + \"/\" + suburl + \"_\" + Cypress.moment().format(\"MM_DD_YYYY_h:mm\") + \".json\";\n cy.exec(\"mkdir -p \" + path);\n cy.exec(\"mkdir -p \" + path + \"/\" + suburl + \"/\");\n cy.exec(\"mkdir -p \" + path + \"/\" + suburl + \"/\" + String(year) + \"/\");\n cy.writeFile(json_path, obj);\n})\n"
},
{
"alpha_fraction": 0.7486910820007324,
"alphanum_fraction": 0.7486910820007324,
"avg_line_length": 13.692307472229004,
"blob_id": "0f59d708a21826ee438e95ab8595cc932f101b73",
"content_id": "4b20ec35bd6016a4ffec321a725587f5473472bd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 191,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 13,
"path": "/README.md",
"repo_name": "apfeiffer1/iCMS_testing",
"src_encoding": "UTF-8",
"text": "# iCMS_testing\n\n```terminal\ncd iCMS_testing\n\nnpm install\n\nnpm run cy:run \"cypress/integration\"\n\npython visualization.py ./data/tools_out.json\n\npython visualization.py ./data/epr_out.json\n```\n"
},
{
"alpha_fraction": 0.6100823283195496,
"alphanum_fraction": 0.6275720000267029,
"avg_line_length": 24.526315689086914,
"blob_id": "dcb715d2f4de6cb660c1729c5620c67cfa2ec0a7",
"content_id": "e3378504cbfe6e036872b16ef4240c4da8828930",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 972,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 38,
"path": "/data/visualization.py",
"repo_name": "apfeiffer1/iCMS_testing",
"src_encoding": "UTF-8",
"text": "import plotly.graph_objects as go\nfrom plotly.colors import n_colors\nimport dash\nimport dash_table\nimport numpy as np\nimport pandas as pd\nimport sys\n\ndata = pd.read_json(sys.argv[1])\ndataf = pd.DataFrame(data)\ndataf[\"table\"] = dataf[\"table\"].apply(lambda a: \", \".join(a) if a != \"None\" else None)\n\ncolumns = dataf.columns\n\ncolor = []\n\ncolor = dataf[\"late_errors\"].apply(lambda a: \"red\" if len(a) != 0 else \"lightgreen\")\ncolors = n_colors('rgb(255, 200, 200)', 'rgb(200, 0, 0)', 9, colortype='rgb')\n\napp = dash.Dash(__name__)\napp.layout = dash_table.DataTable(\n style_cell={\n\t'whiteSpace': 'normal',\n\t'height': 'auto',\n },\n columns=[{'id': c, 'name': c} for c in dataf.columns],\n data=dataf.to_dict('records'),\n style_data_conditional=[{\n\t'if': {\n\t 'column_id': 'late_errors',\n\t 'row_index': i\n\t},\n\t'backgroundColor': color[i],\n\t'color':'white'\n } for i in range(len(color.to_list()))],\n)\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n\n\n"
},
{
"alpha_fraction": 0.44077959656715393,
"alphanum_fraction": 0.4505247473716736,
"avg_line_length": 33.20512771606445,
"blob_id": "08a7ccd87a90f56c2972f50e3680ecb7aa8519e3",
"content_id": "50bafc3596952dc76cc47e61e01db6b63fe26fb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1334,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 39,
"path": "/cypress/integration/tools_test_spec.js",
"repo_name": "apfeiffer1/iCMS_testing",
"src_encoding": "UTF-8",
"text": "describe(\"Checking tools\", () => {\n var site_state = [];\n var base = \"https://icms-dev.cern.ch/tools/\";\n var n = 33;\n for (var j = 0; j < n; j++) {\n site_state.push({\n url: \"\",\n status: 0,\n duration: 0,\n table: [],\n late_errors: [],\n testing_date: \"\"\n });\n }\n for (let k = 0; k < n; k++) {\n it(\"Logs in and tests the pages\", () => {\n cy.server();\n cy.route(\"**/tools-api/restplus/**\").as(\"gets\");\n\t cy.readFile(\"cypress/fixtures/tools_links.json\").then(($link_obj) => {\n let links = $link_obj[0][\"links\"];\n let link = links[k];\n cy.get_stat_dur(link, site_state[k]);\n });\n cy.readFile(\"cypress/fixtures/tools_links.json\").then(($link_obj) => {\n let links = $link_obj[0][\"links\"];\n let link = links[k];\n cy.visit(link);\n });\n\t cy.login(\"login\", \"password\");\n\t cy.wait_for_requests(\"@gets\", site_state[k]);\n cy.find_errors(site_state[k]);\n\t cy.wait(10000);\n\t cy.check_tables(site_state[k]);\n console.log(site_state);\n cy.save_data(site_state[k], base);\n cy.writeFile(\"data/tools_out.json\", site_state);\n });\n }\n});\n"
},
{
"alpha_fraction": 0.4264892339706421,
"alphanum_fraction": 0.45564004778862,
"avg_line_length": 34.8636360168457,
"blob_id": "7d850b8aea7dd7fa4df3614ed29cb7da76b11976",
"content_id": "468feb6727569101670e70e263106c810e7f783b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1578,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 44,
"path": "/cypress/integration/epr_test_spec.js",
"repo_name": "apfeiffer1/iCMS_testing",
"src_encoding": "UTF-8",
"text": "describe(\"Checking epr\", () => {\n var site_state = [];\n var y = 0;\n var years = [2015, 2016, 2017, 2018, 2019, 2020, 2021];\n var n = 50;\n var base = \"https://icms-dev.cern.ch/epr/\";\n for (var j = 0; j < n; j++) {\n site_state.push({\n url: \"\",\n status: 0,\n duration: 0,\n table: \"\",\n late_errors: [],\n testing_date: \"\"\n });\n }\n for (let k = 0; k < n; k++) {\n it(\"Logs in and visits the page\", () => {\n cy.intercept('POST', 'https://icms-dev.cern.ch/epr/api/**').as('posts');\n cy.readFile(\"cypress/fixtures/epr_links.json\").then(($link_obj) => {\n let links = $link_obj[0][\"links\"];\n let link = links[k];\n cy.get_stat_dur(link, site_state[k]);\n });\n cy.readFile(\"cypress/fixtures/epr_links.json\").then(($link_obj) => {\n let links = $link_obj[0][\"links\"];\n let link = links[k];\n cy.visit(links[k]);\n });\n\t cy.login(\"login\", \"password\");\n cy.wait(4000);\n cy.get(\"body > div.container\", {\n timeout: 50000\n });\n\t cy.find_popup_alerts(site_state[k]);\n\t cy.select_year(\"@posts\", site_state[k], y);\n\t cy.click_navbar_elems(\"@posts\", site_state[k]);\n cy.check_tables_epr(site_state[k]);\n cy.writeFile(\"data/epr_out.json\", site_state);\n cy.save_data(site_state[k], base, years[y]);\n console.log(site_state);\n });\n }\n});\n"
}
] | 5 |
Zorro-Lin-7/My-Machine-Learning-Learning-Path
|
https://github.com/Zorro-Lin-7/My-Machine-Learning-Learning-Path
|
4986b2b3ee30797ec1264770b02f1c6b7ba6ec09
|
e798f75fb5946a6d3a5eafc9737d6e1d013e655b
|
3f0a02c1d7109be693d78c2df9e2d2e685cf780e
|
refs/heads/master
| 2021-01-01T06:40:17.068761 | 2018-04-04T00:04:53 | 2018-04-04T00:04:53 | 97,481,246 | 3 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.4004589915275574,
"alphanum_fraction": 0.456683874130249,
"avg_line_length": 19.761905670166016,
"blob_id": "6c06b7e5de2ae9d00c42877ddc67fae1089f286a",
"content_id": "17f727213eb185fcb01fe7eaf2f1ca1941d64235",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2598,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 84,
"path": "/LInear Algebra/Linear_Algebra_01_Matrix.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "#http://www.hahack.com/math/math-matrix/\n\nimport numpy as np\n\n\n-----------------------\n# 创建矩阵\na = np.matrix('5 2 3;\\\n 3 6 0')\n \nb = np.matrix('1 3 5 9; \\\n 2 5 6 2; \\\n 8 0 2 1')\n \n# 数值ndarray 与矩阵的转换\nb = a.getA() # 矩阵->数组 type(b)\nc = np.asmatrix(b) # 数组->矩阵 type(c)\n\n# 取出矩阵中的某个值\na[0,0] # 5\n------------------------\n\n# 矩阵运算\n# 加,减:矩阵的行数与列数必须完全相同,否则无定义\na = np.matrix('1 0 1;\\\n 1 2 1;\\\n 2 1 1')\nb = np.matrix('1 0 1;\\\n 1 2 1;\\\n 2 1 1')\n \na + b\n\n--------------\n# 乘法:充要条件是 第一个矩阵的n_columns = 第二个矩阵的 n_rows \na * b\n\n# 单位矩阵和零矩阵:类比数值1 和0。矩阵*单位阵 = 本身\nI = np.matrix(np.eye(3))\nz = np.matrix(np.zeros((3,2)))\n\n--------------\n# 除(求逆):A * A^-1 = I ; A的逆的逆 = A本身;可类比倒数,倒数与其他数相乘,就相当于除\n # 矩阵求逆有很多中方法,如伴随阵法、初等变化法(高斯·约当消去法)、分块矩阵求逆法\n # 初等变换法:(AI)->(IA^-1); (AI)成为A的增广矩阵\n #【矩阵的初等行变换】和 【初等列变换】 统称为【矩阵的初等变换】,包括:\n # 1、对调2行;\n # 2、k!=0 数乘某行\n # 3、数乘后加到某行\n # 矩阵A经过【有限次】初等变换变成B,那么A等价于B;\n\n # 奇异矩阵Singular matrix\n # 矩阵并不一定都可逆。从定义上,A可逆的充要条件是 A非奇异。公式上有1/|A|,只要矩阵M的行列式|A|=0,则除零无意义。\n # 所以,若|A|=0,则A为奇异矩阵;否则为非奇异矩阵\n\na = np.matrix('1 0 1; 1 2 1; 2 1 1')\na.I # 求逆\na * a.I \na.I * a\n \nsingular = np.matrix('0 1; 0 0')\nf.I # 会报错\n\n--------------------------\n# 矩阵的转置 \na = np.matrix('2 4;1 3')\nb = np.matrix('1 6;2 4')\n\n(a * b).T == a.T * b.T\n\n# 应用举例\n # 求解二元方程组 \n # { 3x + 2y = 7; \n # -x + y = 1 }\n a = np.matrix('3 2;-1 1')\n b = np.matrix('7;1')\n solve = a.I * b\n \n # 二元一次矩阵求解简单,那么更高维,有成百上千个未知数呢? np的子库linalg\n np.linalg.solve(a, b)\n ------\n \n # 假设有向量a=[3;1], b=[2;1], 求如何组成c=[7;1]\n # 用x, y 分别表示2个向量的倍数(线性组合的系数),问题转换为 [3;-1]x + [2;1]y = [7;1],与上例完全同构。"
},
{
"alpha_fraction": 0.6929824352264404,
"alphanum_fraction": 0.6929824352264404,
"avg_line_length": 37.33333206176758,
"blob_id": "25c857e06bee16f2d54a4ad0678c6ba2e7691a2d",
"content_id": "85e718133ffd3d2daa2b57cc3f09cde5c9a28e2d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 114,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 3,
"path": "/NLP/Mastering NLP with Python/Chapter01/obtain_input_and_tokenization.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "import nltk\nr = input('Please write a text: ')\nprint(\"The length of text is\", len(nltk.word_tokenize(r)), 'words')"
},
{
"alpha_fraction": 0.6010498404502869,
"alphanum_fraction": 0.6305774450302124,
"avg_line_length": 19.039474487304688,
"blob_id": "f41f0c6c9e968afcc192cede5b681b9e1cdbf21d",
"content_id": "3cafa77fd63774216a472786bf4edbc3f7ce3e9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2966,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 76,
"path": "/LInear Algebra/Linear_Algebra_02_Vector.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "# 来源:http://www.hahack.com/math/math-vector/\n\n'''\n向量是机器学习中的基础数据表示形式,例如计算机阅读文本的过程首先会将文本分词,然后用向量表示。这是因为\n向量很适合在高维空间中表达和处理。机器学习中,诸如投影、降维的概念,都是在向量的基础上做的。\nNumpy 中,直接用ndarray 表示向量。\n'''\nimport numpy as np\n\n# 加减\na = np.array([-1, 2])\nb = np.array([3, 1])\na + b\na - b # 几何上,减向量相当于加上一个反向的向量\n-------------\n# 乘法\n # 标量 x 向量\nprint(a * 3)\n---------\n# 向量点积(向量 x 向量)= 标量\nproduct = a.dot(b) # 注:不是 * 运算\nproduct = np.dot(a,b)\n\n # 向量长度\na_len = np.sqrt(a.dot(a))\n\n # 柯西不等式:对2个非0向量x,y, 有 |xy|<=|x||y|; 当且仅当x=cy 时取等号。 非常重要。\n ''' 从几何的角度来说,向量的点积与向量间夹角θ的余弦有关:ab = |a||b|cosθ\n 点积反映了向量a在b上的投影,即两个向量在同一方向上的相同程度。\n 当2个向量正交时,cosθ = 0,点积=0,投影最小;\n 当2个向量平行时,cosθ = 1,点积最大,投影也最大\n '''\n---------\n#向量外积:列向量x行向量 称作向量的外积\n'''\n向量外积,又叫叉乘、叉积、向量积。得到的是向量,且垂直与2个原向量组成的平面,即法向量。\n一个作用是得到一个和a, b 两个原向量正交的向量c。\n几何意义,外积与sinθy有关:aXb = |a||b|sinθ\n意味着,外积反映了a与b的正交程度。\n当2个向量平行时,sinθ = 0,外积 = 0,正交程度最小;\n当2个向量正交时,sinθ = 1, 外积最大,正交程度最大\n'''\na = np.array([3, 5, 2])\nb = np.array([1, 4, 7])\nprint(np.cross(a, b))\n\n-----------\n# 矩阵向量积:矩阵x向量\n'''\n矩阵的所有列向量的线性组合,向量的每个分量是每列的权值。\n√ 一个矩阵其实就是一个线性变换。一个矩阵乘以一个向量后得到的向量,相当于将这个向量进行了线性变换。\n'''\n\na = np.matrix('4 3 1;1 2 5')\nx = np.array([[5], [2], [7]])\nprint(a*x) # 可以直接*\n\n------------------\n# 向量的转置\n\na = np.array([[2, 4]]) # 注意,用了2个[]以生成二维向量\na.T\nb = np.array([2, 4]) # 一维的转置不会变化\nb.T \n\n------\n# 线性无关\n'''\n一组向量的张成空间,指这些向量随便线性组合后,能够表示多少个向量。记为span(a,b)。\n\n当一个向量集合里的每个向量都对张成的空间有贡献,没有多余向量时,称这个向量集合线性无关。\n换句话说,存在一个向量,可由其他向量线性组合得到,该向量即多余。反之线性相关。\n例如,a = [1;2],b=[3,4],c = 2a =[2;4]。{a,b}张成的空间与{a,b,c}张成的空间一样,c是多余的,a、c线性相关。\n\n能够表示一个空间的最少向量组合,成为空间的基。\n'''\n\n"
},
{
"alpha_fraction": 0.653093159198761,
"alphanum_fraction": 0.6671887040138245,
"avg_line_length": 25.081632614135742,
"blob_id": "9a9ad0d8192d27641ae68b9163592f82379a8020",
"content_id": "b36d00b730cf7916a15cafb3a58719e6837fe745",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1503,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 49,
"path": "/NLP/NLTK Essentials/Chapter01/diving_to_nltk_python2.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\n# 重要:python2 必须要有上述编码声明\n\n# python2 不用NLTK的方式,提取文本并分词\n\nimport urllib2\n\nresponses = urllib2.urlopen(\"http://python.org/\") # 下载网页数据\nhtml = responses.read() # 读取网页数据(包含hmtl)\nprint len(html)\n\n# tokens = [tok for tok in html.split()] #分词\n# print \"Total number of tokens :\"+ str(len(tokens)) #统计词数\n# print tokens[0:20] \n# 除了文本内容,还含有html标签,需要再清洗,以下用re直接剥离提炼\n\nimport re\n\ntokens = re.split(\"\\W+\", html)\nprint \"Total number of tokens : {}\".format(len(tokens))\nprint tokens[:20]\n\n# 上述方式可以用nltk 实现得更简洁\n\n# 词频统计及排序-字典按value排序\n# python 方式:\nimport operator\nfreq_dis = {}\nfor tok in tokens:\n if tok in freq_dis:\n freq_dis[tok] += 1\n else:\n freq_dis[tok] = 1\nsorted_freq_dist = sorted(freq_dis.items(), key = operator.itemgetter(1), reverse=True)\nprint sorted_freq_dist[:20]\n\n# NLTK 方式:\nimport nltk\nFreq_dist_nltk = nltk.FreqDist(tokens)\nprint Freq_dist_nltk\nprint('\\n--------------')\nfor k, v in Freq_dist_nltk.items():\n print str(k) + ':' + str(v)\n\n# stopwords\n# stopwords = [word.strip().lower() for word in open(\"PATH/english.stop.txt\")] # 需要停用词库\n# clean_tokens = [tok for tok in tokens if len(tok.lower()) > 1 and (tok.lower() not in stopwords]\n# Freq_dist_nltk = nltk.FreqDist(clean_tokens) \n# Freq_dist_nltk.plot(50, cumulative=False)"
},
{
"alpha_fraction": 0.6397941708564758,
"alphanum_fraction": 0.6397941708564758,
"avg_line_length": 31.27777862548828,
"blob_id": "311e60420eb302957cfb0fd27059d1b858aca03b",
"content_id": "a3a46c4f690f6589e79dfcff69c95b8256c2fb6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1166,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 36,
"path": "/NLP/Mastering NLP with Python/Chapter07/preprocessing_of_text.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "import nltk\nfrom nltk.stem import WordNetLemmatizer\n\n\nclass Splitter(object):\n def __init__(self):\n self.nltk_splitter = nltk.data.load('tokenizers/punkt/english.pickle')\n self.nltk_tokenizer = nltk.tokenize.TreebankWordTokenizer()\n \n def split(self, text):\n sentences = self.nltk_splitter.tokenize(text)\n tokenized_sentences = [self.nltk_tokenizer.tokenize(sent) for sent in sentences]\n return tokenized_sentences\n \nclass PosTagger(object):\n def __init__(self):\n pass\n \n def pos_tag(self, sentences):\n pos = [nltk.pos_tag(sentence) for sentence in sentences]\n pos = [[(word, WordNetLemmatizer().lemmatize(word), [postag]) for (word, postag) in sentence] for sentence in pos]\n \n return pos\n \n \nif __name__ == \"__main__\":\n text = \"\"\"\n Why are you looking disappointed. We will go to restaurant for dinner.\n \"\"\"\n splitter = Splitter()\n postagger = PosTagger()\n splitted_sentences = splitter.split(text)\n print(splitted_sentences)\n \n pos_tagged_sentence = postagger.pos_tag(splitted_sentences)\n print(pos_tagged_sentence)\n "
},
{
"alpha_fraction": 0.6198686361312866,
"alphanum_fraction": 0.6321839094161987,
"avg_line_length": 38.32258224487305,
"blob_id": "5d6d3a1610aa802b75bfaed1e76a7d1f08bd70f0",
"content_id": "1d8cd8edf09a4ac21dc6f9c8cb7954509b46dcc1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1314,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 31,
"path": "/RealWorldMachineLearning/Chapter6/gender_identification.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "import random\nfrom nltk.corpus import names\nfrom nltk import NaiveBayesClassifier\nfrom nltk.classify import accuracy as nltk_accuracy\n\n# To define a function to extract features from input words\n# 名字的最后几个字母作为特征\ndef gender_features(word, num_letters=2): \n return {'feature': word[-num_letters:].lower()}\n \nif __name__ == '__main__':\n # training data:\n labeled_names = ([(name, 'male') for name in names.words('male.txt')]\n + [(name, 'female') for name in names.words('female.txt')])\n random.seed(7)\n random.shuffle(labeled_names) \n \n # test data:\n input_names = ['Leonardo', 'Amy', 'Sam']\n \n # 因为我们不知道该截取的词尾长度,所以我们将遍历parameter space from 1 to 5,看看用哪个的准确度最高\n for i in range(1, 5):\n print(\"\\nNumber of letters:\", i)\n feature_sets = [(gender_features(n, i), gender) for (n, gender) in labeled_names]\n train_set, test_set = feature_sets[500:], feature_sets[:500]\n classifier = NaiveBayesClassifier.train(train_set)\n print(\"Accuracy ==>\", str(100 * nltk_accuracy(classifier, test_set)) +str('%'))\n \n # Predict\n for name in input_names:\n print(name, \"==>\", classifier.classify(gender_features(name, i)))"
},
{
"alpha_fraction": 0.6573367118835449,
"alphanum_fraction": 0.6675148606300354,
"avg_line_length": 31.75,
"blob_id": "3664618e228c80b51fb495510b3c128b8c62739a",
"content_id": "b85a7228acb21f4a5a6f5c4215c20c254a47dbfe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1347,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 36,
"path": "/NLP/NLTK Essentials/Chapter01/python3_NLTK.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "# -*- coding: UTF-8 -*-\n# python3\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\nweb_data = requests.get(\"http://python.org/\") # get 整个网页元数据\npython_html = web_data.text # 元数据中提取html部分的文本\nsoup = BeautifulSoup(python_html,'lxml') # 解析html文本,好比 混合物状态的汤 变成 分层的汤\nclean = soup.get_text() #从“分层”的汤里,提取“html文本”这一层 \n# print(clean)\ntokens = [tok for tok in clean.split()]\nprint(\"Total number of tokens: {}\".format(len(tokens)))\nprint(tokens[:25])\nprint(\"\\n---------------\")\n# 对比:用re貌似提纯度更高,也可能分词更细导致噪音增加\ntokens_by_re = re.split(\"\\W+\", clean)\nprint(\"Total number of tokens_by_re: {}\".format(len(tokens_by_re)))\nprint(tokens_by_re[:25])\n\nimport nltk\nFreq_dist_nltk = nltk.FreqDist(tokens) # 词频统计\nprint(Freq_dist_nltk)\nprint(\"\\n------------\")\nfor k, v in Freq_dist_nltk.items():\n print(str(k) + ':' + str(v))\n\n# stopwords exist\nFreq_dist_nltk.plot(50, cumulative=False)\n\n# no stopwords\n# stopwords = [word.strip().lower() for word in open(\"PATH/english.stop.txt\")]\n# clean_tokens = [tok for tok in tokens if len(tok.lower()) > 1 and (tok.lower() not in stopwords)]\n# Freq_dist_nltk = nltk.FreqDist(clean_tokens)\n# Freq_dist_nltk.plot(50, cumulative=False)\n"
},
{
"alpha_fraction": 0.5444191098213196,
"alphanum_fraction": 0.5489749312400818,
"avg_line_length": 19,
"blob_id": "b26cf28097cf62de28461fb067f7dbf6dadca583",
"content_id": "4a2db0ff43757a45f8bd316abd7c6ff81862da31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 439,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 22,
"path": "/NLP/NLTK Essentials/Chapter01/mywordfreq.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "import sys\n\ndef wordfreq(mystring):\n \"\"\"\n Function to generated the frequency distribution of the given text.\n \"\"\"\n print(mystring)\n word_freq = {}\n for tok in mystring.split():\n if tok in word_freq:\n word_freq[tok] += 1\n else:\n word_freq[tok] = 1\n print(word_freq)\n \ndef main():\n str = \"This is my first NLP program!\"\n wordfreq(str)\n\n\nif __name__ == '__main__':\n main()"
},
{
"alpha_fraction": 0.6892988681793213,
"alphanum_fraction": 0.7040590643882751,
"avg_line_length": 35.14666748046875,
"blob_id": "d5c69ee090584918959b66fd2bf2486391456b02",
"content_id": "e17239b597aa229e269cd6f8cc2d1a2493b61376",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2778,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 75,
"path": "/RealWorldMachineLearning/Chapter1/RidgeRegression.py",
"repo_name": "Zorro-Lin-7/My-Machine-Learning-Learning-Path",
"src_encoding": "UTF-8",
"text": "import sys\nimport numpy as np\n\nfilename = sys.argv[1]\n\nX = []\ny = []\nwith open(filename, 'r') as f:\n for line in f.readlines():\n data = [float(i) for i in line.split(',')]\n xt, yt = data[:-1], data[-1]\n X.append(xt)\n y.append(yt)\n \n# Train/test split\nnum_training = int(0.8 * len(X))\nnum_test = len(X) - num_training\n\n# Training data\n# X_train = np.array(X[:num_training]).reshape((num_training,1))\nX_train = np.array(X[:num_training])\ny_train = np.array(y[:num_training])\n\n# Test data\nX_test = np.array(X[:num_test])\ny_test = np.array(y[:num_test])\n\n# Ridge regression\n# Create linear regression object\nfrom sklearn import linear_model\n\nlinear_regressor = linear_model.LinearRegression()\nridge_regressor = linear_model.Ridge(alpha=0.01, fit_intercept=True, max_iter=10000)\n\nlinear_regressor.fit(X_train, y_train)\nridge_regressor.fit(X_train, y_train)\n\n# Predict the output\ny_test_pred = linear_regressor.predict(X_test)\ny_test_pred_ridge = ridge_regressor.predict(X_test)\n\n# Measure performance\nimport sklearn.metrics as sm\n\nprint(\"LINEAR:\")\nprint(\"Mean absolute error =\", round(sm.mean_absolute_error(y_test, y_test_pred),2))\nprint(\"Mean squared error =\", round(sm.mean_squared_error(y_test, y_test_pred), 2))\nprint(\"Median absolute error =\", round(sm.median_absolute_error(y_test, y_test_pred), 2))\nprint(\"Explained variance score=\", round(sm.explained_variance_score(y_test, y_test_pred), 2))\nprint(\"R2 score =\", round(sm.r2_score(y_test, y_test_pred), 2))\n\n\nprint(\"\\nRIDGE:\")\nprint(\"Mean absolute error =\", round(sm.mean_absolute_error(y_test, y_test_pred_ridge),2))\nprint(\"Mean squared error =\", round(sm.mean_squared_error(y_test, y_test_pred_ridge), 2))\nprint(\"Median absolute error =\", round(sm.median_absolute_error(y_test, y_test_pred_ridge), 2))\nprint(\"Explained variance score =\", round(sm.explained_variance_score(y_test, y_test_pred_ridge), 2))\nprint(\"R2 score =\", round(sm.r2_score(y_test, y_test_pred_ridge), 2))\n\n# print(y_test_pred)\n# print(\"\\n-------------------\")\n# print(y_test_pred_ridge)\n\n# Polynomial regression\nfrom sklearn.preprocessing import PolynomialFeatures\n\npolynomial = PolynomialFeatures(degree=3) # 设置最高项次\nX_train_transformed = polynomial.fit_transform(X_train) # to represent the datapoints in terms of the coefficients of the polynomial\ndatapoint = [0.39, 2.78, 7.11] # 给定新的数据点\npoly_datapoint = polynomial.fit_transform(datapoint) # 将新数据点做预处理\n\npoly_linear_model = linear_model.LinearRegression() # 线性回归\npoly_linear_model.fit(X_train_transformed, y_train) # 拟合多元线性回归\nprint(\"\\nLinear regression:\\n\", linear_regressor.predict(datapoint)[0])\nprint(\"\\nPolynomial regression:\\n\", poly_linear_model.predict(poly_datapoint)[0])"
}
] | 9 |
zhougui-QAQ/Mypython-project
|
https://github.com/zhougui-QAQ/Mypython-project
|
025443e2748a1e85e7d9b9ad8d06117f88a7d856
|
a0adb0136264869a42fcd18efe65e5b8f62257aa
|
32bc0b7607301f05f548b6b752c8657658c221ad
|
refs/heads/master
| 2022-11-12T04:01:23.240585 | 2020-06-30T12:41:56 | 2020-06-30T12:41:56 | 269,854,452 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.5990098714828491,
"alphanum_fraction": 0.5990098714828491,
"avg_line_length": 24.25,
"blob_id": "33aa7489bffb4b016841cac04ea381428446c058",
"content_id": "aef465dd9318c97c54e8236fae689c2ecc6ba6a4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 236,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 8,
"path": "/File search.py",
"repo_name": "zhougui-QAQ/Mypython-project",
"src_encoding": "UTF-8",
"text": "import shutil\nimport os\npath = 'xxx'#你的目录\nfiles = os.listdir(path)\nfor f in files:\n if 'xx'in f and f.endswith('.py'):#文件名和后缀\n print('yes ' + f)\n shutil.copy('xx', 'xxx')#复制 目录文件到xxx\n"
}
] | 1 |
RamIIITA/Solutions
|
https://github.com/RamIIITA/Solutions
|
0b92ba46c9baabfe2bab38feae888d2ce333b164
|
1bec3dafd848f36cee2da3baf05898e6d6ffed1e
|
22f1f1d612d440f3fde5ae36963d2cf9fb00ea25
|
refs/heads/master
| 2020-09-22T23:02:22.137958 | 2019-12-02T09:59:07 | 2019-12-02T09:59:07 | 225,339,417 | 0 | 0 | null | null | null | null | null |
[
{
"alpha_fraction": 0.41610169410705566,
"alphanum_fraction": 0.4372881352901459,
"avg_line_length": 20.071428298950195,
"blob_id": "599eb620b4c74d2f655807c23558c0761979ee50",
"content_id": "c6001ccd457f99c0ebda6791efc67f54fda52041",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1180,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 56,
"path": "/reminders of the factorial.py",
"repo_name": "RamIIITA/Solutions",
"src_encoding": "UTF-8",
"text": "#code is written in python3\n#Fac Function results facotrial for a particular number\n\ndef fact(n):\n Sum = 1\n if n<3:\n return n\n for i in range(2,n+1):\n Sum*=i\n return Sum\n\n#solution part\ndef sol(n):\n temp = 1\n fac = [0,1]\n dic_fac = {1:1,2:2,0:0}\n for i in range(2,n):\n factor = fact(i)\n temp+=(factor*i)\n dic_fac[i] = factor\n fac.append(i)\n if n<temp:\n break\n \n ans=dict()\n for i in fac:\n ans[i]=0\n \n while(n):\n for i in reversed(fac):\n for j in range(i,-1,-1):\n if (j*dic_fac[i]) <= n:\n n-=(j*dic_fac[i])\n ans[i] = j\n break\n if n<1:\n break\n \n if n<1:\n break\n result = \"\"\n for i in sorted(ans.keys(), reverse = True):\n result=result+str(ans[i])+\" \"\n return result\n \n#checking the base conndition \ndef fun(n):\n if n<1:\n return 0\n if n<2:\n return str(1)+\" \"+str(0)\n return sol(n)\n\nif __name__=='__main__':\n n = int(input(\"Enter the number: \"))\n print(fun(n))\n"
}
] | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.