query
stringlengths
9
3.4k
document
stringlengths
9
87.4k
metadata
dict
negatives
listlengths
4
101
negative_scores
listlengths
4
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
Gets the average GPS coordinates of the rough address interval
def selective_geocode(rough_address: str) -> dict: lat_results = []; lon_results = [] found = re.findall(r"\d+~\d+", rough_address) if not found: raise geo.AddressError(geo.__name__, rough_address) bound = [int(i) for i in found[0].split('~')] if bound[0] > bound[1]: raise geo.AddressError(geo.__name__, rough_address) interval = int((bound[1] - bound[0] + 1) / settings.GEO_SAMPLES) samples = [i for i in range(bound[0], bound[1] + 1, interval)] for sample in samples: query_address = rough_address.replace(found[0], str(sample)) gps_coordinates = geo.geocode(query_address, culture='zh-TW')["GPS"] if gps_coordinates["lat"] and gps_coordinates["lon"]: lat_results.append(gps_coordinates["lat"]) lon_results.append(gps_coordinates["lon"]) return {"lat": lat_results, "lon": lon_results}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gavg(idata):\n\t\n\twgt1=np.cos(np.deg2rad(idata.lat))*(idata*0+1)\n\tga=(wgt1*idata).sum(dim=['lat','lon'])/wgt1.sum(dim=['lat','lon'])\n\n\treturn ga", "def _get_lat_avg(self, report):\n match = re.search(\"\\s*lat\\s*\\((\\w+)\\).*avg\\=\\s*(\\d+\\.{0,1}\\d*)\",\n report)\n if...
[ "0.66684115", "0.66580987", "0.6334983", "0.62975043", "0.61769515", "0.61367", "0.60557425", "0.6047087", "0.6028656", "0.59404755", "0.57874817", "0.57128465", "0.57006764", "0.5697978", "0.5691043", "0.5690729", "0.5679087", "0.56297153", "0.5596291", "0.55928093", "0.5568...
0.5241144
57
Geocode address of the same county in quarter fashion
def partition_geocode(con: sqlite3.Connection, cur: sqlite3.Cursor, quarter: str, county_cht: str): cur.execute('''SELECT 土地區段位置或建物區門牌 FROM "{0}/TRX" WHERE 縣市 = ? GROUP BY 土地區段位置或建物區門牌;'''.format(quarter), (county_cht,)) for address, in cur.fetchall(): cur.execute('''SELECT GEO.編號 FROM "{0}/TRX" AS TRX, "{0}/GEO" AS GEO WHERE TRX.編號 = GEO.編號 AND TRX.土地區段位置或建物區門牌 = ? AND GEO.LAT_Avg ISNULL;'''.format(quarter), (address,)) identities = cur.fetchall() if not identities: continue print("[%d] "%(len(identities)) + address) try: results = selective_geocode(address) except geo.AddressError: continue if len(results["lat"]) != 5 or len(results["lon"]) != 5: continue results["lat"].append(sum(results["lat"]) / len(results["lat"])) results["lon"].append(sum(results["lon"]) / len(results["lon"])) combined = [num for zipped in zip(results["lat"], results["lon"]) for num in zipped] values = [(tuple(combined) + identity) for identity in identities] cur.executemany('''UPDATE "{0}/GEO" SET LAT_1 = ?, LON_1 = ?, LAT_2 = ?, LON_2 = ?, LAT_3 = ?, LON_3 = ?, LAT_4 = ?, LON_4 = ?, LAT_5 = ?, LON_5 = ?, LAT_Avg = ?, LON_Avg = ? WHERE 編號 = ?;'''.format(quarter), values) con.commit()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def geo_coder(house_number, boro_code, street_name, zip_code): \r\n wa1 = '1B{}{}{}{}{}C{}{}'.format(rightpad(house_number, 16), rightpad('', 38), boro_code, rightpad('', 10), rightpad(street_name, 32), rightpad('', 113), rightpad(zip_code, 5))\r\n wa1 = rightpad(wa1, 1200)\r\n wa2 = rightpad('', 4300...
[ "0.6251422", "0.6227843", "0.60835624", "0.59131515", "0.585577", "0.5806368", "0.57388103", "0.5738554", "0.5722705", "0.5614146", "0.5594229", "0.55850214", "0.5574379", "0.5574237", "0.5490394", "0.54893243", "0.5472008", "0.5418318", "0.5418175", "0.53998554", "0.5397736"...
0.6954527
0
fit offset gaussian, with offset, amplitude, and sigma constrained to be positive
def fitgauss(bin_edges, counts, guess): """sigma is constrained to be >= one bin width""" """unless guess[3] < 0, then offset set to zero""" bincen = np.zeros(np.size(bin_edges)-1) bincen[:] = bin_edges[0:np.size(bin_edges)-1] binstep = bin_edges[2]-bin_edges[1] bincen += binstep/2 #print(bincen) #print(counts) #plt.plot(bincen, counts, label = 'data') #plt.show() if(guess[3]>0): #allow y_offset coeff, var_matrix = curve_fit(gauss, bincen, counts, guess, bounds=([0,-np.inf, binstep, 0],[np.inf,np.inf, np.inf, np.inf])) [A, mu, sigma, yoff] = coeff else: #force y_offset to be zero - pure gaussian coeff, var_matrix = curve_fit(puregauss, bincen, counts, guess[0:3], bounds=([0,-np.inf, binstep],[np.inf,np.inf, np.inf])) [A, mu, sigma] = coeff yoff = 0.0 c_exp = gauss(bincen, A, mu, sigma, yoff) resid2 = sum((c_exp - counts)**2) #print coeff # print var_matrix #display check #hist_fit=gauss(bincen, *coeff) #plt.plot(bincen, counts, label='data') #plt.plot(bincen, hist_fit, label='fit') #plt.show() return [A, mu, sigma, yoff, resid2]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def gaussian(x, *parameters):\n position, sigma, amplitude, background = parameters\n return amplitude * np.exp(-(x - position)**2 / (2.0 * sigma**2)) + background", "def gaussian(mu, wid, x):\n return np.exp(-((x - mu) / (0.6005612 * wid))**2)", "def Gaussian(x, mu=0, sigma=26.4, A=1, y0=0):\r\n #...
[ "0.68242663", "0.6790471", "0.67830956", "0.67823905", "0.67808473", "0.67197216", "0.67171425", "0.661976", "0.6550336", "0.6550336", "0.6507729", "0.64968884", "0.64913034", "0.64834434", "0.64469576", "0.6435371", "0.6381322", "0.6359356", "0.63252896", "0.6323852", "0.630...
0.5754527
87
method catches all requests that are not api requests ensures routing possibilities within VUE
def catch_all(path=''): return render_template('index.html')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def serve(self, request, *args, **kwargs):\n raise Http404", "def serve(self, request, *args, **kwargs):\n raise Http404", "def serve(self, request, *args, **kwargs):\n raise Http404", "def serve(self, request, *args, **kwargs):\n raise Http404", "def serve(self, request, *args,...
[ "0.55937976", "0.55937976", "0.55937976", "0.55937976", "0.55937976", "0.5476229", "0.5457845", "0.5313464", "0.5251401", "0.5202117", "0.5182233", "0.5172451", "0.51495206", "0.51472974", "0.51144993", "0.5110918", "0.5094427", "0.50860524", "0.50750285", "0.5068474", "0.505...
0.0
-1
This creates the generator object yielding squares of the number
def generate_square_number(square_limit): for i in range(0,square_limit): yield i**2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def square_numbers_2(nums):\n for i in nums:\n yield(i*i)", "def perfect_sq_seq_gen(num):\n for i in range(num):\n yield i ** 2", "def gensquares(n):\n for number in my_range.my_range(n): # note that we are NOT calling range(N), we implemented our own my_range() generator\n yiel...
[ "0.76812726", "0.7570587", "0.7127406", "0.7013921", "0.6935942", "0.6566116", "0.65498954", "0.65378404", "0.65034443", "0.6499686", "0.64733166", "0.6452493", "0.6364364", "0.6352053", "0.6324538", "0.63203084", "0.62623084", "0.6218521", "0.6207027", "0.6205454", "0.619938...
0.7852594
0
r"""One could also use the Laplacian of Gaussian formula to design the filter.
def laplacian_1d(window_size) -> torch.Tensor: filter_1d = torch.ones(window_size) filter_1d[window_size // 2] = 1 - window_size laplacian_1d: torch.Tensor = filter_1d return laplacian_1d
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def filter(self, op=GaussianFilter):\n\n if self._verbose > 0:\n print(\"Filtering...\")\n\n # Import from utils specified params.\n params = get_filtering_params()\n\n negative = self.image_raw - op(sigma=params['sigma_bgd']).convolve(self.image_raw)\n\n self.image_fi...
[ "0.66963106", "0.65597415", "0.6478427", "0.636755", "0.6351325", "0.6253081", "0.62316626", "0.62082386", "0.617469", "0.61242366", "0.6101194", "0.6060973", "0.60049284", "0.600304", "0.60001606", "0.59720194", "0.59712464", "0.59702766", "0.5951012", "0.59331256", "0.59309...
0.0
-1
r"""Function that returns the coefficients of a 1D Laplacian filter
def get_laplacian_kernel(kernel_size: int) -> torch.Tensor: if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ kernel_size <= 0: raise TypeError("ksize must be an odd positive integer. Got {}" .format(kernel_size)) window_1d: torch.Tensor = laplacian_1d(kernel_size) return window_1d
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _laplacian_to_image(lpyr, filter_vec, coeff):\n im = lpyr[-1]\n filter_vec = filter_vec.reshape(filter_vec.size, 1)\n for i in reversed(range(len(lpyr) - 1)):\n im = _expand(im, filter_vec) + coeff[i] * lpyr[i]\n\n return im", "def slip_to_coefficients(x, y, a):\n partials = np.zeros((x...
[ "0.63450897", "0.59707314", "0.56549406", "0.5654393", "0.56457824", "0.5604039", "0.55629796", "0.554021", "0.55173355", "0.55153257", "0.54377836", "0.54277223", "0.5426681", "0.53971505", "0.538953", "0.5377202", "0.5352815", "0.53502446", "0.534966", "0.53384006", "0.5319...
0.0
-1
r"""Function that returns Gaussian filter matrix coefficients.
def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor: if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \ kernel_size <= 0: raise TypeError("ksize must be an odd positive integer. Got {}" .format(kernel_size)) kernel = torch.ones((kernel_size, kernel_size)) mid = kernel_size // 2 kernel[mid, mid] = 1 - kernel_size ** 2 kernel_2d: torch.Tensor = kernel return kernel_2d
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _gaussian(self, c, sigma):\n d = 2*sigma*sigma\n ax = exp(-power(self._xx-self._xx.T[c], 2)/d)\n ay = exp(-power(self._yy-self._yy.T[c], 2)/d)\n return (ax * ay).T # the external product gives a matrix", "def apply_gaussian(X, sigma):\n return np.array([ndimage.gaussian_filter...
[ "0.64841884", "0.6266498", "0.6249518", "0.59057564", "0.5897109", "0.5803587", "0.57633173", "0.5752097", "0.56212413", "0.56012994", "0.5532037", "0.5527262", "0.55129933", "0.55118227", "0.5507921", "0.54987395", "0.5487615", "0.54819536", "0.54755914", "0.5475295", "0.547...
0.0
-1
Returns a 2D Laplacian kernel array.
def get_laplacian_kernel(kernel_size) -> torch.Tensor: kernel: torch.Tensor = get_laplacian_kernel2d(kernel_size) return kernel
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:\n if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \\\n kernel_size <= 0:\n raise TypeError(\"ksize must be an odd positive integer. Got {}\"\n .format(kernel_size))\n\n kernel = torch.ones((k...
[ "0.68943256", "0.5928996", "0.5873876", "0.5794534", "0.5719824", "0.568754", "0.5661878", "0.56419665", "0.5635752", "0.5564691", "0.5545013", "0.553446", "0.54953605", "0.5416252", "0.5343913", "0.53213376", "0.5320362", "0.5318403", "0.5306929", "0.5298269", "0.52873653", ...
0.66206235
1
r"""Function that returns a tensor using a Laplacian filter. The operator smooths the given tensor with a laplacian kernel by convolving it to each channel. It suports batched operation.
def laplacian(src: torch.Tensor, kernel_size: int) -> torch.Tensor: return Laplacian(kernel_size)(src)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _laplacian_to_image(lpyr, filter_vec, coeff):\n im = lpyr[-1]\n filter_vec = filter_vec.reshape(filter_vec.size, 1)\n for i in reversed(range(len(lpyr) - 1)):\n im = _expand(im, filter_vec) + coeff[i] * lpyr[i]\n\n return im", "def lapsharp(image, maskret = False):\n #padded_image =...
[ "0.6398194", "0.6261045", "0.6243763", "0.6211535", "0.6126479", "0.6089628", "0.60353637", "0.59343386", "0.5885602", "0.58751994", "0.5864428", "0.58093095", "0.58002144", "0.5674847", "0.56685555", "0.5641529", "0.55820704", "0.5570494", "0.55570203", "0.5538427", "0.55247...
0.7140893
0
Slow method that exhaustively find pairs that gives the maximum product
def max_pairwise_product(numbers): n = len(numbers) max_product = 0 for first in range(n): for second in range(first + 1, n): max_product = max(max_product, numbers[first] * numbers[second]) return max_product
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_pairwise_product_brute_force(array):\n\n if len(array) <= 1:\n return 0\n\n max_product = 0\n\n for i in range(len(array)):\n for j in range(len(array)):\n if i != j:\n if array[i] * array[j] > max_product:\n max_product = array[i] * array...
[ "0.76415133", "0.7435716", "0.7419571", "0.73527825", "0.6995507", "0.6947662", "0.6701412", "0.66534376", "0.66308546", "0.6610363", "0.65937907", "0.65213996", "0.65124816", "0.6395902", "0.63665193", "0.63143504", "0.62744373", "0.62582433", "0.62466544", "0.6241433", "0.6...
0.7392273
3
Sort the list first, then take the last two number (biggest) and multiply them
def max_pairwise_product_sort(numbers): sorted_list = sorted(numbers) ans = sorted_list[-1]*sorted_list[-2] return ans
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def greatest_difference(num_list):", "def highest_product_2(arr):\n\n # make a list to store the highest three ints, initializing to first three\n maxes = [arr[0], arr[1], arr[2]]\n\n # find the lowest of the highest three ints\n lowest_max = min(maxes)\n\n # go through the rest of the list to che...
[ "0.6987764", "0.685001", "0.66746044", "0.66537255", "0.6615918", "0.66083395", "0.6553763", "0.64379936", "0.64302796", "0.6412502", "0.6391118", "0.63837785", "0.6367723", "0.6360329", "0.633378", "0.6331884", "0.63131255", "0.6293756", "0.628999", "0.6283172", "0.6250778",...
0.7739796
0
Find the largest 2 numbers by scanning through the list
def max_pairwise_product_fast(numbers): num_list = numbers.copy() max_num_1 = max(num_list) num_list.remove(max_num_1) max_num_2 = max(num_list) ans = max_num_1*max_num_2 return ans
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def max_in_list(list):\n x=list[0] #set x be the first number in the list\n for i in range(0,len(list)):#go over the number in the list\n if x<=list[i]: #if the second one is bigger than the first\n x=list[i] #assign x to the bigger one\n else:\n continue#repeat until find...
[ "0.7865657", "0.77563345", "0.7723488", "0.77118576", "0.7655584", "0.76221126", "0.7604391", "0.7559842", "0.7552165", "0.7419501", "0.7415454", "0.73194754", "0.72359556", "0.7183456", "0.7156729", "0.71380377", "0.7110791", "0.7098136", "0.7089967", "0.7050428", "0.7011190...
0.0
-1
Get the result of a MATLAB statement. Parameter
def result(self, timeout=None): self.__validate_engine() if self._retrieved: return self._result """ Following code is used to poll the Ctrl+C every second from keyboard in order to cancel a MATLAB function. """ try: result_ready = self.wait(timeout, pythonengine.waitForFEval) if not result_ready: raise TimeoutError(pythonengine.getMessage('MatlabFunctionTimeout')) self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err) self._retrieved = True return self._result except KeyboardInterrupt: self.cancel() if self.cancelled(): print(pythonengine.getMessage('MatlabFunctionCancelled')) except: raise
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def execute_sql_scalar(self, sql):\n msg_type, msg = self.protocol.build_execute_statement(\"sql\", sql)\n self.protocol.send_msg(msg_type, msg)\n result = RowResult(self)\n result.fetch_all()\n if result.count == 0:\n raise InterfaceError(\"No data found\")\n r...
[ "0.5909357", "0.5690119", "0.5548101", "0.5496141", "0.54489595", "0.54063964", "0.5397221", "0.5366224", "0.5346653", "0.52857095", "0.5272317", "0.52682745", "0.5259357", "0.52247185", "0.52104545", "0.51776475", "0.5130771", "0.51298857", "0.51254255", "0.51205885", "0.511...
0.4819287
61
Cancel the execution of an evaluation of a MATLAB statement. Returns bool True if the corresponding MATLAB statement can be cancelled; False otherwise. Raises RejectedExecutionError an error occurs if the engine is terminated.
def cancel(self): self.__validate_engine() return pythonengine.cancelFEval(self._future)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cancelled(self):\n self.__validate_engine()\n return pythonengine.isCancelledFEval(self._future)", "def cancel(self):\n if not self.is_cancelled:\n self.will_change_value_for('is_cancelled')\n self.cancelled = True\n # remove our dependencies so that we're ready, properly beha...
[ "0.63782734", "0.6360038", "0.570138", "0.567854", "0.5647722", "0.5620772", "0.5620772", "0.5620772", "0.5620772", "0.5569046", "0.5432427", "0.53818804", "0.53624535", "0.5357489", "0.5344577", "0.53426117", "0.53072584", "0.5285678", "0.52575773", "0.52286595", "0.5207874"...
0.67627895
0
Obtain the cancellation status of the asynchronous execution of a MATLAB command. Returns bool True if the execution is cancelled; False otherwise. Raises RejectedExecutionError an error occurs if the engine is terminated.
def cancelled(self): self.__validate_engine() return pythonengine.isCancelledFEval(self._future)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cancel(self):\n self.__validate_engine()\n return pythonengine.cancelFEval(self._future)", "def cancelled(self):\n return self._status == Future.STATUS_CANCELED", "async def cancelled(self):\n await self._refresh_and_update()\n return (\n self._operation.HasFie...
[ "0.57483846", "0.5747091", "0.5745746", "0.5590403", "0.55467594", "0.55077934", "0.55016315", "0.5491056", "0.5442433", "0.5399497", "0.5271981", "0.5269121", "0.5266887", "0.5225791", "0.5185286", "0.5151515", "0.51362634", "0.5117819", "0.51172787", "0.50527465", "0.502697...
0.6059455
0
Obtain the completion status of the asynchronous invocation of a MATLAB command. Returns bool True if the execution is finished; False otherwise. It returns True even if there is an error generated from the MATLAB statement or it is cancelled. Raises RejectedExecutionError an error occurs if the engine is terminated.
def done(self): self.__validate_engine() return pythonengine.isDoneFEval(self._future)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def _execute(self):\n f = os.popen(self._com)\n if self._exec_time > 0:\n await asyncio.sleep_ms(self._exec_time)\n try:\n r = f.read()\n print(r)\n if self._expected_return is not None:\n if r == self._expected_return:\n ...
[ "0.6209489", "0.5881146", "0.57704556", "0.5739999", "0.57303506", "0.56933546", "0.56448203", "0.560831", "0.5604192", "0.56039965", "0.55831635", "0.5569415", "0.549603", "0.549603", "0.549603", "0.549603", "0.549603", "0.549603", "0.5446532", "0.5408486", "0.53901416", "...
0.53526616
22
Test POST a start call registry and expect a response from API containing a job_id and the data posted. Test uses start_call_fx fixture
def test_POST_a_call_and_expect_job_id_and_data_posted(client, start_call_fx): url = reverse_lazy('calls:registry-list') response = client.post(url, start_call_fx, content_type='application/json') response_data = response.json() assert response.status_code == status.HTTP_201_CREATED assert 'job_id' in response_data for item in start_call_fx.items(): assert item in response_data['data'].items()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_call_and_recover_it_using_a_GET_request(client, start_call_fx):\n\n url = reverse_lazy('calls:registry-list')\n\n post_request = client.post(url,\n start_call_fx,\n content_type='application/json')\n\n assert post_request.st...
[ "0.80795336", "0.7127848", "0.70870763", "0.70252454", "0.690225", "0.682077", "0.6728949", "0.64632064", "0.61601955", "0.61388147", "0.6122343", "0.61069036", "0.598875", "0.5923191", "0.5838878", "0.5811853", "0.581069", "0.5795599", "0.5779675", "0.5745532", "0.5728147", ...
0.8062351
1
Test the job_id URL of a start call registry POST. Test uses start_call_fx fixture
def test_expect_200Ok_response_GETting_a_job_id_URL(client, start_call_fx): url = reverse_lazy('calls:registry-list') response = client.post(url, start_call_fx, content_type='application/json') response_data = response.json() task_url = response_data.get('job_id', None) task_response = client.get(task_url) assert task_response.status_code == status.HTTP_200_OK
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_call_and_recover_it_using_a_GET_request(client, start_call_fx):\n\n url = reverse_lazy('calls:registry-list')\n\n post_request = client.post(url,\n start_call_fx,\n content_type='application/json')\n\n assert post_request.st...
[ "0.7932951", "0.7636372", "0.7201175", "0.70154786", "0.69145167", "0.66262203", "0.626443", "0.62300295", "0.61841965", "0.60890883", "0.5921425", "0.58591396", "0.58441097", "0.57225126", "0.57005316", "0.56909", "0.5625876", "0.55742955", "0.5544029", "0.55416805", "0.5526...
0.784503
1
Test if there is a 'status' property in a response about registry process, and if it contains a 'DONE' status about this task. Test uses start_call_fx fixture
def test_expect_status_property_about_registry_process(client, start_call_fx): url = reverse_lazy('calls:registry-list') response = client.post(url, start_call_fx, content_type='application/json') job_id = response.data.get('job_id') job = client.get(job_id) assert job.data.get('status') == 'DONE'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_expect_data_posted_return_encapsulated_on_message_property_on_response(client, start_call_fx):\n\n url = reverse_lazy('calls:registry-list')\n\n response = client.post(url, start_call_fx, content_type='application/json')\n\n job_id = response.data.get('job_id')\n\n job = client.get(job_id)\n\n...
[ "0.6107858", "0.6048469", "0.6048469", "0.60329425", "0.5998805", "0.59744084", "0.59617215", "0.59564376", "0.5914125", "0.5885923", "0.5870812", "0.58333784", "0.58272076", "0.5810825", "0.5786063", "0.57617617", "0.57480896", "0.5696804", "0.5684844", "0.5677295", "0.56715...
0.81807953
0
Test if there is a 'result' property containing the result of registry process Test uses start_call_fx fixture
def test_expect_data_posted_return_encapsulated_on_message_property_on_response(client, start_call_fx): url = reverse_lazy('calls:registry-list') response = client.post(url, start_call_fx, content_type='application/json') job_id = response.data.get('job_id') job = client.get(job_id) result = job.json() assert result.get('result') registry_url = json.loads(result.get('result')) assert client.get(registry_url.get('url')).status_code == status.HTTP_200_OK
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_expect_status_property_about_registry_process(client, start_call_fx):\n\n url = reverse_lazy('calls:registry-list')\n\n response = client.post(url, start_call_fx, content_type='application/json')\n\n job_id = response.data.get('job_id')\n\n job = client.get(job_id)\n\n assert job.data.get('...
[ "0.7666267", "0.6480155", "0.63547766", "0.63009536", "0.6242489", "0.623529", "0.61790955", "0.6141608", "0.61038685", "0.6090213", "0.6060126", "0.6026361", "0.5984391", "0.59258854", "0.5911147", "0.5894738", "0.5893941", "0.5885163", "0.58836126", "0.5859428", "0.5853621"...
0.6334782
3
Test POST a start call registry to registry API and expect recover it using a GET request. Test uses start_call_fx fixture
def test_post_a_start_call_and_recover_it_using_a_GET_request(client, start_call_fx): url = reverse_lazy('calls:registry-list') post_request = client.post(url, start_call_fx, content_type='application/json') assert post_request.status_code == status.HTTP_201_CREATED job_url = post_request.data.get('job_id') job_request = client.get(job_url) result = json.loads(job_request.data.get('result')) get_request = client.get(result.get('url')) response = get_request.json() assert get_request.status_code == status.HTTP_200_OK for key, value in start_call_fx.items(): assert value == response.get(key)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_and_stop_registry_and_get_a_call(client, start_call_fx,\n stop_call_fx):\n\n post_url = reverse_lazy('calls:registry-list')\n\n post_data = [start_call_fx, stop_call_fx]\n\n for data in post_data:\n response = client.post(p...
[ "0.77212137", "0.7614569", "0.7375702", "0.69436055", "0.68681324", "0.6717918", "0.66508937", "0.63880897", "0.62512255", "0.61260146", "0.58564955", "0.5841628", "0.5779191", "0.57728964", "0.57675964", "0.56549394", "0.55403256", "0.54902625", "0.54620844", "0.5461441", "0...
0.85472727
0
Test a GET request on the Call API Endpoint and expect it return 200 Ok
def test_GET_call_api_and_return_200Ok(client): url = '/api/v1/calls/' response = client.get(url) assert response.status_code == status.HTTP_200_OK
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_get(self):\n self.assertEqual(200, self.resp.status_code)", "def test_get(self):\n self.assertEqual(200, self.resp.status_code)", "def test_1():\n\tassert api_call().status_code == 200", "def test_get(self):\n self.assertEqual(200, self.response.status_code)", "def test_get(se...
[ "0.7947968", "0.7947968", "0.7879138", "0.77913356", "0.77913356", "0.77886796", "0.76140255", "0.75884384", "0.7562267", "0.75419384", "0.75371504", "0.75371504", "0.7369333", "0.7351754", "0.7339209", "0.73001033", "0.72693115", "0.7259427", "0.72563964", "0.721277", "0.719...
0.8886346
0
Test if there is a Call API endpoint and if is defined as "calls" namespace and "calllist" as his name
def test_namespace_of_call_api_endpoint(): url = '/api/v1/calls/' resolved = resolve(url) assert resolved.namespace == 'calls'\ and resolved.url_name == 'call-list'
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_call_api_return_only_consolidated_calls(client, start_call_fx, stop_call_fx):\n\n post_url = reverse_lazy('calls:registry-list')\n\n start_call_fx_2 = copy(start_call_fx)\n start_call_fx_2['call_id'] = 2\n\n post_data = [start_call_fx, start_call_fx_2, stop_call_fx]\n\n for data in post_dat...
[ "0.62145686", "0.6031098", "0.597374", "0.59650505", "0.5733628", "0.55599207", "0.54912245", "0.54800916", "0.54037213", "0.5337027", "0.531804", "0.523795", "0.5225318", "0.5171135", "0.516988", "0.51654184", "0.5162458", "0.51472855", "0.51333857", "0.5127361", "0.5116722"...
0.77283394
0
Test for documentation on Call API Endpoint view
def test_documentation_for_call_view(): url = reverse_lazy('calls:call-list') view = resolve(url).func assert view.__doc__
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_view_detail_as_method(self):\n url = reverse(\n \"django-admindocs-views-detail\",\n args=[\"django.contrib.admin.sites.AdminSite.index\"],\n )\n response = self.client.get(url)\n self.assertEqual(response.status_code, 200)", "def test_view():\n\treturn ...
[ "0.6804205", "0.65882033", "0.6567295", "0.6547328", "0.6524265", "0.64814574", "0.6474007", "0.6394351", "0.6393633", "0.6392588", "0.6389973", "0.62900865", "0.62861174", "0.62557405", "0.62550545", "0.6218095", "0.61950505", "0.61669517", "0.61537933", "0.6125932", "0.6122...
0.7911585
0
Test POSTing a start and a stop registry and expect get it at Call API Endpoint Test uses start_call_fx fixture Test uses stop_call_fx fixture
def test_post_a_start_and_stop_registry_and_get_a_call(client, start_call_fx, stop_call_fx): post_url = reverse_lazy('calls:registry-list') post_data = [start_call_fx, stop_call_fx] for data in post_data: response = client.post(post_url, data, content_type='application/json') assert response.status_code == status.HTTP_201_CREATED get_url = reverse_lazy('calls:call-list') response = client.get(get_url) assert len(response.data) == 1 assert response.data[0].get('start_timestamp') assert response.data[0].get('stop_timestamp')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_and_stop_registry_and_get_a_call_using_url(client,\n start_call_fx,\n stop_call_fx):\n\n post_url = reverse_lazy('calls:registry-list')\n\n post_data = [start_...
[ "0.8207508", "0.7297929", "0.7013963", "0.6848967", "0.6562138", "0.64560413", "0.6252057", "0.6184207", "0.61758155", "0.6018559", "0.59301925", "0.5880597", "0.5861513", "0.58101547", "0.57913876", "0.57734543", "0.5742188", "0.57399577", "0.57374406", "0.5709208", "0.56703...
0.85035634
0
Test POSTing a start and a stop registry and expect get it at Call API Endpoint using a call_id Test uses start_call_fx fixture Test uses stop_call_fx fixture
def test_post_a_start_and_stop_registry_and_get_a_call_using_url(client, start_call_fx, stop_call_fx): post_url = reverse_lazy('calls:registry-list') post_data = [start_call_fx, stop_call_fx] for data in post_data: response = client.post(post_url, data, content_type='application/json') assert response.status_code == status.HTTP_201_CREATED get_url = reverse_lazy('calls:call-detail', kwargs={'call_id': 1}) response = client.get(get_url) assert response.data.get('start_timestamp') assert response.data.get('stop_timestamp')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_and_stop_registry_and_get_a_call(client, start_call_fx,\n stop_call_fx):\n\n post_url = reverse_lazy('calls:registry-list')\n\n post_data = [start_call_fx, stop_call_fx]\n\n for data in post_data:\n response = client.post(p...
[ "0.8484062", "0.75393564", "0.7322953", "0.722341", "0.6426046", "0.62504566", "0.6230039", "0.6164438", "0.59421086", "0.59283173", "0.5919254", "0.58633626", "0.58341634", "0.58131343", "0.5774062", "0.57502663", "0.56712496", "0.5646838", "0.56402326", "0.5634627", "0.5630...
0.8285663
1
Test POSTing two start registries and only one stop registry and expect to GET only on record on Call API Endpoint. Test uses start_call_fx fixture Test uses stop_call_fx fixture
def test_call_api_return_only_consolidated_calls(client, start_call_fx, stop_call_fx): post_url = reverse_lazy('calls:registry-list') start_call_fx_2 = copy(start_call_fx) start_call_fx_2['call_id'] = 2 post_data = [start_call_fx, start_call_fx_2, stop_call_fx] for data in post_data: response = client.post(post_url, data, content_type='application/json') assert response.status_code == status.HTTP_201_CREATED get_url = reverse_lazy('calls:call-list') response = client.get(get_url) assert len(response.data) == 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_post_a_start_and_stop_registry_and_get_a_call(client, start_call_fx,\n stop_call_fx):\n\n post_url = reverse_lazy('calls:registry-list')\n\n post_data = [start_call_fx, stop_call_fx]\n\n for data in post_data:\n response = client.post(p...
[ "0.8359559", "0.81559026", "0.72383404", "0.68315816", "0.6380493", "0.6169041", "0.6073902", "0.60261333", "0.5987054", "0.59616095", "0.5898319", "0.5815202", "0.5773632", "0.5772734", "0.5764194", "0.57637644", "0.57477325", "0.57452106", "0.5725453", "0.569496", "0.566565...
0.76799375
2
Downhill algorithm as described in Kiusalaas Numerical Methods in Engineering with Python 3
def downhill(F, xStart, args=None, side=0.1, ftol=1.0e-6, xtol=1.0e-6, maxiter=1000, maxfunc=1000, maxiternochange=10): # TODO: check the types of the input ??? # print "Entering downhill" n = len(xStart) x = np.zeros((n+1, n), dtype=float) #point null matrix, n+1 rows, n columns f = np.zeros(n+1, dtype=float) # null vector, n+1 columns p_count = 0 # counter for detecting a plateau f_count = 0 # counter for the number of function call f_best_count = 0 # counter for the number of iterations in which the best solution does not change f_best_prev = 0.0 # holds the best value from the previous iteration epsilon = 0.001 # tolerance for considering two values as equal # max_iter_no_change = 10 # maximum number of accepted iterations with no change in the optimal solution precision = 2 round_map = partial(round, ndigits=precision) # partial function for rounding purposes # initial simplex x[0] = xStart for i in xrange(1, n+1): x[i] = xStart x[i,i-1] = xStart[i-1] + side # print "Evaluate the starting points" # compute the value of F at the vertices of the simplex for i in xrange(n+1): f[i] = F(x[i], args) # p_count += 1 # main loop # print "Start iterating" for k in xrange(maxiter): # check the number of function calls if f_count > maxfunc: print "Stopping criteria: maximum number of function calls" print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'MAXFUNCALL'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'MAXFUNCALL'} # find the best and worst vertex (consider a minimization problem) iLo = np.argmin(f) # best vertex iHi = np.argmax(f) # worst vertex # print k," ", f[iLo] # # if f[iLo] < -0.310000: # print f[iLo] # print x[iLo] # print x # sys.exit(1) # print "k: ", k, " f_best_prev: ", f_best_prev, " f[iLo]: ", f[iLo], " f_best_count: ", f_best_count # print "Beginning of iteration: %4d | Best x: %4f %4f %4f | Best value: %f" % (k, x[iLo][0], x[iLo][1], x[iLo][2], f[iLo]) # print "x: ", x, " f: ", f # print "=========================================================================================" # check if the solution has changed from the previous iterations if f[iLo] < f_best_prev: f_best_prev = f[iLo] f_best_count = 0 else: f_best_count += 1 if f_best_count > maxiternochange: print "Stopping criteria: maximum number of iterations with no improvement in the best solution" print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'NOIMPROVEMENT'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'NOIMPROVEMENT'} if abs(f[iLo] - f[iHi]) < ftol: # If difference between highest and lowest is smaller than ftol, return print "Stopping criteria: difference between highest and lowest points is smaller than tolerance" print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'MAXTOLERANCE'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'MAXTOLERANCE'} # compute the move vector d d = (-(n+1) * x[iHi] + np.sum(x, axis=0)) / n # print "d: ", d # check for convergence if sqrt(np.dot(d, d)/n) < xtol: # length of the vector d print "Stopping criteria: length of step d smaller than tolerance" print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'SMALLSTEP'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'SMALLSTEP'} # try reflection xNew = np.array(map(round_map, x[iHi] + 2 * d)) fNew = F(xNew, args) f_count += 1 # print "Reflected point: ", xNew, " value: ", fNew # check for no improvement over the worst point # and for plateau condition if f[iHi] - epsilon <= fNew <= f[iHi] + epsilon: p_count += 1 # print "No improvement here" if p_count == n+2: # we reflected all vertices with no improvement print "Stopping criteria: Probably we landed on a plateau... exiting" # TODO: restart instead of exiting print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'PLATEAU'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'PLATEAU'} else: p_count = 0 if fNew <= f[iLo]: # if the new value is better than the best so far, x[iHi] = xNew # substitute the worst vertex with the new one f[iHi] = fNew # try to expand the reflection xNew = np.array(map(round_map, x[iHi] + d)) fNew = F(xNew, args) f_count += 1 # print "Expanded point: ", xNew, " value: ", fNew if fNew <= f[iHi]: # in the original source version it is f[iLo] (?) x[iHi] = xNew f[iHi] = fNew else: # try reflection again if fNew <= f[iHi]: x[iHi] = xNew f[iHi] = fNew else: # try contraction xNew = np.array(map(round_map, x[iHi] + 0.5 * d)) fNew = F(xNew, args) f_count += 1 # print "Contracted point: ", xNew, " value: ", fNew if fNew <= f[iHi]: # accept contraction x[iHi] = xNew f[iHi] = fNew else: # shrink for i in xrange(len(x)): if i != iLo: x[i] = np.array(map(round_map, x[i] - x[iLo] * 0.5)) f[i] = F(x[i], args) f_count += 1 # print "End of iteration: %4d | Best x: %4f %4f %4f | Best value: %f" % (k, x[iLo][0], x[iLo][1], x[iLo][2], f[iLo]) # print "x: ", x, " f: ", f # print "*"*50 # print "" print "Stopping criteria: maximum number of iterations" print "Best solution so far: ", x[iLo], " value: ", f[iLo], " at iteration:", k # return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': (args['Q1'], args['Q2'], args['Q3']), 'stopping': 'MAXITERATION'} return {'point' : x[iLo], 'value': f[iLo], 'iteration': k, 'funcalls': f_count, 'allocation': [args['Q{}'.format(h)] for h in xrange(1, args['retailers']+1)], 'stopping': 'MAXITERATION'}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def solution(A):\n \"\"\"method 2 n**2\n east=[] #0\n west=[] #1\n for i in range(len(A)):\n if A[i] == 0:\n east.append(i)\n else:\n west.append(i)\n\n result = 0\n for e in east:\n count = 0\n for j in range(len(west)):\n if e > west[...
[ "0.6305694", "0.58596754", "0.5824617", "0.57462597", "0.5715227", "0.5684032", "0.56557304", "0.5591559", "0.5554532", "0.55386126", "0.5528498", "0.55246407", "0.5522697", "0.5501514", "0.5486631", "0.5482586", "0.54730695", "0.546426", "0.5456875", "0.5453615", "0.5421071"...
0.5833218
2
Plot balance between classes
def plot_balance_class(classes): unique, counts = np.unique(classes, return_counts=True) plt.bar(unique, counts) plt.title('Class Frequency') plt.xlabel('Class') plt.ylabel('Frequency') plt.show()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_class_imbalance(df, title='Class Imbalance', PATH=None):\n ax = sns.barplot(x=[\"Normal\", \"Clickbait\"], y=df.groupby(['target']).target.count())\n ax.set_title(title, size=20)\n plt.xticks([0,1],[\"Normal\", \"Clickbait\"], size = 20)\n ax.set_ylabel(\"Document Count\", size=17)\n ax.set...
[ "0.6470689", "0.62615764", "0.618939", "0.5848157", "0.58320725", "0.5751623", "0.5716817", "0.5682445", "0.56821924", "0.56675744", "0.5648744", "0.5599107", "0.5581174", "0.5550323", "0.5517062", "0.5514832", "0.54800415", "0.54709786", "0.5425537", "0.54238087", "0.5382205...
0.7392071
0
Load data and convert class type to str
def load_data(dataset_path: str): data = arff.loadarff(dataset_path) data_frame = pd.DataFrame(data[0]) return data_frame
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _convert_to_str(self, data):\n raise NotImplementedError()", "def loaddata(cls, data, auto_cls=True):\n keys = data.dtype.fields if hasattr(data, 'dtype') else data\n if auto_cls and 'class' in keys:\n cls_components = str(data['class']).split('.')\n mod_name = '.'....
[ "0.64354247", "0.6280863", "0.6222278", "0.6192303", "0.61756396", "0.61756396", "0.61756396", "0.61756396", "0.61756396", "0.616021", "0.616021", "0.61370295", "0.61201906", "0.6067332", "0.6043132", "0.60146064", "0.60138565", "0.60008734", "0.5951044", "0.58738834", "0.580...
0.0
-1
Find best parameters for decision tree
def find_best_classifier(x_train, x_test, y_train, y_test): max_depth, _ = find_best_parameters( 'max_depth', list(range(1, 30)), x_train, x_test, y_train, y_test) print("Best max_depth t: ", max_depth) min_samples_split, _ = find_best_parameters( 'min_samples_split', list(range(2, 400)), x_train, x_test, y_train, y_test) min_samples_split = int(min_samples_split) print("Best min samples split: ", min_samples_split) min_samples_leaf, _ = find_best_parameters( 'min_samples_leaf', list(range(2, 200)), x_train, x_test, y_train, y_test) min_samples_leaf = int(min_samples_leaf) print("Best sample leaf: ", min_samples_leaf) max_leaf_nodes, _ = find_best_parameters( 'max_leaf_nodes', list(range(2, 150)), x_train, x_test, y_train, y_test) max_leaf_nodes = int(max_leaf_nodes) print("Best max leaf nodes split: ", max_leaf_nodes) min_impurity_decrease, _ = find_best_parameters( 'min_impurity_decrease', np.arange(0.0005, 0.1, 0.0005), x_train, x_test, y_train, y_test) print("Best min impurity decrease: ", min_impurity_decrease) clf = DecisionTreeClassifier( min_impurity_decrease=min_impurity_decrease, max_depth=max_depth, min_samples_leaf=min_samples_leaf, max_leaf_nodes=max_leaf_nodes, min_samples_split=min_samples_split, random_state=0) clf = clf.fit(x_train, y_train) return clf
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def select_model():\r\n from sklearn import tree\r\n import graphviz\r\n\r\n ValidationSetAndLabels = AllSets[1]\r\n ValLabels = ValidationSetAndLabels[:, [-1]] # extract labels (last column)\r\n ValSet = np.delete(ValidationSetAndLabels, -1, axis=1) # delete labels\r\n\r\n TrainingSetAndLabels =...
[ "0.73654014", "0.6803678", "0.6700777", "0.669526", "0.6686797", "0.6683199", "0.6660834", "0.6638287", "0.65660405", "0.65332466", "0.65164715", "0.64410394", "0.64108276", "0.64031994", "0.6387443", "0.6330438", "0.62947744", "0.6267406", "0.6226899", "0.62210745", "0.61950...
0.74380594
0
Converts a binary adjacency matrix to a list of directed edges
def to_adj_list(adj_matrix): adj_list = [] assert (adj_matrix.shape[0] == adj_matrix.shape[1]) for idx in range(adj_matrix.shape[0]): for jdx in range(idx, adj_matrix.shape[0]): if adj_matrix[idx, jdx] == 1: adj_list.append([idx, jdx]) return adj_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def edges(adj_mat, vertices):\n return [(i,j) for i,j in\n vertices if (i < j and adj_mat[i][j] == 1)]", "def matrix_to_edges(matrix: numpy.ndarray, include_reverse_edges: bool=True):\n sparse = scipy.sparse.coo_matrix(matrix)\n edges = zip(sparse.row, sparse.col)\n\n if not include_revers...
[ "0.7220524", "0.7194223", "0.710978", "0.68476194", "0.6835649", "0.67063034", "0.67027074", "0.6680238", "0.6674114", "0.6642599", "0.66176134", "0.66089475", "0.6598832", "0.6533455", "0.65062785", "0.64912444", "0.64912444", "0.64545166", "0.6395245", "0.6378416", "0.63470...
0.69720167
3
Returns a list of successors by vertex, sensitive to the read strand
def get_successor_list(adj_matrix, vertex_map, read_strand): succ_list = [] assert (adj_matrix.shape[0] == adj_matrix.shape[1]) for idx in range(adj_matrix.shape[0]): succ_list.append([]) for jdx in range(adj_matrix.shape[0]): if adj_matrix[idx, jdx] == 1 and \ ((read_strand == "+" and vertex_map[0][idx] <= vertex_map[0][jdx]) or \ (read_strand == "-" and vertex_map[1][idx] >= vertex_map[1][jdx])): succ_list[idx].append(jdx) return succ_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_successors(vertex, graph):\n successors = list()\n successors.extend(graph.successors(vertex))\n return successors", "def get_predecessors_successors(vertex, graph):\n overlaps = list()\n pre = get_unique_predecessors(vertex, graph)\n suc = get_unique_successors(vertex, graph)\n over...
[ "0.7708114", "0.6563205", "0.6376617", "0.6307063", "0.62348616", "0.61934036", "0.60396194", "0.594999", "0.59440297", "0.58112705", "0.57270694", "0.5720067", "0.57045156", "0.5680978", "0.5673067", "0.5660702", "0.56433517", "0.5618526", "0.5613443", "0.5608551", "0.560492...
0.6470455
2
Find overlapping CDS within an exon given a list of CDS starts
def find_overlapping_cds_simple(v_start, v_stop, cds_begins, strand): # cds_start = cds_begin[0] if strand == '+': return list(filter(lambda x: x[0] >= v_start and x[0] < v_stop, cds_begins)) else: return list(filter(lambda x: x[0] > v_start and x[0] <= v_stop, cds_begins))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def overlap(list1,list2):\n \n coord=[]\n for pos1 in list1:\n #print 'pos in list1 is', pos1\n coord.append(('S',int(pos1.split('-')[0]), 'l1'))\n #print 'S is ', pos1.split('-')[0]\n coord.append(('E',int(pos1.split('-')[1]),'l1'))\n #print 'E is ', pos1.split('-')[1]\...
[ "0.6343779", "0.5909693", "0.5851059", "0.57616645", "0.5732729", "0.568256", "0.5675713", "0.56729394", "0.5659118", "0.56387144", "0.5623953", "0.558914", "0.5588006", "0.5570414", "0.55475664", "0.5545426", "0.5528489", "0.5526816", "0.5525146", "0.5520476", "0.5492296", ...
0.7374044
0
Encodes chromosome to same cn
def encode_chromosome(in_num): convert_dict = {23: "X", 24: "Y", 25: "MT"} return convert_dict[in_num] if in_num in convert_dict else str(in_num)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __encode(self):\n\n for i, char in enumerate(self.__chars):\n self.__char2idx[char] = i\n self.__idx2char[i] = char", "def encode(self, C, num_rows):\n x = np.zeros((num_rows, len(self.chars)))\n print(C)\n for i, c in enumerate(C):\n x[i, self.cha...
[ "0.65794533", "0.62438995", "0.6232326", "0.62068266", "0.6048946", "0.5984779", "0.5922863", "0.5862185", "0.5761406", "0.57606995", "0.5690487", "0.56302047", "0.5617058", "0.5587301", "0.5558331", "0.5556066", "0.5555711", "0.55398685", "0.54918736", "0.54819953", "0.54703...
0.7192931
0
Get the mutated dna subsequence according to mutation specified by the variant_comb.
def get_sub_mut_dna(background_seq, coord, variant_comb, somatic_mutation_sub_dict, strand, gene_start): def _get_variant_pos_offset(variant_pos, coord_pair_list, strand): offset = 0 takes_effect = False for p1,p2 in coord_pair_list: if variant_pos >= p1 and variant_pos < p2: if strand == '+': offset += variant_pos - p1 else: offset += p2 - variant_pos - 1 takes_effect = True break else: offset = p2 - p1 return offset if takes_effect else np.nan real_coord = list(filter(lambda x: x is not np.nan and x != None, coord)) assert len(real_coord) % 2 == 0 coord_pair_list = list(zip(real_coord[::2], real_coord[1::2])) if strand == '+': sub_dna = ''.join([background_seq[pair[0] - gene_start:pair[1] - gene_start] for pair in coord_pair_list]) else: sub_dna = ''.join([background_seq[pair[0] - gene_start:pair[1] - gene_start][::-1] for pair in coord_pair_list]) if variant_comb is np.nan : # no mutation exist return sub_dna relative_variant_pos = [_get_variant_pos_offset(variant_ipos, coord_pair_list, strand) for variant_ipos in variant_comb] for i,variant_ipos in enumerate(variant_comb): mut_base = somatic_mutation_sub_dict[variant_ipos]['mut_base'] ref_base = somatic_mutation_sub_dict[variant_ipos]['ref_base'] pos = relative_variant_pos[i] if pos is not np.nan: sub_dna = sub_dna[:pos] + mut_base + sub_dna[pos+1:] return sub_dna
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_DNA_seq(mutant_position, all_lines):\n\n dna_lines = []\n for i in range(mutant_position + 2, len(all_lines)):\n line = all_lines[ i ]\n if not line:\n break\n\n line = line.replace(\"Variant sequence: \", \"\")\n dna_lines.append(line)\n return dna_lines", ...
[ "0.5627289", "0.5542037", "0.5341807", "0.5279429", "0.49878958", "0.4956177", "0.49556637", "0.49054444", "0.4834147", "0.48148525", "0.47234476", "0.4720456", "0.4699101", "0.46727768", "0.4651557", "0.46446463", "0.46332493", "0.46132207", "0.46070266", "0.45562443", "0.45...
0.695729
0
Get the expression adjustment parameter for certain samples.
def get_size_factor(samples, lib_file_path): libs = np.loadtxt(lib_file_path, dtype='str', skiprows=1, delimiter='\t') a, b = np.where(samples[:, np.newaxis] == libs[:, 0]) assert np.all(libs[b, 0] == samples) libs = libs[b, :] med = np.median(libs[:, 1].astype('float')) sf = med / libs[:, 1].astype('float') return sf
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def adjustment(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"adjustment\")", "def adjustment(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"adjustment\")", "def adjustment(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"adjustment\")...
[ "0.5970573", "0.5970573", "0.5970573", "0.5970573", "0.5970573", "0.5970573", "0.5970573", "0.5970573", "0.55451614", "0.5458691", "0.5382217", "0.5338391", "0.52984136", "0.52497977", "0.5241062", "0.5241062", "0.52158433", "0.5213984", "0.5213984", "0.5159911", "0.5122732",...
0.0
-1
Get all combinations of items in the given array Specifically used for generating variant combination
def get_all_comb(array, r=None): if r is None: r = len(array) return [_ for i in range(1, r + 1) for _ in itertools.combinations(array, i)]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def combinations(arrays):\n return np.array(np.meshgrid(*arrays)).T.reshape(-1, len(arrays))", "def combos(array,n=2): \n # base case\n if n==0:\n yield frozenset()\n return\n\n # core recursion\n for c in set(combos(array,n-1)):\n for i in array:\n #added this t...
[ "0.73074627", "0.7185561", "0.6950121", "0.67702305", "0.67702305", "0.6750947", "0.6720031", "0.6644649", "0.6399782", "0.63772047", "0.63587743", "0.6318727", "0.62932175", "0.62885773", "0.62456626", "0.6200499", "0.6191303", "0.61892384", "0.61841613", "0.6181527", "0.616...
0.79023576
0
Indicate if a peptide is translated by an isolated cds Currently, it is a simple version. If the exon where the cds is has no connected exon, it is isolated. (the method is not true in some cases)
def is_isolated_cds(gene, gene_info, idx): if len(gene_info.vertex_succ_list[idx]) > 0: return False return np.sum(gene.splicegraph.edges[:, idx]) == 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_isolated(self, d):\n if not self.center.is_isolated(d):\n return False\n\n for i in self.leads:\n if not i.is_isolated(d+1):\n return False\n\n return True", "def is_atomic(self):\n found = True\n if self.ant is not None:\n ...
[ "0.59894097", "0.5898949", "0.5672679", "0.5648508", "0.5560285", "0.5529773", "0.5459054", "0.54222125", "0.541582", "0.5374678", "0.53390956", "0.53365326", "0.53323716", "0.5328659", "0.52947295", "0.5285229", "0.5278996", "0.5277022", "0.5254552", "0.5249883", "0.5224548"...
0.6469092
0
Split the exon into segments and get the corresponding counts.
def get_exon_expr(gene, vstart, vstop, countinfo, Idx, seg_counts): out_shape = (seg_counts.shape[1] + 1) if len(seg_counts.shape) > 1 else 2 # Todo: deal with absense of count file if vstart is np.nan or vstop is np.nan: # isolated exon case return np.zeros((0, out_shape), dtype='float') if countinfo is None or Idx.sample is None: return np.zeros((0, out_shape), dtype='float') #[np.nan] segments = gene.segmentgraph.segments sv1_id = bisect.bisect(segments[0], vstart) - 1 sv2_id = bisect.bisect(segments[0], vstop) - 1 if sv1_id == sv2_id: if len(seg_counts.shape) > 1: expr_list = np.c_[np.array([vstop - vstart]), [seg_counts[sv1_id, :]]] else: expr_list = np.array([(vstop - vstart, seg_counts[sv1_id])]) else: if len(seg_counts.shape) > 1: expr_list = np.c_[segments[1, sv1_id:sv2_id + 1] - segments[0, sv1_id:sv2_id + 1], seg_counts[sv1_id:sv2_id + 1, :]] else: expr_list = np.c_[segments[1, sv1_id:sv2_id + 1] - segments[0, sv1_id:sv2_id + 1], seg_counts[sv1_id:sv2_id + 1, np.newaxis]] expr_list[0, 0] -= (vstart - segments[0, sv1_id]) expr_list[-1, 0] -= (segments[1, sv2_id] - vstop) if gene.strand == '-': # need to reverse epression list to match the order of translation expr_list = expr_list[::-1] return expr_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getSegmentCount(self) -> int:\n ...", "def calculate_number_of_segments(self):\n return sum(len(eg.transcript_file.segments) for eg in self.exemplars)", "def getSegments(self) -> List[int]:\n ...", "def Test_NumSegments(Daten):\n N_Leitungen = len(Daten.PipeSegments)\n\n return...
[ "0.65174055", "0.6436669", "0.6075838", "0.5796184", "0.57153535", "0.57003266", "0.56921184", "0.5661428", "0.5604101", "0.5561135", "0.55508536", "0.553926", "0.5515936", "0.5487367", "0.54719216", "0.54696095", "0.5457705", "0.54412377", "0.537007", "0.5364843", "0.5354218...
0.0
-1
Get the segment expression for one exonpair. Apply 'get_exon_expr' for each exon and concatenate them.
def get_segment_expr(gene, coord, countinfo, Idx, seg_counts, cross_graph_expr): if coord.start_v3 is None: expr_list = np.vstack([get_exon_expr(gene, coord.start_v1, coord.stop_v1, countinfo, Idx, seg_counts ), get_exon_expr(gene, coord.start_v2, coord.stop_v2, countinfo, Idx, seg_counts )]) else: expr_list = np.vstack([get_exon_expr(gene, coord.start_v1, coord.stop_v1, countinfo, Idx, seg_counts ), get_exon_expr(gene, coord.start_v2, coord.stop_v2, countinfo, Idx, seg_counts ), get_exon_expr(gene, coord.start_v3, coord.stop_v3, countinfo, Idx, seg_counts )]) seg_len = np.sum(expr_list[:, 0]) n_samples = expr_list[:, 1:].shape[1] len_factor = np.tile(expr_list[:, 0], n_samples).reshape(n_samples, expr_list.shape[0]).transpose() mean_expr = (np.sum(expr_list[:, 1:]*len_factor, 0) / seg_len).astype(int) if seg_len > 0 else np.zeros(n_samples).astype(int) if not cross_graph_expr: mean_expr = mean_expr[0] return mean_expr,expr_list
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_exon_expr(gene, vstart, vstop, countinfo, Idx, seg_counts):\n out_shape = (seg_counts.shape[1] + 1) if len(seg_counts.shape) > 1 else 2\n # Todo: deal with absense of count file\n if vstart is np.nan or vstop is np.nan: # isolated exon case\n return np.zeros((0, out_shape), dtype='float')\...
[ "0.5563815", "0.5293783", "0.5213351", "0.49248624", "0.49004447", "0.48478526", "0.4781561", "0.47813958", "0.4710072", "0.4675474", "0.4543498", "0.45414433", "0.45138633", "0.44763458", "0.44727144", "0.44690332", "0.4463009", "0.44608518", "0.44598845", "0.44542956", "0.4...
0.56654406
0
get total reads count for the given sample and the given gene actually total_expr = reads_lengthtotal_reads_counts
def get_total_gene_expr(gene, countinfo, Idx, seg_expr, cross_graph_expr): if len(seg_expr.shape) == 1: n_samples = 1 else: n_samples = seg_expr.shape[1] if countinfo is None or Idx.sample is None: return [np.nan] * n_samples seg_len = gene.segmentgraph.segments[1] - gene.segmentgraph.segments[0] if cross_graph_expr: total_expr = np.sum(seg_len * seg_expr.T, axis=1) total_expr = total_expr.tolist() else: total_expr = [np.sum(seg_len*seg_expr)] return total_expr
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_count_total_reads(self):\n \n bam = pybedtools.BedTool(clipper.test_file(\"allup_test.bam\"))\n gene_dfn = pybedtools.BedTool(clipper.test_file(\"hg19_genes.bed\"))\n \n result = count_total_reads(bam, gene_dfn)\n \n self.assertEqual(result, 2086)", "def ...
[ "0.71968734", "0.64680296", "0.624144", "0.60355866", "0.6020118", "0.58288175", "0.57842183", "0.5721398", "0.5674062", "0.56387067", "0.5625821", "0.5600439", "0.5572864", "0.55386955", "0.55117846", "0.550808", "0.5496517", "0.54497534", "0.5437835", "0.5402488", "0.539430...
0.5925086
5
Create a aggregated Index with namedtuple idx Combine the gene_idx, sample_idx
def get_idx(countinfo, sample, gene_idx): if not countinfo is None: if not sample in countinfo.sample_idx_dict: sample_idx = None logging.warning("utils.py: The sample {} is not in the count file. Program proceeds without outputting expression data.".format(sample)) else: sample_idx = countinfo.sample_idx_dict[sample] else: sample_idx = None return Idx(gene_idx, sample_idx)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_gene_indexes(df):\n\tgeneDict = OrderedDict()\n\n\tgeneCount = 0\n\tpreviousGeneIndex = 0\n\n\tcurrent_id=\"\"\n\tcurrent_gene=\"\"\n\n\tfor i in range(len(df)):\n\n\t\tif df.loc[i,'feature'] == 'gene':\n\t\t\ttrdict = parse_entry(df.loc[i,'transcript_id'])\n\n\t\t\tcurGeneID = trdict['gene_id'][0]\n\t\t...
[ "0.6321686", "0.6155408", "0.60595196", "0.6051188", "0.59505635", "0.5836034", "0.5680135", "0.56531954", "0.5625771", "0.55557144", "0.5533098", "0.5517968", "0.5480308", "0.54524577", "0.54428107", "0.5442492", "0.5433063", "0.543244", "0.54272753", "0.54136074", "0.540922...
0.64187765
0
create library_size text file. Calculate the 75% expression and sum of expression for each sample and write into output_fp.
def create_libsize(expr_distr_fp, output_fp, sample, debug=False): sample_expr_distr = pa.parquet.read_table(expr_distr_fp['path']).to_pandas() libsize_count= pd.DataFrame({'sample': sample_expr_distr.columns[1:], 'libsize_75percent': np.percentile(sample_expr_distr.iloc[:, 1:], 75, axis=0), 'libsize_total_count': np.sum(sample_expr_distr.iloc[:, 1:], axis=0)}, index = None) df_libsize = pd.DataFrame(libsize_count) if os.path.isfile(output_fp): previous_libsize = pd.read_csv(output_fp, sep = '\t') df_libsize = pd.concat([previous_libsize, df_libsize], axis=0).drop_duplicates(subset=['sample'], keep='last') df_libsize.to_csv(output_fp, sep='\t', index=False)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_libfile():\n # wfc3_obsmodes_uvis\n wfc3_uvis = [\n \"f218w\",\n \"f225w\",\n \"f275w\",\n \"f336w\",\n \"f390m\",\n \"f390w\",\n \"f410m\",\n \"f438w\",\n \"f467m\",\n \"f475w\",\n \"f547m\",\n \"f555w\",\n \...
[ "0.54608756", "0.5400242", "0.5211215", "0.5197263", "0.5194946", "0.51773113", "0.51361793", "0.51357317", "0.5126693", "0.5125787", "0.5115333", "0.51034206", "0.5085765", "0.50600755", "0.5036529", "0.5036529", "0.5028773", "0.50280166", "0.5021801", "0.50140125", "0.50085...
0.6827684
0
Get the concatenated peptide from possible match peptide.
def get_concat_peptide(front_coord_pair, back_coord_pair, front_peptide, back_peptide, strand, k=None): def get_longest_match_position(front_str,back_str,L=None): if L is None: L = min(len(front_str),len(back_str)) for i in reversed(list(range(1,L+1))): if front_str[-i:] == back_str[:i]: return i return None if strand == '+': front_coord = front_coord_pair.stop_v2 back_coord = back_coord_pair.start_v1 else: front_coord = front_coord_pair.start_v2 back_coord = back_coord_pair.stop_v1 if abs(front_coord-back_coord) % 3 == 0: if front_coord == back_coord: # no intersection and we concatenate them directly new_peptide = front_peptide + back_peptide else: pep_common_num = get_longest_match_position(front_peptide,back_peptide,L=k) if pep_common_num is None: new_peptide = '' else: new_peptide = front_peptide + back_peptide[pep_common_num:] return new_peptide else: return ''
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def concatenate(self):\n if not self.match_count:\n # No concatenating if there are no matches\n return []\n if self.match_count <= 1:\n # Can't combine a single match\n return self.match_list\n # Setup for iterating through\n cont = True\n ...
[ "0.58377457", "0.57520026", "0.55693895", "0.51852643", "0.5118976", "0.5036226", "0.4998545", "0.49705812", "0.49523178", "0.49279532", "0.4873407", "0.4863047", "0.48540068", "0.48335233", "0.4816873", "0.48077628", "0.48022303", "0.48017293", "0.4800456", "0.4780788", "0.4...
0.6651385
0
Print memory diagnostics including the active resident set size
def print_memory_diags(disable_print=False): process = psutil.Process(os.getpid()) memory = process.memory_info().rss/1000000000.0 if not disable_print: logging.info('\tMemory usage: {:.3f} GB'.format(memory)) return memory
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _mem_report(tensors: Iterable, mem_type: str) -> None:\n print(f\"Storage on {mem_type}\")\n print(\"-\" * LEN)\n total_numel = 0\n total_mem = 0\n visited_data: List[Any] = []\n for tensor in tensors:\n if tensor.is_sparse:\n continue\n ...
[ "0.70509243", "0.7048715", "0.684797", "0.6824635", "0.6806491", "0.67121667", "0.6675784", "0.66524774", "0.6635588", "0.66292006", "0.65855217", "0.6583841", "0.6535865", "0.65259236", "0.65087706", "0.6496641", "0.64578336", "0.6444816", "0.64439434", "0.63657725", "0.6365...
0.74818563
0
Return some simple info for the tables in VotoStudio's workshop.
def get_table_values(self): table_descriptors = getattr(self, 'table_descriptors', None) if not table_descriptors: raise AttributeError(f"Please add the 'table_descriptors' field to the model '{self._meta.label}'") return { 'id': self.id, 'descriptors': [{ 'name': d, 'value': self._get_descriptor_value(d), } for d in table_descriptors], 'app_label': self._meta.app_label, 'model_name': self._meta.model_name, 'model_label': self._meta.label, **self._get_user_info(), }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def show_table():\n\n title_list = ('ID', 'Platform', 'Producer', 'Year', 'Elements')\n \n return table, title_list", "def PrintInfo(self):\n infoname = list(zip(*self.basicinfo.cursor.execute(\n \"SELECT Name FROM Infoname\").fetchall()))[0]\n for obj in infoname:\n ...
[ "0.6594911", "0.6500587", "0.64386666", "0.6242125", "0.61695975", "0.6073596", "0.6034584", "0.6016744", "0.5995429", "0.5982109", "0.59196234", "0.59027016", "0.5872902", "0.5864931", "0.5819785", "0.57872105", "0.57864594", "0.5785509", "0.57692075", "0.57690203", "0.57690...
0.0
-1
Return more detailed info for the detail view in VotoStudio's workshop.
def get_detail_info(self): detail_descriptors = getattr(self, 'detail_descriptors', None) if not detail_descriptors: raise AttributeError(f"Please add the 'detail_descriptors' field to the model '{self._meta.label}'") detail_values = [{ 'name': d, 'value': getattr(self, d), 'type': 'basic', } for d in detail_descriptors['basic']] related_descriptors = detail_descriptors['related'] for related_descriptor in related_descriptors: field_name = related_descriptor['field'] field = self._meta.get_field(field_name) field_value = getattr(self, field_name) # If this field on the instance # has a value then check its type. if field: field_type = field.get_internal_type() value = None if field_type == 'ManyToManyField': value = [[{ 'name': attr, 'value': getattr(o, attr) } for attr in ('id', *related_descriptor['attrs'])] for o in field_value.all()] if field_type == 'ForeignKey' or field_type == 'OneToOneField': value = [{ 'name': attr, 'value': getattr(field_value, attr, None), } for attr in related_descriptor['attrs']] detail_values.append({ 'name': field_name, 'model_label': field.related_model._meta.label, 'value': value, 'type': 'related', }) return detail_values
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_details(self):", "def print_details(self):\n self.view.print_details()", "def detail(self):\n info = self.info()\n return info", "def get_details(self):\n return self.details", "def get_details(self):\n return self.details", "def get_details(self):\n retu...
[ "0.6816689", "0.67486215", "0.6713748", "0.65807945", "0.65807945", "0.65807945", "0.65140444", "0.6467318", "0.6412233", "0.6406499", "0.63699645", "0.62743896", "0.62667674", "0.6252862", "0.6249236", "0.6226553", "0.619854", "0.61578506", "0.61264884", "0.61043566", "0.606...
0.0
-1
model_predict will return the preprocessed image
def model_predict(img_path, model_path): learn = load_model(model_path) img = open_image(img_path) # get the outputs from the model pred_class,pred_idx,outputs = learn.predict(img) # return the classification the model returns return pred_class
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def predict(model, img):\n\tx = image.img_to_array(img)\n\tx = np.expand_dims(x, axis=0)\n\tx = preprocess_input(x)\n\tpreds = model.predict(x)\n\treturn preds[0]", "def predict(model, img, target_size=(229, 229)): #fixed size for InceptionV3 architecture\r\n if img.size != target_size:\r\n img = img.resize(...
[ "0.8407046", "0.82272613", "0.8150348", "0.8089915", "0.804863", "0.804863", "0.78832704", "0.7876628", "0.7739453", "0.7739021", "0.77017534", "0.769704", "0.76113904", "0.7572362", "0.75003004", "0.7484886", "0.74482", "0.7415542", "0.7312185", "0.72863543", "0.728227", "...
0.7862426
8
Randomly permute the training roidb.
def _shuffle_roidb_idx(self): self.perm = np.random.permutation(np.arange(self.num_images)) self.cur = 0
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _random_permutation(self):\n self.train_permutation = numpy.random.permutation(range(len(self.train_list)))", "def shuffle(self, random_state=None): \n if random_state is None:\n random_state = self.random_state\n perm_ids = random_state.permutation(self.n_examples)\n ...
[ "0.7341957", "0.6980299", "0.6517204", "0.6517204", "0.64934677", "0.64483047", "0.6303886", "0.6292093", "0.6292093", "0.626896", "0.61837375", "0.61757475", "0.6172573", "0.6138042", "0.61206377", "0.6080488", "0.6078871", "0.6064974", "0.59135115", "0.59126294", "0.5903226...
0.65922296
2
Return the roidb indices for the next minibatch.
def _get_next_minibatch_idx(self): if self.cur + self.batch_size >= self.num_images: self._shuffle_roidb_idx() db_idx = self.perm[self.cur:self.cur + self.batch_size] self.cur += self.batch_size return db_idx
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_next_minibatch_inds(self):\n ## 实际上只需要向后遍历一个即可\n\n if self._cur + cfg.TRAIN.IMS_PER_BATCH >= len(self._roidb):\n self._shuffle_roidb_inds()\n self._cur = 0\n\n db_inds = self._perm[self._cur : self._cur+ cfg.TRAIN.IMS_PER_BATCH]\n self._cur += cfg.TRAIN.IM...
[ "0.76239616", "0.745489", "0.7413968", "0.70359194", "0.6630719", "0.65478575", "0.6362661", "0.6330628", "0.6231964", "0.6105139", "0.60316145", "0.5990063", "0.59887934", "0.5968671", "0.5885011", "0.58408743", "0.582455", "0.5802829", "0.57580876", "0.5756126", "0.5748933"...
0.72795445
3
We use this function to flip the bunch in s and convert the information from time (t) to the longitudinal length along the bunch(s).
def flip_slice(t, bins=2944): s = constants.c*np.ravel((np.max(t)-t)) # Flip s s_sort_index = np.argsort(s) # Ascending order. plt.clf() hist_min = np.min(s) # hist_max = np.min(s)+(np.max(s)-np.min(s))*0.96 hist_max = np.min(s)+(np.max(s)-np.min(s))*0.99 hist, zplot, patches = plt.hist(s, bins,range = (hist_min, hist_max)) id_slices = [] for n in range(0, bins): num_begin = int(np.sum(hist[0:n])) num_end = int(np.sum(hist[0:n+1])) id_slices.append(s_sort_index[num_begin:num_end]) return id_slices, zplot, hist
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def MakeLongTime(t, N):\n dt=(t.max()-t.min())/(max(shape(t))-1)\n tout=arange(0,N,dtype='f')\n tout=tout*dt\n return tout", "def time_unwrap(val_timestamps):\n a=val_timestamps.shape[0]\n val_time =val_timestamps.astype('int64')\n for i in range(a-1):\n if val_time[i+1]-val_time[i]<-...
[ "0.5729294", "0.535365", "0.5282586", "0.52594215", "0.5227779", "0.5178457", "0.51595366", "0.507217", "0.5067364", "0.50368345", "0.5025668", "0.49911958", "0.49690363", "0.49690363", "0.49686134", "0.4950423", "0.490032", "0.4897815", "0.48929238", "0.4863648", "0.4863037"...
0.49709463
12
We use this function to analyze the beam property along s.
def beam_property_along_s(ps, id_slices): prop_s = np.zeros((14, len(id_slices))) for n in range(len(id_slices)): ps_s = np.take(ps, id_slices[n], axis=1) prop_s[0, n] = np.average(ps_s[0,:]) prop_s[1, n] = np.average(ps_s[1,:]) prop_s[2, n] = np.average(ps_s[2,:]) prop_s[3, n] = np.average(ps_s[3,:]) prop_s[4, n] = np.std(ps_s[0,:]) prop_s[5, n] = np.std(ps_s[2,:]) prop_s[6:, n] = emittance_and_twiss(ps_s) return prop_s
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def prt_beam_prms(self):\n print '\\nIon Charge States = ', self.M.conf()['IonChargeStates']\n print 'IonEs [MeV] = ', self.M.conf()['IonEs']/1e6\n print 'IonEk [MeV] = ', self.M.conf()['IonEk']/1e6\n print '\\nBaryCenter 0:\\n', self.M.conf()['BaryCenter0']\n print '...
[ "0.55478334", "0.55464554", "0.5515675", "0.54473466", "0.5417652", "0.5381833", "0.533846", "0.5251011", "0.5237646", "0.5210435", "0.5204704", "0.51945657", "0.5185809", "0.5178469", "0.5154056", "0.5144773", "0.51260614", "0.51221514", "0.51218563", "0.5119552", "0.5115868...
0.63167745
0
I want to use this function to calculate the 4D phase space at the end of some components in the undulator beamline.
def analyze_phase_space_at_end(ps_beg, beamline, beamline_id, id_slices, N_bin): phase_spc = ps_beg ## Count how many times the class beamline_id occurs in the beamline_id count_beamline = 0 for element in beamline: if isinstance(element, beamline_id): count_beamline += 1 ps_end = np.zeros((4, count_beamline, N_bin)) count_id = 0 for element in beamline: phase_spc = np.dot( element.M1, phase_spc ) +element.M2 if isinstance(element, beamline_id): ps_along_s = beam_property_along_s(phase_spc, id_slices) ps_end[0, count_id, :] = ps_along_s[0, :] ps_end[1, count_id, :] = ps_along_s[1, :] ps_end[2, count_id, :] = ps_along_s[2, :] ps_end[3, count_id, :] = ps_along_s[3, :] count_id += 1 return ps_end
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_phasedbeam(self):\n\n self.phasedbeam = n.zeros((len(self.dmarr),len(self.reltime)), dtype='float64')\n\n for i in xrange(len(self.dmarr)):\n self.phasedbeam[i] = self.dedisperse(dmbin=i).mean(axis=3).mean(axis=2).mean(axis=1).real # dedisperse and mean\n ...
[ "0.6671196", "0.64827406", "0.6373965", "0.6372035", "0.6084464", "0.60772616", "0.6052406", "0.59829885", "0.5869289", "0.5851694", "0.580842", "0.58041", "0.5711219", "0.5682935", "0.5637525", "0.5630165", "0.5624642", "0.56207854", "0.5617892", "0.5615495", "0.5611847", ...
0.6127306
4
We want to use this function to analyze which part is on the axis in each undulator section.
def analyze_on_axis(phase_space, id_begin, id_end, ds_slice, zplot): ps = phase_space[:, (id_begin-1):id_end, :] # print(np.shape(ps)) # ps = ps[numpy.logical_not(numpy.isnan(ps))] x = ps[0, :, :] px = ps[1, :, :] y = ps[2, :, :] py = ps[3, :, :] id_on_axis = np.zeros((4, int(id_end-id_begin+1))) for n in range(int(id_end-id_begin+1)): x_this = x[n, :] px_this = px[n, :] y_this = y[n, :] py_this = py[n, :] # Remove all NAN elements in the phase space array x_this = x_this[np.logical_not(np.isnan(x_this))] px_this = px_this[np.logical_not(np.isnan(px_this))] y_this = y_this[np.logical_not(np.isnan(y_this))] py_this = py_this[np.logical_not(np.isnan(py_this))] ## Plot X plt.subplot(2, 2, 1) plt.plot(zplot[0:len(x_this)]*1e+6, x_this*1e+6) plt.ylabel('Position in X/ $\mu$m', fontsize=10) ## Plot Y plt.subplot(2, 2, 2) plt.plot(zplot[0:len(y_this)]*1e+6, y_this*1e+6) plt.ylabel('Position in Y/ $\mu$m', fontsize=10) ## Plot px plt.subplot(2, 2, 3) plt.plot(zplot[0:len(px_this)]*1e+6, px_this) plt.ylabel('Angle in X', fontsize=10) ## Plot py plt.subplot(2, 2, 4) plt.plot(zplot[0:len(py_this)]*1e+6, py_this) plt.ylabel('Angle in Y', fontsize=10) # plt.xlabel('Longitudianl Direction of the Bunch $s$/ $\mu$m') # plt.title('First Undulator Section') # plt.title('Second Undulator Section') # plt.title('Third Undulator Section') id_on_axis[0, n] = np.argmin(np.abs(x_this)) id_on_axis[1, n] = np.argmin(np.abs(px_this)) id_on_axis[2, n] = np.argmin(np.abs(y_this)) id_on_axis[3, n] = np.argmin(np.abs(py_this)) fig = plt.gcf() fig.set_size_inches(13.5, 9) ax = plt.gca() ax.yaxis.get_major_formatter().set_powerlimits((0,1)) fig.savefig('phase_space_U3_new.png', dpi=100) plt.show() s_on_axis = np.average(id_on_axis[2:4,:])*ds_slice return id_on_axis, s_on_axis
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def othersn(ax):", "def _sections(self, axis=None, direction=None, cycle=None,\n concat_direction=False, concat_cycle=False, info=False,\n **kwargs):\n if axis is None:\n axis = ['x', 'y']\n if direction is None:\n direction = ['left', 'right'...
[ "0.5563447", "0.55561185", "0.55355847", "0.5400956", "0.5346773", "0.5164223", "0.51494545", "0.5128714", "0.5126724", "0.50905246", "0.5079524", "0.5058356", "0.5053756", "0.5040289", "0.50352335", "0.50240916", "0.5023575", "0.50167745", "0.50061435", "0.49880677", "0.4979...
0.6365625
0
We want to use this function to optimize parameters for orbit correctors. Indeed, we always need two orbit correctors to do this job.
def analyze_orbit_corrector(OC1, OC2, beamline, phase_beg): M = np.identity(4) OC_parameters = np.zeros(4) for element in beamline: M = np.dot(element.M1, M) # Since the X and Y are decoupled, we can treat them separately. M_x = M[0:2, 0:2] M_y = M[2:4, 2:4] L1 = [[OC1.length/2], [1]] L2 = [[OC2.length/2], [1]] M_OC1 = np.array(OC1.M1)[0:2, 0:2] M_OC2 = np.array(OC2.M1)[0:2, 0:2] # The following part solve the cx_1 and cx_2 M1_x = np.linalg.multi_dot([M_OC2, M_x, L1]) M2_x = np.linalg.multi_dot([M_OC2, M_x, M_OC1]) M_OC_x = np.hstack((M1_x, L2)) OC_parameters[0:2] = -np.linalg.multi_dot([np.linalg.inv(M_OC_x), M2_x, phase_beg[0:2]]) # The end of the X-part # The following part solve the cy_1 and cy_2 M1_y = np.linalg.multi_dot([M_OC2, M_y, L1]) M2_y = np.linalg.multi_dot([M_OC2, M_y, M_OC1]) M_OC_y = np.hstack((M1_y, L2)) OC_parameters[2:4] = -np.linalg.multi_dot([np.linalg.inv(M_OC_y), M2_y, phase_beg[2:4]]) # The end of the Y-part return OC_parameters
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def solve_prep(self):\n\n par = self.par\n sol = self.sol\n\n # a. retirement\n sol.m_ret = np.zeros((par.T,par.Nm_ret))\n sol.c_ret = np.zeros((par.T,par.Nm_ret))\n sol.a_ret = np.zeros((par.T,par.Nm_ret))\n sol.inv_v_ret = np.zeros((par.T,par.Nm_ret))\n sol...
[ "0.6054454", "0.6029055", "0.6029055", "0.6029055", "0.59086585", "0.5886708", "0.585231", "0.58431363", "0.57428247", "0.57226473", "0.56672513", "0.5646705", "0.5617193", "0.5610204", "0.56079906", "0.5607317", "0.55761766", "0.5571415", "0.5559164", "0.55436873", "0.552162...
0.56180215
12
I want to use this function to directly set up all orbit correctors.
def set_up_orbit_correctors(ps_beg, delay, id_slice1, ds_slice, zplot, id_slices, U_core, lambdaref): SXSS = Chicane(3.2716, 0.362, 0.830399, delay[0]) HXSS = Chicane(3.2, 0.3636, 0.5828, delay[1]) OC2 = [CORR08, D1_SXSS, SXSS, D2_SXSS, QUAD09, CORR09] OC3 = [CORR15, D1_HXSS, HXSS, D2_HXSS, QUAD16, CORR16] ps_end1 = beam_transportation(ps_beg, U_core[0]) # ps_end1 is a 4-by-N array. N is the number of macro-particles. It is the full # 4D phase space distribution at the end of the first undulator section. # The id of the slice on the axis in the second undulator section on_axis_id_U2 = int(id_slice1+delay[0]/ds_slice+ (8*110)*lambdaref/ds_slice) # The last part is slippage print(on_axis_id_U2) ps_end_slice1 = beam_property_along_s(ps_end1, id_slices)[0:4, :] ps_on_axis_2 = np.ravel(ps_end_slice1[:, on_axis_id_U2]) # print(ps_on_axis_2) OC2_optimized = analyze_orbit_corrector(OC2[0], OC2[-1], OC2[1:-1], ps_on_axis_2) print(OC2_optimized) CORR08_new = Orbit_Corrector(OC2[0].length, OC2_optimized[0], OC2_optimized[2]) CORR09_new = Orbit_Corrector(OC2[-1].length, OC2_optimized[1], OC2_optimized[3]) # The whole U2 with optimized orbit correctors U2_new = [CORR08_new] + OC2[1:-1] + [CORR09_new] + U_core[1] ps_end2 = beam_transportation(ps_end1, U2_new) # ps_end2 is a 4-by-N array. N is the number of macro-particles. It is the full # 4D phase space distribution at the end of the second undulator section. # The id of the slice on the axis in the third undulator section on_axis_id_U3 = int(id_slice1+(delay[0]+delay[1])/ds_slice +(14*110*lambdaref)/ds_slice) # The last term is the slipage print(on_axis_id_U3) ps_end_slice2 = beam_property_along_s(ps_end2, id_slices)[0:4, :] ps_on_axis_3 = np.ravel(ps_end_slice2[ :, on_axis_id_U3]) # print(ps_on_axis_3) OC3_optimized = analyze_orbit_corrector(OC3[0], OC3[-1], OC3[1:-1], ps_on_axis_3) print(OC3_optimized) CORR15_new = Orbit_Corrector(OC3[0].length, OC3_optimized[0], OC3_optimized[2]) CORR16_new = Orbit_Corrector(OC3[-1].length, OC3_optimized[1], OC3_optimized[3]) U3_new = [CORR15_new] + OC3[1:-1] + [CORR16_new] + U_core[2] Undulator_Beamline = U_core[0]+U2_new+U3_new return Undulator_Beamline
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setUp(self):\n self.precip_cube = setup_precipitation_cube()\n self.oe_cube = setup_orographic_enhancement_cube()\n self.vel_x = set_up_xy_velocity_cube(\"advection_velocity_x\")\n self.vel_y = set_up_xy_velocity_cube(\"advection_velocity_y\")\n for cube in [self.precip_cube,...
[ "0.59741217", "0.59616315", "0.59439087", "0.59116036", "0.58822644", "0.58440155", "0.5834586", "0.57733816", "0.5746145", "0.5736931", "0.57054114", "0.56986", "0.56339926", "0.5609833", "0.5579601", "0.5572102", "0.5556903", "0.55461323", "0.5529173", "0.5519832", "0.55151...
0.64385605
0
Loads the preprocessed celeb_a dataset scaled down to 32x32
def get_celeb_a32(): path = './data/celeb_a32' if not os.path.exists(path): print(path, " does not exits") return None images = utils.get_tensor_images_from_path(path) data = tf.data.Dataset.from_tensor_slices(images) data = data.map(lambda x: tf.cast(x, tf.float32)) data = data.batch(int(tf.data.experimental.cardinality(data))) return data
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_celebA():\n channel_mean = [0.50003925, 0.42008925, 0.37377534]\n channel_std = [0.30878809, 0.28794379, 0.28661432]\n\n dataset = CelebA(transform=transforms.Compose([\n transforms.CenterCrop(178),\n transforms.Resize(64),\n transforms.ToTensor(),\n transforms.Normali...
[ "0.7416813", "0.6421557", "0.6321571", "0.60597914", "0.5983696", "0.5967315", "0.5948484", "0.59380203", "0.5907359", "0.5897862", "0.58657163", "0.58646065", "0.5861289", "0.58553", "0.58469105", "0.577485", "0.5769538", "0.5751676", "0.574995", "0.57490104", "0.5744094", ...
0.72671366
1
listen for message event
async def on_message(self, msg: Message): from_contact = msg.talker() text = msg.text() room = msg.room() if text == '#ding': conversation: Union[ Room, Contact] = from_contact if room is None else room await conversation.ready() await conversation.say('dong') file_box = FileBox.from_url( 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/' 'u=1116676390,2305043183&fm=26&gp=0.jpg', name='ding-dong.jpg') await conversation.say(file_box)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _handle_message(self, msg):\n self.event('message', msg)", "def on_message(data):\n pass", "def event_in_cb(self, msg):\n self.event = msg.data", "def on_message(self, message):\n print \"Client %s received a message : %s\" % (self.id, message)", "def onMessage(self, message...
[ "0.8410868", "0.8254583", "0.7882204", "0.78618526", "0.7829602", "0.7802724", "0.773378", "0.7572389", "0.7512617", "0.74960405", "0.74841064", "0.74824226", "0.7457746", "0.7441775", "0.74085176", "0.73933196", "0.7379106", "0.7322716", "0.7322716", "0.730575", "0.729197", ...
0.0
-1
all initialization jobs should be done here.
async def on_ready(self, payload: EventReadyPayload): log.info('ready event <%s>', payload) # 1. get all of friends friends: List[Contact] = await self.Contact.find_all() for friend in friends: log.info('load friend<%s>', friend) # 2. get all of rooms rooms: List[Room] = await self.Room.find_all() for room in rooms: log.info('load room<%s>', room)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _initJobs(self):\n pass", "def do_init(self):\n\n pass", "def _initialise_run(self) -> None:", "def initialize():\n manager.initialize()\n logs.exit_great_success()", "def _manually_initialize(self) -> None:\n # XXX: maybe refactor, this is actually part of the public interfa...
[ "0.7979565", "0.7962231", "0.7734526", "0.76368004", "0.7622692", "0.7585923", "0.7379355", "0.7354919", "0.73505986", "0.7327622", "0.7325596", "0.7325596", "0.7325596", "0.73226774", "0.7315183", "0.7215203", "0.7204069", "0.7199315", "0.7195699", "0.7195699", "0.7195699", ...
0.0
-1
Run all dispatch tests
def dispatch(): suite = ServiceTestSuite() suite.addTest(unittest.makeSuite(Test, 'test_dispatch')) return suite
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def runTests(self):\n \n pass", "def doAllTests(self):\n # Initial offset\n self.getAlertsFile()\n self.offset = self.getOffset(self.config.get('PATHS', 'tempfile'))\n\n # Do all tests\n # As the socket is not persistent, client side attacks have to be done before all...
[ "0.7445618", "0.72676694", "0.72357136", "0.69886786", "0.69496655", "0.69481313", "0.6913679", "0.6835688", "0.6833541", "0.68203133", "0.68139446", "0.6779515", "0.67011243", "0.6626831", "0.66243935", "0.6614983", "0.65842265", "0.6561729", "0.6560582", "0.6522628", "0.648...
0.7137783
3
Run all local tests
def local(): suite = ServiceTestSuite() suite.addTest(unittest.makeSuite(Test, 'test_local')) return suite
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _run_local_tests(self, *args, **kwargs):\n pass", "def runAll():\n\n loader = unittest.TestLoader()\n test_dir = pkg_resources.resource_filename('frvcpy.test','.')\n suite = loader.discover(test_dir)\n\n runner = unittest.TextTestRunner(verbosity=2)\n runner.run(suite)", "def main():\...
[ "0.8297117", "0.7959936", "0.7950929", "0.7797158", "0.768714", "0.766804", "0.76199144", "0.75607073", "0.7456279", "0.744708", "0.7380929", "0.7380103", "0.72950643", "0.7281221", "0.727362", "0.7181298", "0.71580607", "0.7139827", "0.7125284", "0.70671266", "0.7064775", ...
0.0
-1
Run all network tests
def net(): suite = ServiceTestSuite() suite.addTest(unittest.makeSuite(Test, 'test_net')) return suite
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_all():\n test_get_to()\n test_error_type()\n test_exchange()\n print(\"All tests passed.\")", "def run_all_tests():\n remove_dbs()\n run_training_tests()\n run_custom_training_tests()\n run_training_save_tests()\n run_validation_tests()\n run_feature_extraction_tests()", ...
[ "0.7459378", "0.74455136", "0.7278033", "0.71453613", "0.713573", "0.7003208", "0.69377714", "0.6935737", "0.6916369", "0.68943274", "0.6879508", "0.6857769", "0.67931044", "0.6778059", "0.6765904", "0.675124", "0.67291695", "0.66894144", "0.66677123", "0.6644143", "0.6638301...
0.627527
56
This function will get a vector an construct a polynomial(function) f(x) with each degree having a coefficient from the corrosponding value from the vector.
def vecToFunc(vector): def f(x): f = 0 for i in range(len(vector)): f += vector[i]*x**i return f return f
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate_polynomial(f,x):\n degree = len(f)-1\n ans = 0\n for i in f:\n ans += i*x**degree\n degree -= 1\n return(ans)", "def build_poly(x, degree):\n phi = np.ones(len(x))\n phi = np.vstack((phi, [x**(j+1) for j in range(degree)]))\n \n return phi.T", "def polynomial_...
[ "0.71002614", "0.6959504", "0.6857088", "0.6731912", "0.671709", "0.66995835", "0.6682442", "0.6642471", "0.66166174", "0.6615598", "0.6501584", "0.6486129", "0.6437595", "0.64153004", "0.64109534", "0.6395708", "0.63793916", "0.636425", "0.63570154", "0.6323563", "0.63210785...
0.67569125
3
Parse command line arguments
def get_options(cmd_args=None): cmd_parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cmd_parser.add_argument( '-i', '--input_file', help="""a log file to be cleaned up""", type=str, default='') cmd_parser.add_argument( '-s', '--salt', help="""the salt for anonymizing IPs [optional, defaults to hardcoded one]""", type=str, default=salt) args = cmd_parser.parse_args(cmd_args) options = {} options['input_file'] = args.input_file options['salt'] = args.salt return options
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def parse_arguments(args):", "def parse_args():\n parser = argparse.ArgumentParser(\n description=\"Reads datapacket pcds, interpolates quaternions and generates scans from dataset in config file\")\n parser.add_argument(\"--visualization\", \"-v\", action=\"store_true\", help=\"if generated clouds ...
[ "0.84956664", "0.77526116", "0.7492404", "0.74425805", "0.74166906", "0.7415034", "0.7406717", "0.7405937", "0.7394592", "0.739314", "0.7353777", "0.73531276", "0.73295814", "0.7326098", "0.73121136", "0.7297962", "0.72947985", "0.7294619", "0.7293887", "0.7288054", "0.727713...
0.0
-1
Returns the file for a given URL. If the URL appear to be a static file, we will attempt to load it internally. Otherwise, it will resolve normally as an external URL. Relative URLs are only supported The default behaviour will fetch any http(s) files normally, and will also attempt to resolve staticfiles internally (this should mostly affect development scenarios, but also works if static files are served under a relative URL).
def django_url_fetcher(url: str): # If the URL looks like a staticfile, try to load it as such. # Reading it from the storage avoids a network call in many cases (unless the # storage is remote, in which case this improves nothing: try: if url.startswith(staticfiles_storage.base_url): filename = url.replace(staticfiles_storage.base_url, "", 1) data = None path = finders.find(filename) if path: # Read static files from source (e.g.: the file that's bundled with the # Django app that provides it. # This also picks up uncollected staticfiles (useful when developing / # in DEBUG mode). with open(path, "rb") as f: data = f.read() else: # File was not found by a finder. This commonly happens when running in # DEBUG=True with a storage that uses Manifests or alike, since the # filename won't match with the source file. # In these cases, use the _storage_ to find the file instead: with staticfiles_storage.open(filename) as f: data = f.read() return { "mime_type": mimetypes.guess_type(url)[0], "string": data, } except (ValueError, FileNotFoundError): # Looks like this wasn't a staticfile (or maybe it was a missing one?) # Let it resolve as a normal URL. pass try: # If the URL is a relative URL, use Django's resolver to figure out how Django # would serve this. # # This should cover all those funky scenarios like: # - Custom views that serve dynamically generated files. # - Media files (if serving them via Django, which is not recommended). if url.startswith("/"): view, args, kwargs = resolve(url) kwargs["request"] = HttpRequest kwargs["request"].method = "GET" response = view(*args, **kwargs) return { "mime_type": mimetypes.guess_type(url)[0], "string": response.content, } except Resolver404 as e: raise InvalidRelativeUrl(f"No view matched `{url}`.") from e return default_url_fetcher(url)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_file(cls, url, working_dir):\n if url.lower().startswith(\"s3://\"):\n return cls._s3_get_file(url)\n elif url.lower().startswith(\"http\"):\n return cls._http_get_file(url)\n else:\n return cls._fs_get_file(url, working_dir)", "def _fs_get_file(url, ...
[ "0.7276085", "0.7078293", "0.66783506", "0.6656778", "0.643477", "0.6392354", "0.6384419", "0.6384419", "0.6384419", "0.63783556", "0.63404953", "0.63349915", "0.6328483", "0.62485206", "0.6248228", "0.6211496", "0.62018925", "0.6179627", "0.61627275", "0.6156638", "0.6155268...
0.68511707
2
Writes the PDF data into ``file_``. Note that ``file_`` can actually be a Django Response object as well, since these are filelike objects. This function may be used as a helper that can be used to save a PDF file to a file (or anything else outside of a request/response cycle).
def render_pdf( template: Union[List[str], str], file_: IO, url_fetcher=django_url_fetcher, context: Optional[dict] = None, ): context = context or {} if isinstance(template, str): template = [template] html = select_template(template).render(context) HTML( string=html, base_url="not-used://", url_fetcher=url_fetcher, ).write_pdf( target=file_, )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def save_pdf(self, response):\n\n # get metadata\n file_type = \"__comprovante_de_acesso__\"\n\n # options to save pdf\n file_id = str(uuid.uuid4())\n filename = \"{file_id}.pdf\".format(file_id=file_id)\n file_path = os.path.join(path, \"downloads\", self.scrape_id, filen...
[ "0.67716074", "0.6708492", "0.6434953", "0.6190672", "0.61892325", "0.6181426", "0.6171567", "0.6031542", "0.5953594", "0.59264964", "0.587159", "0.5858788", "0.57871544", "0.5752377", "0.57122386", "0.56981695", "0.56687397", "0.5661542", "0.56381875", "0.56225604", "0.56082...
0.55854136
21
Set the `order_by_field` on the filterset and ensure that the field name is respected.
def test_ordering_with_overridden_field_name(self): class F(FilterSet): class Meta: model = User fields = ['username', 'status'] order_by = ['status'] order_by_field = 'order' f = F({'order': 'status'}, queryset=self.qs) self.assertQuerysetEqual( f.qs, ['carl', 'alex', 'jacob', 'aaron'], lambda o: o.username)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_ordering_with_overridden_field_name(self):\n class F(FilterSet):\n class Meta:\n model = User\n fields = ['username', 'status']\n order_by = ['status']\n order_by_field = 'order'\n\n f = F().form\n self.assertNotIn...
[ "0.7114981", "0.6805322", "0.65821075", "0.6384245", "0.6316189", "0.6254384", "0.6160399", "0.60926193", "0.59577346", "0.59503293", "0.59400135", "0.5909272", "0.5759706", "0.57583076", "0.57493776", "0.5726326", "0.5716653", "0.571355", "0.5712792", "0.5647503", "0.5642596...
0.7341014
0
Test ordering descending works when order_by=True.
def test_ordering_descending_unset(self): class F(FilterSet): class Meta: model = User fields = ['username', 'status'] order_by = True f = F({'o': '-username'}, queryset=self.qs) self.assertQuerysetEqual( f.qs, ['jacob', 'carl', 'alex', 'aaron'], lambda o: o.username)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_orderby(self):\n\n # TODO: make a unit test out of these various combinations\n #m = mapper(User, users, order_by=desc(users.c.user_name))\n mapper(User, users, order_by=None)\n #mapper(User, users)\n\n #l = create_session().query(User).select(order_by=[desc(users.c.user...
[ "0.68660283", "0.6728724", "0.6677009", "0.6650034", "0.65972036", "0.6469477", "0.64451", "0.6346018", "0.62945986", "0.62910104", "0.6286649", "0.6240998", "0.6212203", "0.619569", "0.618064", "0.61099553", "0.6034809", "0.5979432", "0.59784126", "0.59772485", "0.59331065",...
0.6622364
4
Set the `order_by_field` on the filterset and ensure that the field name is respected.
def test_ordering_with_overridden_field_name(self): class F(FilterSet): class Meta: model = User fields = ['username', 'status'] order_by = ['status'] order_by_field = 'order' f = F().form self.assertNotIn('o', f.fields) self.assertIn('order', f.fields) self.assertEqual(f.fields['order'].choices, [('status', 'Status')])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_ordering_with_overridden_field_name(self):\n class F(FilterSet):\n class Meta:\n model = User\n fields = ['username', 'status']\n order_by = ['status']\n order_by_field = 'order'\n\n f = F({'order': 'status'}, queryset=se...
[ "0.7341898", "0.6805477", "0.6581681", "0.6385461", "0.6315338", "0.6252756", "0.6159823", "0.6090766", "0.5956584", "0.5951964", "0.59386057", "0.59089255", "0.5759275", "0.57582235", "0.5749629", "0.57229424", "0.5717913", "0.5713295", "0.5711421", "0.5647316", "0.56422055"...
0.7116057
1
Set the `order_by_field` on the filterset and ensure that the field name is respected.
def test_ordering_with_overridden_field_name_and_descending(self): class F(FilterSet): class Meta: model = User fields = ['username', 'status'] order_by = ['status', '-status'] order_by_field = 'order' f = F().form self.assertNotIn('o', f.fields) self.assertIn('order', f.fields) self.assertEqual(f.fields['order'].choices, [('status', 'Status'), ('-status', 'Status (descending)')])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_ordering_with_overridden_field_name(self):\n class F(FilterSet):\n class Meta:\n model = User\n fields = ['username', 'status']\n order_by = ['status']\n order_by_field = 'order'\n\n f = F({'order': 'status'}, queryset=se...
[ "0.7341014", "0.7114981", "0.65821075", "0.6384245", "0.6316189", "0.6254384", "0.6160399", "0.60926193", "0.59577346", "0.59503293", "0.59400135", "0.5909272", "0.5759706", "0.57583076", "0.57493776", "0.5726326", "0.5716653", "0.571355", "0.5712792", "0.5647503", "0.5642596...
0.6805322
2
Given object without dependency, use it's importerManager to get available data
def test_nondependent_object_get(self): manager = ImporterManager(importer=UserImporter()) for row,name in enumerate(self.usernames): manager.update_kvs(field_name='username',value=name,row=row) manager.get_available_rows() for i in range(self.n_objs): objs: List[RecordData] = manager.get_objs_and_meta(i) #: Returns a list of objects only if manytomany self.assertEqual(objs[0].available, True) self.assertIsNotNone(objs[0].object) self.assertIsInstance(objs[0].object, User) self.assertIsNotNone(objs[0].query) del manager
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def importer():\n pass", "def get_objects_data(self):\n pass", "def import_(self, data):\n return self.__import(data)", "def import_data(self):\n self.models = []\n for o in self.loader.load():\n klass = self.type_for(o)\n if hasattr(klass, \"from_api\"):\...
[ "0.64458275", "0.62757504", "0.61903095", "0.6175268", "0.59833163", "0.5957138", "0.5917701", "0.58304566", "0.58275753", "0.58036554", "0.57879543", "0.5749467", "0.5749467", "0.5749467", "0.5749467", "0.57487833", "0.574654", "0.5720211", "0.5711407", "0.5699259", "0.56894...
0.5439921
37
Given object without dependency, use it's importerManager to get available data, and assert that after deleting a given user, we can still query the metadata returned by the ImporterManger
def test_partial_nondependent_object_get(self): MISSING_INDEX = 2 User.objects.filter(username=self.usernames[MISSING_INDEX]).delete() manager = ImporterManager(importer=UserImporter()) for row,name in enumerate(self.usernames): manager.update_kvs(field_name='username',value=name,row=row) manager.get_available_rows() for i in range(self.n_objs): objs: List[RecordData] = manager.get_objs_and_meta(i) #: Returns a list of objects only if manytomany if i==MISSING_INDEX: self.assertEqual(objs[0].available, False) self.assertIsNone(objs[0].object) self.assertIsNotNone(objs[0].query) continue self.assertEqual(objs[0].available, True) self.assertIsNotNone(objs[0].object) self.assertIsInstance(objs[0].object, User) self.assertIsNotNone(objs[0].query) del manager
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_nondependent_object_get(self):\n manager = ImporterManager(importer=UserImporter())\n for row,name in enumerate(self.usernames):\n manager.update_kvs(field_name='username',value=name,row=row)\n\n manager.get_available_rows()\n for i in range(self.n_objs):\n ...
[ "0.6992192", "0.6501583", "0.63623047", "0.60247934", "0.5967793", "0.594195", "0.57997954", "0.57775795", "0.56826866", "0.56701046", "0.56604755", "0.5646488", "0.5642088", "0.5631375", "0.5626657", "0.55903274", "0.55903274", "0.5548128", "0.5526234", "0.5525164", "0.55185...
0.6286618
3
Ensures any object with an analagous dependency relationship to UserProfile > User && UserProfile > Company can filter based on it's related import kvs
def test_dependent_object_import(self): # Initialize Importers up_manager = ImporterManager(importer=UserProfileImporter()) company_manger = ImporterManager(importer=CompanyImporter()) user_manager = ImporterManager(importer=UserImporter()) # Populate leaf models of dependency tree with kv data for row,name in enumerate(self.usernames): user_manager.update_kvs(field_name='username', value=name, row=row) company_manger.update_kvs(field_name='natural_id', value=self.company.natural_id, row=row) #: Retrieve data associated with kv data user_manager.get_available_rows() company_manger.get_available_rows() #: Populate data up the dependency tree with retrieved rows for row in range(self.n_objs): up_manager.update_kvs('company', company_manger.get_object_or_list(row), row=row) up_manager.update_kvs('user', user_manager.get_object_or_list(row), row=row) #: Retrieve data associated with models depended upon up_manager.get_available_rows() #: Test corresponding UserProfile has been returned for row in range(self.n_objs): objs = up_manager.get_objs_and_meta(row) #: Returns a list of objects only if manytomany, o/w just 1 self.assertEqual(objs[0].available, True) self.assertIsNotNone(objs[0].object) self.assertIsInstance(objs[0].object, UserProfile) self.assertIsNotNone(objs[0].query) self.assertEqual(objs[0].object.user.username, self.usernames[row])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_twice_dependent_object_import(self):\n pass", "def test_partial_twice_dependent_object_import(self):\n pass", "def test_m2m_dependent_object_import_precision(self): #: TODO: Come up with a better name\n other_company = Company.objects.create(name='Other Co', natural_id='oc')\n ...
[ "0.55593485", "0.5515848", "0.548871", "0.53242356", "0.5323796", "0.5270651", "0.52381533", "0.5179091", "0.51565045", "0.5153947", "0.50942135", "0.50636023", "0.4970877", "0.4866266", "0.48630893", "0.48102677", "0.47713712", "0.47691986", "0.47338426", "0.4730474", "0.470...
0.6230097
0
Tag > UserProfile > User
def test_twice_dependent_object_import(self): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tags(request):\n return Tag.objects.filter(user=request.user)", "def test_tags_limited_to_user_tags(self):\n\n user2 = create_user(\n fname='Test2',\n lname='User2',\n email='test2@gmail.com',\n password='testpass2'\n )\n\n Tag.objects.creat...
[ "0.6036632", "0.59151506", "0.5854669", "0.5790308", "0.5763715", "0.574283", "0.5727083", "0.57143545", "0.57116055", "0.56976116", "0.5677059", "0.5661893", "0.56557196", "0.56339324", "0.5570487", "0.5566566", "0.5553686", "0.5552441", "0.55499566", "0.5542527", "0.5512405...
0.0
-1
Tag > UserProfile > User
def test_partial_twice_dependent_object_import(self): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def tags(request):\n return Tag.objects.filter(user=request.user)", "def test_tags_limited_to_user_tags(self):\n\n user2 = create_user(\n fname='Test2',\n lname='User2',\n email='test2@gmail.com',\n password='testpass2'\n )\n\n Tag.objects.creat...
[ "0.6036632", "0.59151506", "0.5854669", "0.5790308", "0.5763715", "0.574283", "0.5727083", "0.57143545", "0.57116055", "0.56976116", "0.5677059", "0.5661893", "0.56557196", "0.56339324", "0.5570487", "0.5566566", "0.5553686", "0.5552441", "0.55499566", "0.5542527", "0.5512405...
0.0
-1
Image (m)(m)> Tag > UserProfile > User e.g. see factory.create_tags_images for the creation of the below items > We'll assert that populating related data on the m2m field > constructs the expect > retrieves the correct results > doesn't retrieve the incrorrect results Image.pk Image.name Tag.name i grass green i grass blue k sun yellow l grass m sun
def test_m2m_dependent_object_import(self): user_profile: UserProfile = self.user_profiles[0] # See self.setUp() # ************ First Handle generating the Tags/Images Synthetically Through the Importer ************ # Initialize Importers image_manager = ImporterManager(importer=ImageImporter()) tag_manager = ImporterManager(importer=TagImporter()) up_manager = ImporterManager(importer=UserProfileImporter()) company_manger = ImporterManager(importer=CompanyImporter()) user_manager = ImporterManager(importer=UserImporter()) # Populate leaf models of dependency tree with kv data for row,image in enumerate(self.images): user_manager.update_kvs(field_name='username', value=user_profile.user.username, row=row) company_manger.update_kvs(field_name='natural_id', value=self.company.natural_id, row=row) #: Retrieve data associated with kv data user_manager.get_available_rows() company_manger.get_available_rows() #: Populate data up the dependency tree with retrieved rows for row,image in enumerate(self.images): up_manager.update_kvs('company', company_manger.get_object_or_list(row), row=row) up_manager.update_kvs('user', user_manager.get_object_or_list(row), row=row) #: Retrieve data associated with models depended upon up_manager.get_available_rows() tag_manager.update_kvs('slug', 'blue', row=0, col=0) tag_manager.update_kvs('slug', 'green', row=0, col=1) tag_manager.update_kvs('company', company_manger.get_object_or_list(0), row=0, col=0) tag_manager.update_kvs('created_by', up_manager.get_object_or_list(0), row=0, col=0) tag_manager.update_kvs('slug', 'yellow', row=1, col=0) tag_manager.update_kvs('company', company_manger.get_object_or_list(1), row=1, col=0) tag_manager.update_kvs('created_by', up_manager.get_object_or_list(1), row=1, col=0) #: Retrieve associate intermediate data tag_manager.get_available_rows() for row,image in enumerate(self.images): image_manager.update_kvs('path', image.path, row=row) image_manager.update_kvs('name', image.name, row=row) image_manager.update_kvs('tag', tag_manager.get_object_or_list(row), row=row) image_manager.update_kvs('company', company_manger.get_object_or_list(row), row=row) image_manager.get_available_rows() self.assertNotEqual(image_manager.get_object_or_list(0), []) self.assertIsInstance(image_manager.get_object_or_list(0), Image) self.assertNotEqual(image_manager.get_object_or_list(1), []) self.assertIsInstance(image_manager.get_object_or_list(1), Image)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_image(self):\n\n image = Image.query.filter(Image.tag1 == \"Denali\").first()\n self.assertEqual(image.tag1, \"Denali\")", "def test_users_photos_view_set_get_own_photos(self):\n # Create user and data\n user = account_models.User.objects.create_user(email='mrtest@mypapaya.io...
[ "0.6760434", "0.6466026", "0.6373129", "0.620715", "0.61913586", "0.61831266", "0.6162001", "0.61448395", "0.61397374", "0.61137104", "0.6010534", "0.60070205", "0.59996825", "0.5987241", "0.59855795", "0.59617376", "0.5952365", "0.5951813", "0.594541", "0.5944202", "0.594388...
0.57373446
35
Image (m)(m)> Tag > UserProfile > User e.g. see factory.create_tags_images for the creation of the below items > We'll assert that populating related data on the m2m field > constructs the expect > retrieves the correct results > doesn't retrieve the incrorrect results Image.pk Image.name Tag.name company user i grass green x y i grass blue x y k sun yellow x y l grass green q l m sun green q l
def test_m2m_dependent_object_import_precision(self): #: TODO: Come up with a better name other_company = Company.objects.create(name='Other Co', natural_id='oc') _,other_user_profile = create_base_models(username='other', company=other_company) #: Create same named tags <-- assert later that they do not get filtered out as they are from a different #: company blue = Tag.objects.create( company=other_company, created_by=other_user_profile, name='blue', slug='blue', rank=0 ) green = Tag.objects.create( company=other_company, created_by=other_user_profile, name='green', slug='green', rank=2 ) user_profile: UserProfile = self.user_profiles[0] # See self.setUp() # ************ First Handle generating the Tags/Images Synthetically Through the Importer ************ # Initialize Importers image_manager = ImporterManager(importer=ImageImporter()) tag_manager = ImporterManager(importer=TagImporter()) up_manager = ImporterManager(importer=UserProfileImporter()) company_manger = ImporterManager(importer=CompanyImporter()) user_manager = ImporterManager(importer=UserImporter()) # Populate leaf models of dependency tree with kv data for row,image in enumerate(self.images): user_manager.update_kvs(field_name='username', value=user_profile.user.username, row=row) company_manger.update_kvs(field_name='natural_id', value=self.company.natural_id, row=row) #: Retrieve data associated with kv data user_manager.get_available_rows() company_manger.get_available_rows() #: Populate data up the dependency tree with retrieved rows for row,image in enumerate(self.images): up_manager.update_kvs('company', company_manger.get_object_or_list(row), row=row) up_manager.update_kvs('user', user_manager.get_object_or_list(row), row=row) #: Retrieve data associated with models depended upon up_manager.get_available_rows() tag_manager.update_kvs('slug', 'blue', row=0, col=0) tag_manager.update_kvs('slug', 'green', row=0, col=1) #: Anyway to avoid pushing these redundant kvs accross a row (??) tag_manager.update_kvs('company', company_manger.get_object_or_list(0), row=0, col=0) # tag_manager.update_kvs('company', company_manger.get_object_or_list(0), row=0, col=1) tag_manager.update_kvs('created_by', up_manager.get_object_or_list(0), row=0, col=0) # tag_manager.update_kvs('created_by', up_manager.get_object_or_list(0), row=0, col=1) tag_manager.update_kvs('slug', 'yellow', row=1, col=0) tag_manager.update_kvs('company', company_manger.get_object_or_list(1), row=1, col=0) tag_manager.update_kvs('created_by', up_manager.get_object_or_list(1), row=1, col=0) #: Retrieve associate intermediate data tag_manager.get_available_rows() self.assertEqual(len(tag_manager.get_object_or_list(0)), 2) for tag in tag_manager.get_object_or_list(0): self.assertEqual(tag.company_id, self.company.id) self.assertNotEqual(tag.company_id, other_company.id) self.assertIsInstance(tag_manager.get_object_or_list(1), Tag)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_image(self):\n\n image = Image.query.filter(Image.tag1 == \"Denali\").first()\n self.assertEqual(image.tag1, \"Denali\")", "def test_users_photos_view_set_get_own_photos(self):\n # Create user and data\n user = account_models.User.objects.create_user(email='mrtest@mypapaya.io...
[ "0.66079843", "0.6477032", "0.6326245", "0.6268388", "0.6267517", "0.6212116", "0.6183669", "0.61595887", "0.6151405", "0.61384684", "0.60875714", "0.60794526", "0.6066342", "0.60580915", "0.6017938", "0.60149026", "0.600587", "0.6003988", "0.5976658", "0.59595704", "0.595938...
0.56813097
43
Method to be implemented
def update_with_fit_args(self, **kwargs): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __call__(self):\n raise NotImplementedError", "def support(self):", "def __call__(self):\n raise NotImplementedError()", "def __call__(self):\r\n raise NotImplementedError('override me')", "def __call__(self):\n\t\treturn", "def __call__(self) -> None:", "def __call__( self ):\...
[ "0.78358424", "0.7723889", "0.7493241", "0.7416625", "0.7341111", "0.7135667", "0.7118768", "0.71088976", "0.71088976", "0.70884323", "0.69750255", "0.68996793", "0.6808303", "0.6796849", "0.6753698", "0.67092526", "0.66899514", "0.6654799", "0.6654799", "0.6654799", "0.66419...
0.0
-1
Explore a dataset dataset pandas dataset prj_info dictionnary containing projet information (response...)
def explore_data(data,prj_info,TMP=1234): print(" Data file rows and columns are : ", data.shape) #Open pdf pp = PdfPages(prj_info['OUTPUT_PATH'] + "exploration_" + str(TMP) + ".pdf") #Plot average plot_average_reponse(data,prj_info,pp,TMP) #Close pdf pp.close() return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extract_project_details(\n df,\n copy_columns=info_columns,\n column_rename_dict=info_column_rename_dict,\n use_record=0,\n record_index=\"PID_Index\",\n):\n df_details = df.copy().loc[df[record_index] == use_record][copy_columns]\n\n if column_rename_dict:\n df_details = df_details...
[ "0.58241713", "0.57872564", "0.5712627", "0.5473365", "0.5464034", "0.5438289", "0.54039174", "0.53523386", "0.5309826", "0.5266796", "0.5227246", "0.5216134", "0.51905394", "0.5185898", "0.51729375", "0.5161594", "0.5143175", "0.5138437", "0.5124035", "0.51153386", "0.510663...
0.5347947
8
Plot average response for all variables in dataset and save plot in pdf dataset pandas dataset prj_info dictionnary containing projet information (response...)
def plot_average_reponse(data,prj_info,pp=PdfPages("exploration.pdf"),TMP=1234,bins=20): #Copy data data = data.copy() #Slice data data = data.sample(n = min(10000,data.shape[0]),random_state=1234) #Colnames var_to_plot = list(set(data.columns.values)-set(prj_info['PRJ_COLUMN'].values())) #Loop figure pbar = ProgressBar() for var in pbar(var_to_plot): #Bins if data[var].dtype.name != "category" and len(data[var].unique())>bins: data["var_new"] = pd.qcut(data[var], bins, duplicates='drop') else: data["var_new"] = data[var].astype(str) data_plot = data.groupby("var_new").agg({prj_info['PRJ_COLUMN']["RESPONSE"]: 'mean', "var_new": 'count'}) #Table data_plot = data.groupby("var_new").agg({prj_info['PRJ_COLUMN']["RESPONSE"]: 'mean', "var_new": 'count'}) #Build plot f, ax = plt.subplots() ax2 =ax.twinx() sns.barplot(x=data_plot.index.tolist(), y="var_new",data=data_plot,ax=ax, color="dodgerblue") sns.pointplot(x=data_plot.index.tolist(), y=prj_info['PRJ_COLUMN']["RESPONSE"], data=data_plot,ax=ax2, color="chartreuse") ax.set_xlabel(var) ax.set_ylabel(var) ax2.set_ylabel(prj_info['PRJ_COLUMN']["RESPONSE"]) plt.title("Average reponse by " + var) plt.setp(ax.xaxis.get_majorticklabels(), rotation=60) pp.savefig(f) return None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def avg_response_report(df, var_list, y_obs, y_est, file):\n page = PdfPages(file)\n for var in var_list:\n avg_response(df, var, y_obs, y_est, show=False)\n page.savefig()\n page.close()", "def explore_data(data,prj_info,TMP=1234):\r\n print(\" Data file rows and columns are : \", d...
[ "0.7190156", "0.6753629", "0.60996735", "0.6064925", "0.6016448", "0.6008773", "0.60022396", "0.60006684", "0.5999985", "0.59736115", "0.5944627", "0.59434086", "0.5941799", "0.5931249", "0.5897575", "0.5877158", "0.5876371", "0.5840248", "0.58335423", "0.58302295", "0.582852...
0.7230312
0
Create weights as defined in Section 5.1 of our paper.
def create_weights(N, weights_type): if weights_type == "uniform": weights = np.array([1 / N,] * N) elif weights_type == "decreasing": normaliser = sum([1 / i for i in range(1, N + 1)]) weights = np.array([1 / (i * normaliser) for i in range(1, N + 1)]) elif weights_type == "increasing": normaliser = sum([1 / i for i in range(1, N + 1)]) weights = np.array([1 / ((N + 1 - i) * normaliser) for i in range(1, N + 1)]) elif weights_type == "centred": if N % 2 == 1: normaliser = sum([1 / (abs((N + 1) / 2 - i) + 1) for i in range(1, N + 1)]) weights = np.array( [1 / ((abs((N + 1) / 2 - i) + 1) * normaliser) for i in range(1, N + 1)] ) else: normaliser = sum( [1 / (abs((N + 1) / 2 - i) + 0.5) for i in range(1, N + 1)] ) weights = np.array( [ 1 / ((abs((N + 1) / 2 - i) + 0.5) * normaliser) for i in range(1, N + 1) ] ) else: raise ValueError( 'The value of weights_type should be "uniform" or' '"decreasing" or "increasing" or "centred".' ) return weights
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _create_weights(self):\n gate_size = self._hidden_size * self._num_gates\n # Compute the shape of weight and bias.\n matrix_shapes, bias_shapes = [], []\n for layer in range(self._num_layers):\n for direction in range(self._num_directions):\n layer_input_si...
[ "0.7466049", "0.7392558", "0.7357619", "0.72760403", "0.71676654", "0.7089966", "0.7077687", "0.70380753", "0.7031394", "0.7028164", "0.7026333", "0.70108604", "0.69093025", "0.69080865", "0.68695116", "0.68506765", "0.6768174", "0.6768174", "0.6765752", "0.67634475", "0.6748...
0.6555952
38
Runs evaluate on the provided data and generates a detailed error report
def make_report(self, report_name, id_test, x_test, y_test, country_test, frame_test): if not os.path.exists('Reports/' + report_name): os.mkdir('Reports/' + report_name) results = self.predict(x_test) # Generate detailied evaluation report header = 'Country,Child,Frame' for output_layer in self.get_config()['output_layers']: header += ',{}_Actual'.format(output_layer[0]) for output_layer in self.get_config()['output_layers']: header += ',{}_Prediction'.format(output_layer[0]) header += '\n' with open('Reports/{}/evaluation_report.txt'.format(report_name), 'a') as f: if os.stat('Reports/{}/evaluation_report.txt'.format(report_name)).st_size == 0: f.write(header) for row in range(len(results)): entry = ','.join([str(i) for i in country_test[row]]) + ',' entry += ','.join([str(i) for i in id_test[row]]) + ',' entry += ','.join([str(i) for i in frame_test[row]]) + ',' entry += ','.join([str(i) for i in y_test[row]]) + ',' entry += ','.join([str(i) for i in results[row]]) + '\n' f.write(entry) # Generate report of summary statistics cultures = np.unique(country_test) for c in cultures: culture_rows = np.where(country_test == c)[0] # get row numbers for culture c culture_ids = id_test[culture_rows] # get ID rows for culture c unique_ids = np.unique(culture_ids) # get unique IDs for culture c for u in unique_ids: all_id_rows = np.where(id_test == u)[0] id_rows = np.intersect1d(all_id_rows, culture_rows) # get ID rows for child u id_icc = icc(results[id_rows], y_test[id_rows])[0] # compute ICC for child u id_pcc = pcc(results[id_rows], y_test[id_rows])[0][0] # compute PCC for child u id_ccc = ccc(results[id_rows], y_test[id_rows]) # compute CCC for child u id_mae = mae(results[id_rows], y_test[id_rows]) # compute MAE for child u icc_entry = '{},{},{}\n'.format(c, u, id_icc) pcc_entry = '{},{},{}\n'.format(c, u, id_pcc) ccc_entry = '{},{},{}\n'.format(c, u, id_ccc) mae_entry = '{},{},{}\n'.format(c, u, id_mae) with open('Reports/{}/icc_report.txt'.format(report_name), 'a') as f: f.write(icc_entry) with open('Reports/{}/pcc_report.txt'.format(report_name), 'a') as f: f.write(pcc_entry) with open('Reports/{}/ccc_report.txt'.format(report_name), 'a') as f: f.write(ccc_entry) with open('Reports/{}/mae_report.txt'.format(report_name), 'a') as f: f.write(mae_entry) return results
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def evaluate(self, test_data):\n result = self.model.run(test_data)\n self._save_result(result)", "def evaluate(self, dataset):\n\t\tpass", "def evaluate(\n self,\n test_data=None,\n print_report=True,\n save_path=\"ktrain_classification_report.csv\",\n class_na...
[ "0.6641769", "0.66378486", "0.62046313", "0.6194362", "0.6182727", "0.61543846", "0.6143863", "0.61434543", "0.6132906", "0.61051583", "0.6086003", "0.60806614", "0.60806614", "0.6062375", "0.60618806", "0.6046971", "0.604346", "0.603338", "0.60103774", "0.60077417", "0.60042...
0.0
-1
Applies VRTfunctions to a GDALreadable inputfile, rendering outputfile. Functions must be an iterable of singleparameter functions that take a filename as input.
def pipeline(inputfile, outputfile, functions, **kwargs): if not functions: raise ValueError('Must have at least one function') tmpfiles = [] try: previous = inputfile for name, f in functions: logging.debug(name) vrt = f(previous) current = vrt.get_tempfile(suffix='.vrt', prefix='gdal') tmpfiles.append(current) previous = current.name logging.info('Rendering reprojected image') return vrt.render(outputfile=outputfile, **kwargs) finally: for f in tmpfiles: f.close()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def main(fn_input, fn_output):\n # read file\n inter = Interpolator()\n inter.read_file(fn_input)\n inter.write_interpolated(fn_output)", "def merge(files: List[str], output_file: str, resample: str = \"average\") -> None:\n\n build_vrt(constants.TEMP_VRT_FILE, files, resample)\n\n gdal.SetConf...
[ "0.5867644", "0.5854852", "0.55360836", "0.52705306", "0.52492493", "0.52203393", "0.50498486", "0.50492585", "0.49810517", "0.49677193", "0.4958387", "0.49372962", "0.4903304", "0.4866099", "0.4855312", "0.4854982", "0.4847482", "0.48274714", "0.48194093", "0.48180053", "0.4...
0.7520964
0
Takes an inputfile (probably a VRT) and generates a singleband VRT.
def extract_color_band(inputfile, band): dataset = Dataset(inputfile) if not 1 <= band <= dataset.RasterCount: raise ValueError( "band must be between 1 and {0}".format(dataset.RasterCount) ) command = [ GDALTRANSLATE, '-q', # Quiet '-of', 'VRT', # Output to VRT '-b', band, # Single band inputfile, '/vsistdout' ] try: return VRT(check_output_gdal([str(e) for e in command])) except CalledGdalError as e: if e.error == ("ERROR 6: Read or update mode not supported on /vsistdout"): # HACK: WTF?!? return VRT(e.output) raise
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_vrt(vrt: str, files: List[str], resample_name: str) -> None:\n\n options = gdal.BuildVRTOptions(srcNodata=0)\n gdal.BuildVRT(destName=vrt, srcDSOrSrcDSTab=files, options=options)\n add_pixel_fn(vrt, resample_name)", "def run_vorpaline(self, input_file, *options):\n\n self._input_file = ...
[ "0.5761271", "0.539191", "0.53234494", "0.5275649", "0.52752906", "0.527388", "0.5264173", "0.5234479", "0.52175415", "0.52002573", "0.51625293", "0.50720745", "0.50369114", "0.50217336", "0.4970289", "0.4957576", "0.4887836", "0.48874044", "0.48784587", "0.48682615", "0.4843...
0.546153
1
Takes an GDALreadable inputfile and generates the VRT to warp it.
def warp(inputfile, spatial_ref=None, cmd=GDALWARP, resampling=None, maximum_resolution=None): dataset = Dataset(inputfile) warp_cmd = [ cmd, '-q', # Quiet - FIXME: Use logging '-of', 'VRT', # Output to VRT ] # Warping to Mercator. if spatial_ref is None: spatial_ref = SpatialReference.FromEPSG(EPSG_WEB_MERCATOR) warp_cmd.extend(['-t_srs', spatial_ref.GetEPSGString()]) # Resampling method if resampling is not None: if not isinstance(resampling, basestring): try: resampling = RESAMPLING_METHODS[resampling] except KeyError: raise UnknownResamplingMethodError(resampling) elif resampling not in list(RESAMPLING_METHODS.values()): raise UnknownResamplingMethodError(resampling) warp_cmd.extend(['-r', resampling]) # Propagate No Data Value nodata_values = [dataset.GetRasterBand(i).GetNoDataValue() for i in range(1, dataset.RasterCount + 1)] if any(nodata_values): nodata_values = [str(v).lower() for v in nodata_values] warp_cmd.extend(['-dstnodata', ' '.join(nodata_values)]) # Call gdalwarp warp_cmd.extend([inputfile, '/vsistdout']) try: return VRT(check_output_gdal([str(e) for e in warp_cmd])) except CalledGdalError as e: if e.error == ("ERROR 6: Read or update mode not supported on /vsistdout"): return VRT(e.output) raise
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_vrt(self):\n for index, i in enumerate(self.months):\n month = str(index + 1)\n if len(month) < 2:\n month = '0' + month\n txt_file = i.joinpath('subnational/tiffs.txt')\n outfile = i.joinpath(f'{self.country}_{month}_normalised.vrt')\n ...
[ "0.6332105", "0.6148278", "0.60546756", "0.6035137", "0.59595346", "0.58744794", "0.58276", "0.58268255", "0.57943213", "0.57037807", "0.56656307", "0.5467358", "0.541127", "0.5396852", "0.53866345", "0.53866345", "0.53640836", "0.5348823", "0.52539855", "0.5224854", "0.51994...
0.6055037
2
Returns gdal.Band.GetNoDataValue() as a NumPy type
def GetNoDataValue(self): result = super(Band, self).GetNoDataValue() if result is not None: return self.NumPyDataType(result)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_band_nodata(self, band_idx=1):\n if band_idx < 1 or band_idx > self.dataset.RasterCount:\n raise IndexError(\"band index is out of range\")\n return self.dataset.GetRasterBand(band_idx).GetNoDataValue()", "def _nodata_value(self):\n try:\n nodata = float(self._i...
[ "0.7544999", "0.7434405", "0.7288697", "0.6567842", "0.6520311", "0.6363698", "0.6319562", "0.62501335", "0.6163293", "0.61502856", "0.61502856", "0.61240387", "0.6110622", "0.60905856", "0.590359", "0.5895869", "0.58876556", "0.58424926", "0.58220965", "0.5796688", "0.577856...
0.86186093
0
Returns the NumPy type associated with gdal.Band.DataType
def NumPyDataType(self): datatype = self.DataType if datatype == gdalconst.GDT_Byte: pixeltype = self.GetMetadataItem('PIXELTYPE', 'IMAGE_STRUCTURE') if pixeltype == 'SIGNEDBYTE': return numpy.int8 return numpy.uint8 elif datatype == gdalconst.GDT_UInt16: return numpy.uint16 elif datatype == gdalconst.GDT_UInt32: return numpy.uint32 elif datatype == gdalconst.GDT_Int16: return numpy.int16 elif datatype == gdalconst.GDT_Int32: return numpy.int32 elif datatype == gdalconst.GDT_Float32: return numpy.float32 elif datatype == gdalconst.GDT_Float64: return numpy.float64 else: raise ValueError( "Cannot handle DataType: {0}".format( gdal.GetDataTypeName(datatype) ) )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_band_dtype(self, band_idx=1):\n if band_idx < 1 or band_idx > self.dataset.RasterCount:\n raise IndexError(\"band index is out of range\")\n return self.dataset.GetRasterBand(band_idx).DataType", "def type(self):\n # type: () -> type\n return _python_type_map[str(se...
[ "0.7380224", "0.7158212", "0.6904815", "0.68386203", "0.67266405", "0.6708839", "0.66951716", "0.663477", "0.663243", "0.6614309", "0.6602418", "0.6594213", "0.65762633", "0.65756744", "0.65720206", "0.657198", "0.6555877", "0.6555877", "0.6546687", "0.65154874", "0.6515137",...
0.76264346
0
Returns the minimum value that can be stored in this band
def MinimumValue(self): datatype = self.NumPyDataType if issubclass(datatype, numpy.integer): return numpy.iinfo(datatype).min elif issubclass(datatype, numpy.floating): return -numpy.inf else: raise TypeError("Cannot handle DataType: {0}".format(datatype))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def min(self):\n if self.kind == 'u':\n return 0\n else:\n try:\n val = iinfo._min_vals[self.key]\n except KeyError:\n val = int(-(1 << (self.bits-1)))\n iinfo._min_vals[self.key] = val\n return val", "def min(...
[ "0.7944226", "0.7944226", "0.7937631", "0.78972983", "0.7884411", "0.78611416", "0.7846386", "0.7778144", "0.77733576", "0.7762124", "0.7680303", "0.7642864", "0.75792414", "0.75792414", "0.75784636", "0.7551094", "0.75474113", "0.75474113", "0.7521111", "0.7521111", "0.74849...
0.7393505
28
Returns the minimum value that can be stored in this band
def MaximumValue(self): datatype = self.NumPyDataType if issubclass(datatype, numpy.integer): return numpy.iinfo(datatype).max elif issubclass(datatype, numpy.floating): return numpy.inf else: raise TypeError("Cannot handle DataType: {0}".format(datatype))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def min(self):\n if self.kind == 'u':\n return 0\n else:\n try:\n val = iinfo._min_vals[self.key]\n except KeyError:\n val = int(-(1 << (self.bits-1)))\n iinfo._min_vals[self.key] = val\n return val", "def min(...
[ "0.7944226", "0.7944226", "0.7937631", "0.78972983", "0.7884411", "0.78611416", "0.7846386", "0.7778144", "0.77733576", "0.7762124", "0.7680303", "0.7642864", "0.75792414", "0.75792414", "0.75784636", "0.7551094", "0.75474113", "0.75474113", "0.7521111", "0.7521111", "0.74849...
0.0
-1
Returns the next `value` expressible in this band
def IncrementValue(self, value): datatype = self.NumPyDataType if issubclass(datatype, numpy.integer): if not isinstance(value, (int, numpy.integer)): raise TypeError( 'value {0!r} must be compatible with {1}'.format( value, datatype.__name__ ) ) iinfo = numpy.iinfo(datatype) minint, maxint = iinfo.min, iinfo.max if not minint <= value <= maxint: raise ValueError( 'value {0!r} must be between {1} and {2}'.format( value, minint, maxint ) ) if value == maxint: return maxint return value + 1 elif issubclass(datatype, numpy.floating): if not isinstance(value, (int, numpy.integer, float, numpy.floating)): raise TypeError( "value {0!r} must be compatible with {1}".format( value, datatype.__name__ ) ) if value == numpy.finfo(datatype).max: return numpy.inf return numpy.nextafter(datatype(value), datatype(numpy.inf)) else: raise TypeError("Cannot handle DataType: {0}".format(datatype))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_next(self) -> float:\n return self._current + self._offset", "def get_next(self) -> int:\n return self._current * self._step + self._offset", "def value(self):\n current_value = self.initial_value * self.schedule(self.step / self.nvalues)\n self.step += 1.\n return cu...
[ "0.69069135", "0.6903918", "0.68510103", "0.6794112", "0.6782542", "0.66370076", "0.66035736", "0.65092635", "0.6481222", "0.6430199", "0.6414499", "0.6410997", "0.63769144", "0.63592046", "0.63583064", "0.63552517", "0.63462645", "0.63152736", "0.6294821", "0.62673527", "0.6...
0.0
-1
Opens a GDALreadable file. Raises a GdalError if inputfile is invalid.
def __init__(self, inputfile, mode=GA_ReadOnly): # Open the input file and read some metadata open(inputfile, 'r').close() # HACK: GDAL gives a useless exception if not isinstance(inputfile, bytes): inputfile = inputfile.encode('utf-8') try: # Since this is a SWIG object, clone the ``this`` pointer self.this = gdal.Open(inputfile, mode).this except RuntimeError as e: raise GdalError(str(e)) # Shadow for metadata so we can overwrite it without saving # it to the original file. self._geotransform = None self._rastersizes = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load(self):\r\n\r\n #Open the dataset read only using GDAL\r\n dataset = gdal.Open(self.inputds, gdal.GA_ReadOnly)\r\n \r\n return dataset\r\n \r\n\r\n #print \"Failed to open %s. Is it a GDAL supported format?\" %(self.inputds)\r", "def open_input(self):\n gd...
[ "0.67583877", "0.6669646", "0.6662748", "0.6427024", "0.5995178", "0.57921493", "0.5738032", "0.5566471", "0.5458556", "0.5453362", "0.5418001", "0.5346144", "0.5346144", "0.5330134", "0.52282006", "0.52168894", "0.5216014", "0.5212678", "0.5209175", "0.51660335", "0.5159364"...
0.62465745
4
Returns whether the dataset covers the whole world or not.
def IsWholeWorld(self, resolution=None): if resolution is None: resolution = self.GetNativeResolution() spatial_ref = self.GetSpatialReference() world_extents = spatial_ref.GetWorldExtents() extents = self.GetExtents() ll_offset = world_extents.lower_left - extents.lower_left ur_offset = world_extents.upper_right - extents.upper_right pixel_sizes = spatial_ref.GetPixelDimensions(resolution=resolution) return (abs(ll_offset.x) <= pixel_sizes.x and abs(ll_offset.y) <= pixel_sizes.y and abs(ur_offset.x) <= pixel_sizes.x and abs(ur_offset.y) <= pixel_sizes.y)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def is_full_dimensional(self):\n\n return self.affine_dimension() == self.space_dimension()", "def is_dataset(self):\n return self._dataset is not None", "def ejscreen_areas_of_concern_data_exists(cls):\n return cls.EJSCREEN_AREAS_OF_CONCERN_SOURCE.is_file()", "def is_mainland(self):\n ...
[ "0.6345008", "0.63167757", "0.61752814", "0.60833305", "0.60241663", "0.6015851", "0.5980115", "0.59584624", "0.5937705", "0.5922513", "0.5917669", "0.59084296", "0.5877617", "0.5835224", "0.5827307", "0.5806919", "0.5801645", "0.57821", "0.5778381", "0.57413006", "0.57294166...
0.68909526
0
of the source data; this usually means upsampling the data, but if the pixel dimensions are slightly smaller than a given resolution, and equal within error tolerance, that resolution will get chosen as the native one.
def GetNativeResolution(self, transform=None, maximum=None): # Get the source projection's units for a 1x1 pixel, assuming square # pixels. width, height = self.GetPixelDimensions() src_pixel_size = min(abs(width), abs(height)) if transform is None: dst_pixel_size = src_pixel_size dst_ref = self.GetSpatialReference() else: # Transform these dimensions into the destination projection dst_pixel_size = transform.TransformPoint(src_pixel_size, 0)[0] dst_pixel_size = abs(dst_pixel_size) dst_ref = transform.dst_ref # We allow some floating point error between src_pixel_size and # dst_pixel_size based on the major circumference so that the error is # in the destination units error = max(*dst_ref.GetPixelDimensions(resolution=0)) / 128 # Find the resolution where the pixels are smaller than dst_pixel_size. for resolution in count(): if maximum is not None and resolution >= maximum: return resolution res_pixel_size = max( *dst_ref.GetPixelDimensions(resolution=resolution) ) if (res_pixel_size - dst_pixel_size) <= error: return resolution # Halve error each resolution error /= 2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def change_resolution(img):\n scale_factor = np.random.choice(list(range(0, 6, 2)))\n if scale_factor == 0:\n return img\n downsample = nn.AvgPool2d(scale_factor)\n upsample = nn.UpsamplingNearest2d(scale_factor=scale_factor)\n new_res_img = upsample(downsample(img.unsqueeze(dim=1))).squeeze()\n return ne...
[ "0.5770578", "0.5644546", "0.56255263", "0.55761415", "0.54033136", "0.5392939", "0.536528", "0.5364385", "0.5331956", "0.5313504", "0.5307943", "0.5276826", "0.52704465", "0.52479804", "0.5238506", "0.5231732", "0.52003103", "0.517683", "0.5145478", "0.51325125", "0.51163715...
0.0
-1
Returns the (width, height) of pixels in this Dataset's units.
def GetPixelDimensions(self): _, width, _, _, _, height = self.GetGeoTransform() return XY(x=width, y=height)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def dimensions (self):\n return (self.width, self.height)", "def get_size(self) -> Tuple2IntType:\n return self.get_width(), self.get_height()", "def size(self):\n return self.width, self.height", "def get_size_inches(self):\n width, height = self.figure.get_size_inches()\n ...
[ "0.7506064", "0.7479907", "0.7441489", "0.74142814", "0.7389819", "0.7367811", "0.73565596", "0.73126996", "0.72868365", "0.7277576", "0.72565204", "0.7253058", "0.72077274", "0.72069263", "0.71481836", "0.7120468", "0.7104735", "0.70551723", "0.7054781", "0.70520395", "0.704...
0.77364904
0
Transforms pixel coordinates into the destination projection. If transform is None, no reprojection occurs and the dataset's SpatialReference is used.
def PixelCoordinates(self, x, y, transform=None): # Assert that pixel_x and pixel_y are valid if not 0 <= x <= self.RasterXSize: raise ValueError('x %r is not between 0 and %d' % (x, self.RasterXSize)) if not 0 <= y <= self.RasterYSize: raise ValueError('y %r is not between 0 and %d' % (y, self.RasterYSize)) geotransform = self.GetGeoTransform() coords = XY( geotransform[0] + geotransform[1] * x + geotransform[2] * y, geotransform[3] + geotransform[4] * x + geotransform[5] * y ) if transform is None: return coords # Reproject return XY(*transform.TransformPoint(coords.x, coords.y)[0:2])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _reproject(ds, dst_crs=None, dst_transform=None, width=None, height=None,\n res=None, extent=None, **kwargs):\n\n if 'resampling' not in kwargs:\n kwargs['resampling'] = rasterio.warp.Resampling.cubic\n\n src_crs = get_crs(ds)\n src_bounds = get_bounds(ds)\n if extent is not No...
[ "0.6720557", "0.6548644", "0.6337521", "0.6230713", "0.62149775", "0.58759457", "0.58334744", "0.5782975", "0.5738817", "0.56981885", "0.5647636", "0.5635617", "0.5624577", "0.5602451", "0.55902624", "0.5584441", "0.5567373", "0.55569345", "0.55569345", "0.5550751", "0.552929...
0.5615591
13
Returns (lowerleft, upperright) extents in transform's destination projection. If transform is None, no reprojection occurs and the dataset's SpatialReference is used.
def GetExtents(self, transform=None): # Prepare GDAL functions to compute extents x_size, y_size = self.RasterXSize, self.RasterYSize # Compute four corners in destination projection upper_left = self.PixelCoordinates(0, 0, transform=transform) upper_right = self.PixelCoordinates(x_size, 0, transform=transform) lower_left = self.PixelCoordinates(0, y_size, transform=transform) lower_right = self.PixelCoordinates(x_size, y_size, transform=transform) x_values, y_values = list(zip(upper_left, upper_right, lower_left, lower_right)) # Return lower-left and upper-right extents return Extents(lower_left=XY(min(x_values), min(y_values)), upper_right=XY(max(x_values), max(y_values)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def extent(self):\n left = self.transform[0]\n right = left + self.transform[1] * self.shape[1]\n top = self.transform[3]\n bottom = top + self.transform[5] * self.shape[0]\n return left, right, bottom, top", "def extent(self):\n if self.x is not None:\n if se...
[ "0.6707964", "0.62306535", "0.61376554", "0.58643377", "0.58163196", "0.5813695", "0.5760055", "0.5748703", "0.57084984", "0.5700975", "0.56836563", "0.5661239", "0.5635688", "0.5632432", "0.56189066", "0.5601325", "0.55867517", "0.5552704", "0.5544527", "0.5532464", "0.55125...
0.75209373
0
Get the scaling ratios required to upsample an image to `resolution`. If resolution is None, then assume it will be upsampled to the native destination resolution. See Dataset.GetNativeResolution() If places is not None, rounds the ratios to the number of decimal places specified.
def GetScalingRatios(self, resolution=None, places=None): if resolution is None: resolution = self.GetNativeResolution(transform=None) # Get the pixel dimensions in map units. There is no custom transform, # because it makes no sense to compute a pixel ratio for a # reprojection. spatial_ref = self.GetSpatialReference() dst_pixel_width, dst_pixel_height = spatial_ref.GetPixelDimensions( resolution=resolution ) src_pixel_width, src_pixel_height = self.GetPixelDimensions() xscale = abs(src_pixel_width / dst_pixel_width) yscale = abs(src_pixel_height / dst_pixel_height) if places is not None: xscale = round(xscale, places) yscale = round(yscale, places) return XY(x=xscale, y=yscale)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetWorldScalingRatios(self, resolution=None, places=None):\n if resolution is None:\n resolution = self.GetNativeResolution()\n\n spatial_ref = self.GetSpatialReference()\n world = spatial_ref.GetWorldExtents().dimensions\n src_pixel_sizes = XY(x=world.x / self.RasterXSiz...
[ "0.66777146", "0.5513569", "0.5297719", "0.5258411", "0.51001024", "0.50386363", "0.50341105", "0.50095075", "0.49838406", "0.49593174", "0.48953298", "0.48382708", "0.47824258", "0.4761503", "0.47418657", "0.47418657", "0.47418657", "0.47353554", "0.46934766", "0.46716377", ...
0.7302088
0
Returns (lowerleft, upperright) TMS tile coordinates. The upperright coordinates are excluded from the range, while the lowerleft are included.
def GetTmsExtents(self, resolution=None, transform=None): if resolution is None: resolution = self.GetNativeResolution(transform=transform) # Get the tile dimensions in map units if transform is None: spatial_ref = self.GetSpatialReference() else: spatial_ref = transform.dst_ref tile_width, tile_height = spatial_ref.GetTileDimensions( resolution=resolution ) # Validate that the native resolution extents are tile-aligned. extents = self.GetTiledExtents(transform=transform) pixel_sizes = spatial_ref.GetPixelDimensions(resolution=resolution) if not extents.almost_equal(self.GetExtents(transform=transform), delta=min(*pixel_sizes)): raise UnalignedInputError('Dataset is not aligned to TMS grid') # Correct for origin, because you can't do modular arithmetic on # half-tiles. left, bottom = spatial_ref.OffsetPoint(*extents.lower_left) right, top = spatial_ref.OffsetPoint(*extents.upper_right) # Divide by number of tiles return Extents(lower_left=XY(int(round(left / tile_width)), int(round(bottom / tile_height))), upper_right=XY(int(round(right / tile_width)), int(round(top / tile_height))))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def getupperleft(self):\n return (self.rect.x, self.rect.y)", "def topLeftCorner(self):\n self._updateExtents()\n return (self._mMinX,self._mMinY)", "def topRightCorner(self):\n self._updateExtents()\n return (self._mMaxX,self._mMinY)", "def get_tile_location(self):\n ...
[ "0.67502934", "0.65008754", "0.6489868", "0.6368388", "0.6322317", "0.63027024", "0.62114066", "0.6206572", "0.6173504", "0.61361134", "0.6121037", "0.6087851", "0.60849476", "0.6061991", "0.6028953", "0.59848636", "0.59517145", "0.59340775", "0.5899759", "0.589703", "0.58896...
0.0
-1