Dataset Viewer
Auto-converted to Parquet Duplicate
code
stringlengths
46
37.2k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.91
max_line_length
int64
13
399
avg_line_length
float64
5.67
140
num_lines
int64
7
299
original_docstring
stringlengths
22
42.6k
source
stringclasses
2 values
function stringToEthereumNetworkId(ethereumNetworkName) { let errPrefix = "(stringToEthereumNetworkId) "; if (common_routines.isEmptyString(ethereumNetworkName)) throw new Error(errPrefix + "The Ethereum network name is empty."); if (ethereumNetworkName == 'MAIN') return EnumEthereumNetwork.MAIN; if (ethereumNe...
javascript
9
0.781088
86
39.684211
19
/** * Convert an Ethereum network name to an Ethereum network ID enum. * * @param {string} ethereumNetworkName - The Ethereum network name to convert. * * @return {EnumEthereumNetwork} - Returns the enum that represents the given * Ethereum network name. * */
function
public static Color ColorFromHsl(double hue, double saturation, double brightness) { double normalizedHue = hue / 360; double red, green, blue; if (brightness == 0) { red = green = blue = 0; } else { ...
c#
25
0.298614
113
37.419355
62
/// <summary> /// Converts a colour from HSL to RGB. /// </summary> /// <remarks>Adapted from the algoritm in Foley and Van-Dam</remarks> /// <param name="hue">A double representing degrees ranging from 0 to 360 and is equal to the GetHue() on a Color structure.</param> /// <param name="saturation">A double value rangi...
function
func DecryptS(ptype string, val sql.NullString, data []byte, clear bool) (string, error) { if !sdk.NeedPlaceholder(ptype) && val.Valid { return val.String, nil } if len(data) == (nonceSize + macSize) { return "", nil } if !clear { return sdk.PasswordPlaceholder, nil } if val.Valid { return val.String, ni...
go
8
0.647202
90
20.684211
19
// DecryptS wrap Decrypt and: // - return Placeholder instead of value if not needed // - cast returned value in string
function
def start_session(username, **kwargs): remember = kwargs.get("remember", True) u = Users.load_user(username) if u is None: u = Users({"username":username, "password":random_str()}) if not u._auto_create(): if username in Users.RESERVED: ...
python
15
0.530903
72
44.142857
14
after user is successfully authenticated, start user session if user is not in local database, add them
function
@ApplicationPath("/rest") @Path("/personaldata") public class PersonalDataExtractor extends Application { final static Logger logger = Logger.getLogger(PersonalDataExtractor.class); /** * This method extracts personal data and scores those personal data. * Output data is formatted so that it can be consumed by ...
java
14
0.713258
86
30.73913
92
/** * Personal Data Extractor and scorer REST interface. It has two POST methods. * "/forviewer" method's response is intended to be consumed by UI (D3), which * requires a particular format of data. "/forconsumer" method's response is * more generic and can be consumed by other applications which can then use the ...
class
public abstract class Util { /** * An instance of Util, containing the method implementations. * <br><br> * It is set during CraftGuide's {@literal @PreInit}. */ public static Util instance; /** * Causes CraftGuide to clear its list of recipes, and reload them with * exactly the same process that was or...
java
6
0.719896
74
34.121212
66
/** * Contains a number of methods that implement common functionality * that would otherwise need to be implemented by everyone who uses * the API, or that relies on parts of CraftGuide not included in * the API. */
class
private static class CompiledExpKey { private final Exp exp; private final boolean scalar; private final ResultStyle resultStyle; private int hashCode = Integer.MIN_VALUE; private CompiledExpKey( Exp exp, boolean scalar, ResultStyle resultStyl...
java
11
0.49574
62
30.512195
41
/** * Just a simple key of Exp/scalar/resultStyle, used for keeping * compiled expressions. Previous to the introduction of this * class, the key was a list constructed as Arrays.asList(exp, scalar, * resultStyle) and having poorer performance on equals, hashCode, * and construction. */
class
def check_depths(self): counter, graph = 1, [] for rule in sorted(self.rules.keys()): choices = self.rules[rule]['choices'] self.non_terminals[rule]['b_factor'] = self.rules[rule][ 'no_choices'] for choice in choices: graph.append([rule...
python
16
0.475087
68
42.2
20
Run through a grammar and find out the minimum distance from each NT to the nearest T. Useful for initialisation methods where we need to know how far away we are from fully expanding a tree relative to where we are in the tree and what the depth limit is. :return: Nothing. ...
function
public boolean growSpores(World world, BlockPos pos, Random random) { float sporeChance = 0.5F; float sporeChancePicked = random.nextFloat(); if (sporeChancePicked <= sporeChance) { world.setBlockState(pos, this.getDefaultState().with(LIT, true)); return true; } ...
java
11
0.618497
77
37.555556
9
/** * This method decides whether the blood kelp should have spores. * * @param world * @param pos The position of the new block. * @param random */
function
func (w *Map180) SVG(boundingBox string, width int, markers []Marker, insetBbox string) (buf bytes.Buffer, err error) { var b bbox if boundingBox == "" { b, err = newBboxFromMarkers(markers) if err != nil { return } } else { b, err = newBbox(boundingBox) if err != nil { return } } m, err := b.new...
go
14
0.592847
154
24.670588
85
/* SVG draws an SVG image showing a map of markers. The returned map uses EPSG3857. Width is the SVG image width in pixels (height is calculated). If boundingBox is the empty string then the map bounds are calculated from the markers. See ValidBbox for boundingBox options. */
function
def read_rst_data(self, win_idx, datasets, path_points, bbox, meta): window = path_points[win_idx] window_height, window_width = np.array([np.abs(bbox[win_idx][2] - bbox[win_idx][0]), ...
python
15
0.386059
108
45.65625
32
Return data windows and final bounds of window :param win_idx: int window index :param datasets: list of int representing dataset inx :param path_points: list of bbox for windows :param bbox: list of ul/br coords of windows :param meta: metadata for final dataset ...
function
public UsbDeviceConnectionWrapper OpenDevice(UsbDevice Device, UsbInterface Interface, boolean ForceClaim) { UsbDeviceConnection u = manager.openDevice(Device); u.claimInterface(Interface, ForceClaim); UsbDeviceConnectionWrapper uu = new UsbDeviceConnectionWrapper(); uu.connection = u; uu.usbInterface = Inter...
java
7
0.800587
108
41.75
8
/** * Connects to the given device and claims exclusive access to the given interface. *ForceClaim - Whether the system should disconnect kernel drivers if necessary. */
function
def to_image_list(tensors, size_divisible=0, shapes=None): if isinstance(tensors, torch.Tensor) and size_divisible > 0: assert False, "code path not tested with cuda graphs" tensors = [tensors] if isinstance(tensors, ImageList): return tensors elif isinstance(tensors, torch.Tensor): ...
python
19
0.555771
87
50.575
40
tensors can be an ImageList, a torch.Tensor or an iterable of Tensors. It can't be a numpy array. When tensors is an iterable of Tensors, it pads the Tensors with zeros so that they have the same shape
function
@Test public void testSearchesWithConcepts() { final TopicMapView topicMap = elementFactory.getFindPage().goToTopicMap(); topicMap.waitForMapLoaded(); final String selectedConcept = topicMap.clickNthClusterHeading(0); elementFactory.getFindPage().waitUntilSavePossible(); save...
java
10
0.724652
88
58.235294
17
// Checks that the saved-ness of the search respects the selected concepts
function
public static MimeType parse(final String mimeType) { if (mimeType == null || "".equals(mimeType.trim())) { throw new IllegalArgumentException("Mime Type can not be empty"); } final Matcher mimeMatcher = MIME_REGEX.matcher(mimeType); if (!mimeMatcher.matches()) { ...
java
10
0.612412
87
49.294118
17
/** * Parses a mime type string including media range and returns a MimeType * object. For example, the media range 'application/*;q=0.5' would get * parsed into: ('application', '*', {'q', '0.5'}). * * @param mimeType the mime type to parse * @return a MimeType object */
function
def to_code(f, arg_value_hints=None, indentation=' '): conversion_map = conversion.ConversionMap() conversion.object_to_graph(f, conversion_map, arg_value_hints) imports = '\n'.join(config.COMPILED_IMPORT_STATEMENTS) code = '\n'.join( compiler.ast_to_source(dep, indentation) for dep in reversed(tup...
python
15
0.693046
64
45.444444
9
Return the equivalent of a function in TensorFlow code. Args: f: A Python function with arbitrary arguments and return values. arg_value_hints: A dict mapping parameter names to objects that can hint at the type of those parameters. indentation: String, when to use for each level of indentation. ...
function
void clean_ipv6_addr(int addr_family, char *addr) { #ifdef HAVE_IPV6 if (addr_family == AF_INET6) { char *pct = strchr(addr, '%'); if (pct) *pct = '\0'; } #endif }
c
11
0.483254
44
16.5
12
/* * clean_ipv6_addr --- remove any '%zone' part from an IPv6 address string * * XXX This should go away someday! * * This is a kluge needed because we don't yet support zones in stored inet * values. Since the result of getnameinfo() might include a zone spec, * call this to remove it anywhere we want to feed ...
function
public class ComplexPiece { /** The ID. */ private final int id; /** The amount of pieces in the complex object. */ private final int pieceAmount; /** The byte array of the data and checksum. */ private final byte[] data, checksum; /** Instance of the protocol. */ private final IProtocol prot...
java
14
0.685215
162
35.508621
116
/** * Networking Library * ComplexPiece.java * Purpose: A piece of a object's byte array that corresponds to a complex object. This piece's data is sent over a socket * and recreated into an object later on. * * @author Jon R (Baseball435) * @version 1.0 7/25/2014 */
class
const SSCHAR* FindTextVariable (const SSCHAR* pString, const textreplace_t ReplaceInfo[]) { int Index; for (Index = 0; ReplaceInfo[Index].pVariable != NULL; ++Index) { if (stricmp(ReplaceInfo[Index].pVariable, pString) == 0) return (ReplaceInfo[Index].pValue); } return (NULL); }
c++
13
0.696246
96
41
7
/*=========================================================================== * * Function - const SSCHAR* FindTextVariable (pString, ReplaceInfo); * * Find a variable in an array of replacement information. Returns the * matching record value (case insensitive) on success or NULL if not found. * *=======...
function
Region * Region::GetFirstAncestorOfNonExceptingFinallyParent() { Region * ancestor = this; while (ancestor && ancestor->IsNonExceptingFinally()) { ancestor = ancestor->GetParent(); } Assert(ancestor && !ancestor->IsNonExceptingFinally()); if (ancestor && ancestor->GetType() != RegionType...
c++
10
0.683946
108
36.4375
16
// Return the first ancestor of the region's parent which is not a non exception finally // Skip all non exception finally regions in the region tree // Return the parent of the first non-non-exception finally region
function
protected void simplifyTransforms() { net.imglib2.concatenate.ConcatenateUtils.join( transforms ); for ( final ListIterator< Transform > i = transforms.listIterator(); i.hasNext(); ) { final Transform t = i.next(); if ( Mixed.class.isInstance( t ) ) { final Mixed mixed = ( Mixed ) t; if ( isIden...
java
17
0.634583
88
30.756757
37
/** * Simplify the {@link #transforms} list. First, concatenate neighboring * transforms if possible. Then, for every {@link Mixed} transform: * <ul> * <li>remove it if it is the identity transforms. * <li>replace it by a {@link TranslationTransform} if it is a pure * translation. * <li>replace it by a {@...
function
private void startTask() { try { getClosestWater(); }catch (NullPointerException e) { destination = new Point(world.getWidth(),world.getHeight()); } if (currentTarget != null) { destination = currentTarget.getLocation(); } }
java
12
0.672131
63
23.5
10
/** * Finds the closest water body and makes the alligator go towards it. * Also finds any animal whilst going towards the water body, and makes * the alligator go towards it first. */
function
public Bitmap GetBitmap(int mipmapLevel) { byte[] pic = GetPixels(mipmapLevel, out int w, out int h, colorEncoding == BlpColorEncoding.Argb8888 ? false : true); Bitmap bmp = new Bitmap(w, h); BitmapData bmpdata = bmp.LockBits(new System.Drawing.Rectangle(0, 0, w, h), ImageLoc...
c#
14
0.625251
142
54.555556
9
/// <summary> /// Converts the BLP to a System.Drawing.Bitmap /// </summary> /// <param name="mipmapLevel">The desired Mipmap-Level. If the given level is invalid, the smallest available level is choosen</param> /// <returns>The Bitmap</returns>
function
static void split_escape_and_log(char *tmpbuf, int len) { char *p = tmpbuf; tmpbuf += len; while (p < tmpbuf) { char c; char *q = G.parsebuf; int pri = (LOG_USER | LOG_NOTICE); if (*p == '<') { pri = bb_strtou(p + 1, &p, 10); if (*p == '>') p++; if (pri & ~(LOG_FACMASK | LOG_PRIMASK)) pri = ...
c
14
0.438721
55
19.142857
28
/* tmpbuf[len] is a NUL byte (set by caller), but there can be other, * embedded NULs. Split messages on each of these NULs, parse prio, * escape control chars and log each locally. */
function
public class FrameFixedFieldTupleAppender implements IFrameTupleAppender, IFrameFieldAppender { private FrameFixedFieldAppender fieldAppender; private FrameTupleAppender tupleAppender; private IFrame sharedFrame; private IFrameAppender lastAppender; public FrameFixedFieldTupleAppender(int numField...
java
15
0.7106
119
37.080357
112
/** * This appender can appendTuple and appendField but at the expense of additional checks. * Please use this Field/Tuple mixed appender only if you don't know the sequence of append functions. * Try using {@link FrameFixedFieldAppender} if you only want to appendFields. * and using {@link FrameTupleAppender} if y...
class
func cleanAssetName(path, basePath, prependPath string) string { var name string path, basePath, prependPath = strings.TrimSpace(path), strings.TrimSpace(basePath), strings.TrimSpace(prependPath) basePath, err := filepath.Abs(basePath) if err != nil { basePath = "" } apath, err := filepath.Abs(path) if err == ...
go
14
0.667742
115
28.09375
32
// cleanAssetName returns an asset name from the parent dirname and // the file name without extension. // The combination // path=/tmp/css/default.css // basePath=/tmp/ // prependPath=new/ // will return // new/css/default
function
function aggregate(sAlias) { var oDetails = oAggregation.aggregate[sAlias], sAggregate = oDetails.name || sAlias, sGrandTotal = sAlias, sWith = oDetails.with; if (sWith) { if ((sWith === "average" || sWith === "countdistinct") && (oDetails.grandTotal || oDetails.subtotals)) { th...
javascript
15
0.559623
70
28
33
/* * Returns the corresponding part of the "aggregate" term for an aggregatable property, * for example "AggregatableProperty with method as Alias". Processes min/max as a side * effect. * * @param {string} sAlias - An aggregatable property name * @returns {string} - Part of the "aggregate" term...
function
public static JMenu createMenu(String name, Action[] actions) { final JMenu menu = new JMenu(name); if (actions != null) { for (final Action action : actions) { menu.add(new JMenuItem(action)); } } return menu; }
java
12
0.561338
63
29
9
/** * Creates a JMenu * @param name the name of the menu. * @param actions an array of actions. * @return the newly created JMenu with the corresponding items. */
function
def migrate_48(TRN): TRN.add("SELECT " "ag_login_id, " "participant_name, " "ag_consent_backup.participant_email, " "is_juvenile, " "parent_1_name, " "parent_2_name, " "deceased_parent, " ...
python
16
0.389987
79
41.06338
142
In order to support the REST api, we need participants to have unique ids. This is a change from the previous keying in ag_consent which worked off of a compound key (ag_login_id, participant_name). As part of schema change 48, we are generating new unique IDs for all sources,...
function
protected void ThreePointCalibration(int frameNumber, Image8 camImage, out IppiPoint? poi) { poi = null; if(_threePointPoints.Origin.x == -1) { var p = MoveAndDetect(_threePointFrame, camImage, new IppiPoint_32f(0.0f, 0.0f)); if (p.x != -1) ...
c#
21
0.54739
136
56.166667
60
/// <summary> /// Runs the initial three point calibration to find approximate camera height and angle/reflection /// </summary> /// <param name="frameNumber">The current camera frame number</param> /// <param name="camImage">The camera image</param> /// <param name="poi">The detected beam centroid</param>
function
private void addSingleton(TempCluster clus, DBIDRef id, double dist, boolean asCluster) { if(asCluster) { clus.addChild(makeCluster(id, dist, null)); } else { clus.add(id); } clus.depth = dist; }
java
10
0.578947
89
26.555556
9
/** * Add a singleton object, as point or cluster. * * @param clus Current cluster. * @param id Object to add * @param dist Distance * @param asCluster Add as cluster (or only as id) */
function
def apply_aberration(model, mcoefs, pcoefs): assert isinstance(model, HanserPSF), "Model must be a HanserPSF" model = copy.copy(model) if mcoefs is None and pcoefs is None: logger.warning("No abberation applied") return model if mcoefs is None: mcoefs = np.zeros_like(pcoefs) ...
python
12
0.631518
72
38.272727
22
Apply a set of abberations to a model PSF. Parameters ---------- model : HanserPSF The model PSF to which to apply the aberrations mcoefs : ndarray (n, ) The magnitude coefficiencts pcoefs : ndarray (n, ) The phase coefficients Note: this function assumes the mcoefs...
function
def list_images(self, location=None): params = {} if location is not None: params['location'] = location.id return self._to_base_images( self.connection.request_api_1('base/imageWithDiskSpeed', params=params) .object)
python
10
0.517241
68
39
8
return a list of available images Currently only returns the default 'base OS images' provided by DimensionData. Customer images (snapshots) are not yet supported. @inherits: :class:`NodeDriver.list_images`
function
def check(self, identity, permission, *args, **kwargs): try: permission = self.permissions[permission] except KeyError: return False else: return permission.check(identity, *args, **kwargs)
python
10
0.586345
62
34.714286
7
Check if the identity has requested permission. :param identity: Currently authenticated identity. :param permission: Permission name. :return: True if identity role has this permission.
function
@Override public int compareTo(Object other) { if (other == null) { return -1; } FlowKey otherKey = (FlowKey)other; return new CompareToBuilder() .appendSuper(super.compareTo(other)) .append(getEncodedRunId(), otherKey.getEncodedRunId()) .toComparison(); }
java
10
0.630719
62
26.909091
11
/** * Compares two FlowKey objects on the basis of * their cluster, userName, appId and encodedRunId * * @param other * @return 0 if this cluster, userName, appId and encodedRunId are equal to * the other's cluster, userName, appId and encodedRunId, * 1 if this cluster or userName or app...
function
@Constraints(noNullInputs = true, notMutable = true, noDirectInsertion = true) public static <T> void validateBean(@BoundInputVariable(initializer = true, atMostOnceWithSameParameters = true) T instance, Class<?> clazz) throws FalsePositiveException, IllegalArgumentException{ Inputs.checkNull(in...
java
17
0.590437
144
47.15
20
/** * Check if all beans that need injection have been properly injected * * @param instance * @param clazz * @param <T> * @throws FalsePositiveException * @throws IllegalArgumentException */
function
class SetClass: """This class performs set operations on the data sets of two SetClass objects. Public Methods: items() display() union() intersection() excluding() isempty() pretty_print() """ def __init__(self, arg=None, name=None): """ Initialize pri...
python
17
0.542969
75
29.516129
217
This class performs set operations on the data sets of two SetClass objects. Public Methods: items() display() union() intersection() excluding() isempty() pretty_print()
class
bool isValidRequest(const SipMessage& sipMessage) { if ((sipMessage.hasHeader(TO)) && (sipMessage.hasHeader(FROM)) && (sipMessage.hasHeader(CSEQ)) && (sipMessage.hasHeader(CALL_ID)) && (sipMessage.hasHeader(MAX_FORWARDS))) { return true; } return false; }
c++
12
0.646048
49
23.333333
12
/// A valid SIP request formulated by a UAC MUST, at a minimum, contain /// the following header fields : To, From, CSeq, Call - ID, Max - Forwards, /// and Via; all of these header fields are mandatory in all SIP /// requests.
function
public long xen_memory_calc() { long xen_mem = memory_overhead; foreach (VM vm in Connection.ResolveAll(resident_VMs)) { xen_mem += vm.memory_overhead; if (vm.is_control_domain) { VM_metrics vmMetrics = vm.Co...
c#
16
0.444444
77
33.866667
15
/// <summary> /// The amount of memory used by Xen, including the control domain plus host and VM overheads. /// Used to calculate this as total - free - tot_vm_mem, but that caused xen_mem to jump around /// during VM startup/shutdown because some changes happen before others. /// </summary>
function
public class LockedModule extends CanvasComparable<LockedModule> implements Serializable{ private static final long serialVersionUID = 1L; private long id; private long context_id; private String context_type; private String name; private String unlock_at; private boolean require_sequential...
java
14
0.556061
106
33.913907
151
/** * Created by Brady Larson on 9/6/13. * * Copyright (c) 2014 Instructure. All rights reserved. */
class
func (h *Filter) Process(_ *http.Request, wr *prompb.WriteRequest) error { defer finalFiltering(wr) tts := wr.Timeseries if len(tts) == 0 { return nil } clusterName, replicaName := haLabels(tts[0].Labels) if err := validateClusterLabels(clusterName, replicaName); err != nil { return err } minTUnix, maxTUnix...
go
11
0.715797
116
34.475
40
// FilterData validates and filters timeseries based on lease info from the service. // When Prometheus & Promscale are running HA mode the below FilterData is used // to validate leader replica samples & ha_locks in TimescaleDB.
function
[Serializable] public class SparseColumnMatrix : AbstractMatrix, ISparseColumnAccessMatrix, IElementalAccessZeroColumnMatrix, IMatrixAccess { private readonly double[][] _data; private readonly int[][] _rowIndex; private readonly int[] _used; private bool _isCompact; public SparseColumnMatrix(int numR...
c#
19
0.591869
97
27.155556
180
/// <summary> Sparse matrix stored as 2D ragged columns. For best performance during /// assembly, ensure that enough memory is allocated at construction time, /// as re-allocation may be time-consuming. /// </summary>
class
public class TestngListener implements ITestListener, IExecutionListener { private static final Logger LOGGER = Logger.getLogger(TestngListener.class); private final String hr = StringUtils.repeat("-", 100); private enum RunResult {SUCCESS, FAILED, SKIPPED, TestFailedButWithinSuccessPercentage } @Over...
java
14
0.657427
118
29.365079
63
/** * Testng listener class. This is useful for things that are applicable to all the tests as well * taking actions that depend on test results. */
class
func (i *fileLedgerIterator) Next() (*cb.Block, cb.Status) { for { if i.blockNumber < i.ledger.Height() { block, err := i.ledger.blockStore.RetrieveBlockByNumber(i.blockNumber) if err != nil { return nil, cb.Status_SERVICE_UNAVAILABLE } i.blockNumber++ return block, cb.Status_SUCCESS } <-i.led...
go
13
0.668657
73
24.846154
13
// Next blocks until there is a new block available, or returns an error if the // next block is no longer retrievable
function
public void rsPlot(PlotFrame frame, Polynomial p, int index, double precision, double left, double right, int subintervals) { double delta = (Math.abs(right-left))/subintervals; PolyPractice popeye = new PolyPractice(); for (double i = left; i <= right; i+=precision) { frame.append(1, i, popeye.eval(p,i)); ...
java
12
0.662791
105
38.181818
11
/** * This method graphs the input polynomial on the input PlotFrame. * It also draws the regions used to calculate a particular Riemann sum. * If RiemannSumRule extends Riemann and RSR is an object of type RiemannSumRule, * then RSR.rsPlot should graph the input polynomial and draw the regions used to calcu...
function
func (v *VolumeEntry) blockHostingSizeIsCorrect(used int) bool { logger.Debug("volume [%v]: comparing %v == %v + %v + %v", v.Info.Id, v.Info.Size, used, v.Info.BlockInfo.FreeSize, v.Info.BlockInfo.ReservedSize) unused := v.Info.BlockInfo.FreeSize + v.Info.BlockInfo.ReservedSize if v.Info.Size != (used + unused) ...
go
11
0.68472
68
38.846154
13
// blockHostingSizeIsCorrect returns true if the total size of the volume // is equal to the sum of the used, free and reserved block hosting size values. // The used size must be provided and should be calculated based on the sizes // of the block volumes.
function
public static String utf8BytesToString(byte[] bytes, int start, int length) { char[] chars = localBuffer.get(); if (chars == null || chars.length < length) { chars = new char[length]; localBuffer.set(chars); } int outAt = 0; for (int at = start; length > 0...
java
17
0.315609
77
36.87013
77
/** * Converts an array of UTF-8 bytes into a string. * * @param bytes non-null; the bytes to convert * @param start the start index of the utf8 string to convert * @param length the length of the utf8 string to convert, not including any null-terminator that might be present * @return non...
function
def _service(method, request): response = requests.post(API_URL, data=json.dumps({method: request})) try: response_dict = response.json() except: raise ServiceError('service did not return a valid response') from None if "error" in response_dict: raise ServiceError(response_dict...
python
12
0.681128
79
41
11
Send a request to the service API, raise exceptions for any unexpected responses, and returned a parsed result.
function
public class AAShapePipe implements ShapeDrawPipe, ParallelogramPipe { static RenderingEngine renderengine = RenderingEngine.getInstance(); CompositePipe outpipe; public AAShapePipe(CompositePipe pipe) { outpipe = pipe; } public void draw(SunGraphics2D sg, Shape s) { BasicStroke b...
java
17
0.510764
119
32.13986
143
/** * This class is used to convert raw geometry into 8-bit alpha tiles * using an AATileGenerator for application by the next stage of * the pipeline. * This class sets up the Generator and computes the alpha tiles * and then passes them on to a CompositePipe object for painting. */
class
def create_cluster_role_binding(self, name: str, subjects: List[ObjectMeta], role_ref_name: str): self.execute_kubernetes_client( self._create_cluster_role_binding, metadata={ "name": name, }, role_ref_name=role_ref_name, subjects=subje...
python
10
0.547904
97
36.222222
9
Creates a cluster role binding Parameters ---------- name cluster role binding name subjects subjects that the permissions defined in the cluster role with the given name are granted to role_ref_name cluster role defining permissio...
function
char * asc_tolower(const char *buff, size_t nbytes) { char *result; char *p; if (!buff) return NULL; result = pnstrdup(buff, nbytes); for (p = result; *p; p++) *p = pg_ascii_tolower((unsigned char) *p); return result; }
c
11
0.617021
44
18.666667
12
/* * ASCII-only lower function * * We pass the number of bytes so we can pass varlena and char* * to this function. The result is a palloc'd, null-terminated string. */
function
int PlatformCore::GetDisplayCount() { MonitorSet monitors; monitors.MonitorCount = 0; EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&monitors); int primary = 0; MONITORINFOEX info; for (int m=0; m < monitors.MonitorCount; m++) { info.cbSize = sizeof(MONITORINFOEX); ...
c++
10
0.601083
72
28.210526
19
// Returns the number of active screens for extended displays and 1 for mirrored display
function
def customjson(jsonid, json_data, account, active, export): if jsonid is None: print("First argument must be the custom_json id") if json_data is None: print("Second argument must be the json_data, can be a string or a file name.") data = import_custom_json(jsonid, json_data) if data is ...
python
12
0.642689
87
35.913043
23
Broadcasts a custom json First parameter is the cusom json id, the second field is a json file or a json key value combination e.g. beempy customjson -a holger80 dw-heist username holger80 amount 100
function
public class SMIMESigned extends CMSSignedData { static { final MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.spongycastle.mail.smime.handlers.pkcs7_signature"); mc.addMailcap("mu...
java
15
0.638752
141
34.843137
51
/** * general class for handling a pkcs7-signature message. * <p> * A simple example of usage - note, in the example below the validity of * the certificate isn't verified, just the fact that one of the certs * matches the given signer... * <p> * <pre> * CertStore certs = s.getCertificates("Colle...
class
class FuncVerifier { public: LogicalResult failure() { return mlir::failure(); } LogicalResult failure(const Twine &message, Operation &value) { return value.emitError(message); } LogicalResult failure(const Twine &message, Function &fn) { return fn.emitError(message); } LogicalResult failure(const ...
c++
20
0.663815
78
37.980392
51
/// This class encapsulates all the state used to verify a function body. It is /// a pervasive truth that this file treats "true" as an error that needs to be /// recovered from, and "false" as success. ///
class
final class UtilizationObjective extends AbstractObjective implements WorkloadDependentObjective { /** * The name of the class. */ static final String name = "utilization"; /** * Short run detection. */ private List zoneList = new LinkedList(); /** * Format for printing utilization. */ private s...
java
18
0.645533
71
27.789286
280
/** * A resource set utilization based objective which will assess moves * in terms of their (likely) impact on the future performance of a * resource set with respect to it's specified utilization objective. * * The utilization objective must be specified in terms of a * KVOpExpression, see the class definition ...
class
public void SetExpandAll(bool expanded) { foreach (var control in ResizeContainerControls) { control?.ToggleExpandAction(expanded); } }
c#
10
0.536946
60
28.142857
7
/// <summary> /// Sets the expand state of all the message boxes within the control to a specified value. /// </summary> /// <param name="expanded">if set to <c>true</c> all the message boxes within the control are expanded.</param>
function
private String retrieveDnsLabel(LookupContext ctx) throws LookupException { ctx.setPrefix(ctx.getType() + Constants.NAME); ctx.setRrType(Type.PTR); Record[] records = lookup(ctx); String dnsLabel = null; if (records != null) { for (Reco...
java
15
0.505051
114
41.47619
21
/** * Retrieve the DNS domain label for the browsing domain and specified Service Type. * * @param ctx A <code>LookupContext</code> defining this lookup parameters * @return A <code>String</code> containing the DNS domain label * @throws LookupException In case of unsuccessf...
function
def source_releasability(request): if request.method == 'POST' and request.is_ajax(): type_ = request.POST.get('type', None) id_ = request.POST.get('id', None) name = request.POST.get('name', None) note = request.POST.get('note', None) action = request.POST.get('action', None...
python
15
0.483858
85
48.215686
51
Modify a top-level object's releasability. Should be an AJAX POST. :param request: Django request. :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponse`
function
private Button createActionButton(String actionLabel) { Button button = new Button(getActivity()); button.setBackground(ContextCompat.getDrawable(getActivity(), R.drawable .action_button_background)); button.setText(actionLabel); CalligraphyUtils.applyFontToTextView(getAc...
java
20
0.572493
98
56.571429
35
/** * Creates the action button. * * @param actionLabel The text to be displayed on the action button. * @return The instantiated button. */
function
def compute(self, nof_coefficients, ncap=None, permute=None, residual=False, get_trafo=False): if ncap is None: ncap = self.discretized_bath.max_nof_coefficients if ncap < nof_coefficients: print('Accuracy parameter set too low. Must be >= nof_coefficients. Automatically set ncap...
python
13
0.612568
121
55.74359
39
Central method, which computes the chain coefficients via tridigonalization from the discretized bath coefficients. Stores the result in the internal buffers of the object, accessible via c0, omega and t. Uses a fixed accuracy parameter/number of discretized coefficients ncap for th...
function
private byte[] unzip(final byte[] bytes, final int imgWidth, final int imgHeight) throws DataFormatException { final byte[] data = new byte[imgWidth * imgHeight * 8]; int count = 0; final Inflater inflater = new Inflater(); inflater.setInput(bytes); count = inflater.i...
java
9
0.627907
63
42.083333
12
/** * Uncompress the image using the ZIP format. * @param bytes the compressed image data. * @param imgWidth the width of the image in pixels. * @param imgHeight the height of the image in pixels. * @return the uncompressed image. * @throws DataFormatException if the compressed image...
function
def _validate_translation_suggestion_counts(cls, item): supported_language_codes = [ language_code['id'] for language_code in constants.SUPPORTED_AUDIO_LANGUAGES ] all_translation_suggestion_models_in_review = ( suggestion_models.GeneralSuggestionModel.get_all...
python
15
0.526706
80
52.94
50
For each language code, validate that the translation suggestion count matches the number of translation suggestions in the datastore that are currently in review. Args: item: datastore_services.Model. CommunityContributionStatsModel to validate.
function
public class HTTPResponseHandler { private RequestObject request; private HashMap<String, Handler> map; private PrintWriter writer; private Handler handler; private String headers = ""; private String page = ""; private Logger logger; /** * Constructor that initializes the below parameters * @param reques...
java
20
0.657101
132
28.934783
92
/** * A class that reads the parsed request lines and returns appropriate message to the client * @author Tae Hyon Lee * */
class
@WebService(endpointInterface = PluginConstants.CERTIFICATE_ENROLLMENT_SERVICE_ENDPOINT, targetNamespace = PluginConstants.DEVICE_ENROLLMENT_SERVICE_TARGET_NAMESPACE) @Addressing(enabled = true, required = true) @BindingType(value = SOAPBinding.SOAP12HTTP_BINDING) public class CertificateEnrollmentServiceImpl i...
java
19
0.685394
118
56.702602
269
/** * Implementation class of CertificateEnrollmentService interface. This class implements MS-WSTEP * protocol. */
class
def test(job): import sys import os RESULT_OK = 'OK : %s' RESULT_FAILED = 'FAILED : %s' RESULT_ERROR = 'ERROR : %s %%s' % job.service.name model = job.service.model model.data.result = RESULT_OK % job.service.name failures = [] expected_actors = ['cockpittesting', 'datacenter', 'sshk...
python
22
0.599016
130
50.711864
59
Test the created directory structure is corrected after ays blueprint on a test repo
function
static int check_sac_nvhdr(const int nvhdr) { int lswap = FALSE; if (nvhdr != SAC_HEADER_MAJOR_VERSION) { byte_swap((char*) &nvhdr, SAC_DATA_SIZEOF); if (nvhdr == SAC_HEADER_MAJOR_VERSION) lswap = TRUE; else lswap = -1; } return lswap; }
c
11
0.54485
51
24.166667
12
/* * check_sac_nvhdr * * Description: Determine the byte order of the SAC file * * IN: * const int nvhdr : nvhdr from header * * Return: * FALSE no byte order swap is needed * TRUE byte order swap is needed * -1 not in sac format ( nvhdr != SAC_HEADER_MAJOR_VERSION ) * */
function
private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.chbHexa = new System.Windows.Forms.CheckBox(); this.txbSendData = new System.Windows.Forms.TextBox(); this.btnSend = new System.Windows.Forms.Button(); t...
c#
19
0.618689
156
55.964286
56
/// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>
function
func (maintenanceWindow *MaintenanceWindow) AssignPropertiesToMaintenanceWindow(destination *v1alpha1api20210501storage.MaintenanceWindow) error { propertyBag := genruntime.NewPropertyBag() destination.CustomWindow = genruntime.ClonePointerToString(maintenanceWindow.CustomWindow) destination.DayOfWeek = genruntime.C...
go
8
0.847201
146
49.923077
13
// AssignPropertiesToMaintenanceWindow populates the provided destination MaintenanceWindow from our MaintenanceWindow
function
public final class PPDrawingTextListing { public static void main(String[] args) throws Exception { if(args.length < 1) { System.err.println("Need to give a filename"); System.exit(1); } HSLFSlideShow ss = new HSLFSlideShow(args[0]); // Find PPDrawings at any second level position Record[] records = ...
java
25
0.593903
125
33.679245
53
/** * Uses record level code to locate PPDrawing entries. * Having found them, it sees if they have DDF Textbox records, and if so, * searches those for text. Prints out any text it finds */
class
public class ChangeProf extends ConcretePrereqObject { /** * A reference to the source WeaponProf that this ChangeProf impacts * (effectively changes the TYPE) */ private final CDOMReference<WeaponProf> source; /** * The resulting Group into which the source WeaponProf is effectively * placed ...
java
13
0.666071
77
24.40566
106
/** * Represents a change to a type of WeaponProficiency for a PlayerCharacter. The * change impacts a given WeaponProf primitive and effectively places that * WeaponProf into a separate TYPE. */
class
class SettingItem: """Creates a setting item :param default: default value for the setting item :type default: Any :param limits: lower and upper bounds of item :type limits: Union[(Any, Any), None] :param sub_type: type of the contents of iterable items :type sub_type: type object :par...
python
11
0.630854
78
33.619048
21
Creates a setting item :param default: default value for the setting item :type default: Any :param limits: lower and upper bounds of item :type limits: Union[(Any, Any), None] :param sub_type: type of the contents of iterable items :type sub_type: type object :param fixed_size: size of ite...
class
async _selectAccount({accountId, callback}) { this.app.logger.info(`${this}select account ${accountId}`) let account = this.app.state.settings.webrtc.account if (accountId) { const res = await this.app.api.client.put('api/plugin/user/selected_account/', {id: accountId}) i...
javascript
18
0.478528
107
39.78125
32
/** * Handles changing the account and signals when the new account info * is loaded, by responding with the *complete* account credentials in * the callback. * @param options - options to pass. * @param options.accountId - Id of an account from options to set. * @param options.callback - Callba...
function
pub fn verify_share( &self, candidate_share: CandidateShare<G>, ciphertext: Ciphertext<G>, index: usize, proof: &LogEqualityProof<G>, ) -> Result<DecryptionShare<G>, VerificationError> { let key_share = self.participant_keys[index].as_element(); let dh_element...
rust
11
0.599727
74
37.578947
19
/// Verifies a candidate decryption share for `ciphertext` provided by a participant /// with the specified `index`. /// /// # Errors /// /// Returns an error if the `proof` does not verify.
function
static int poll_for_response(OSSL_CMP_CTX *ctx, int sleep, int rid, OSSL_CMP_MSG **rep, int *checkAfter) { OSSL_CMP_MSG *preq = NULL; OSSL_CMP_MSG *prep = NULL; ossl_cmp_info(ctx, "received 'waiting' PKIStatus, starting to poll for response"); *rep = NULL; ...
c
19
0.441193
82
38.877778
90
/*- * When a 'waiting' PKIStatus has been received, this function is used to * poll, which should yield a pollRep or finally a CertRepMessage in ip/cp/kup. * On receiving a pollRep, which includes a checkAfter value, it return this * value if sleep == 0, else it sleeps as long as indicated and retries. * * A tran...
function
public void update(GameContainer gc, int delta) { if (!Settings.is("score_effects")) { return; } HashSet<TextParticle> dead = new HashSet<>(); for (TextParticle scoreParticle : particles) { if (scoreParticle.update(gc, delta)) { dead.add(scoreParti...
java
10
0.535897
54
31.583333
12
/** * Update the effects unless disabled in settings. * * @param gc game container * @param delta delta time */
function
@SuppressWarnings("unchecked") public static void startTelemetry() { if (CONFIG_REFRESH_LISTENER != null) { return; } final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); ImmutableList.Builder<ConfigModule> modulesBuilder = ImmutableList.builder(); ServiceLoader.load(ConfigModule...
java
20
0.670386
134
48.595745
47
/** * Reads the telemetry config file and sets itself up to listen for changes. * If telemetry is already available, the most up to date telemetry dependencies (e.g. tracer) * will be added to the registry. */
function
def process_image(self, img): if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]: h, w = img.shape[:2] self.size = (h, w) self.bin = np.empty((h, w, 1), dtype=np.uint8) self.hsv = np.empty((h, w, 3), dtype=np.uint8) se...
python
13
0.550062
123
50.380952
63
Processes an image and thresholds it. Returns the original image, and a binary version of the image indicating the area that was filtered :returns: img, bin
function
public static List<NurbsCurve> BezierInterpolation(List<Vector3> pts) { if (pts.Count == 0) { throw new Exception("Collection of points is empty."); } List<NurbsCurve> beziers = new List<NurbsCurve>(); (List<Vector3> ptsA, List<Vector3>...
c#
19
0.499197
118
40.6
15
/// <summary> /// Creates a set of interpolated cubic beziers through a set of points. /// </summary> /// <param name="pts">Set of points to interpolate.</param> /// <returns>A set of cubic beziers.</returns>
function
def vote(self, mission: list[int], leader: int) -> bool: self.selections.append((leader, mission)) if self.spy: return len([p for p in mission if p in self.spies]) > 0 total = sum(self._estimate(p) for p in mission if p != self) alternate = sum( self._estimate(p) ...
python
13
0.583529
85
46.333333
9
The method is called on an agent to inform them of the outcome of a vote, and which agent voted for or against the mission. Args: mission (list[int]): A list of unique agents to be sent on a mission. leader (int): The index of the player ...
function
End of preview. Expand in Data Studio

This dataset contains deduplicated data from The-Vault-function and The-Vault-class.

Data filtering notes:

  • AST parsability: we extracted only the AST parsable codes
  • AST Depth: only samples with depth from 2.0 to 31.0
  • Maximum Line Length: only samples with a maximum of 12.0 to 400.0 characters
  • Average Line Length: only samples with 5.0 to 140.0 characters on average
  • Alphanumeric Fraction of samples is greater than 0.2 and less than 0.9
  • Number of Lines: from 6.0 to 300.0
  • Language Filter: samples whose docstring scores an English language confidence greater than 98% by the lingua language detector
  • Deduplication: samples MinHash deduplicated using a shingle size of 8 and a similarity threshold of 0.7
Downloads last month
10