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
[Fact] public static void MatchesTest114() { var xml = "books.xml"; var startingNodePath = "/bookstore/book/author"; var testExpression = @"(book/author)[last-name=(/bookstore/book/author/last-name)[1]]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathEx...
c#
12
0.609223
99
44.888889
9
/// <summary> /// Predicate within a predicate - Return all authors with a last-name equal to the first last-name node. /// (book/author)[last-name=(/bookstore/book/author)[1]/last-name] /// </summary>
function
private final void zzd(int r5, int r6) { /* r4 = this; r4.zzqk() com.google.android.gms.common.util.Clock r0 = com.google.android.gms.ads.internal.zzbv.zzer() long r0 = r0.currentTimeMillis() java.lang.Object r2 = r4.mLock monitor-enter(r2)...
java
7
0.500824
135
42.392857
28
/* Code decompiled incorrectly, please refer to instructions dump. */
function
private void toggleCustomiseUI(bool enable) { if (enable) { customiseGrid.Opacity = 1; customiseGrid.IsEnabled = true; btnDelete.IsEnabled = true; } else { customiseGrid.Opacity = 0.33; customiseGrid.IsEnable...
c#
9
0.481203
48
32.333333
12
/// <summary> /// Hides or shows all of the UI elements that require a custom theme to be loaded first (which is most of them) /// </summary> /// <param name="enable">Whether or not to enable UI elements that require a loaded theme</param>
function
public static String determineContextPath(HttpServletRequest request) { String contextPath = request.getContextPath(); String proxyContextPath = request.getHeader(PROXY_CONTEXT_PATH_HTTP_HEADER); String forwardedContext = request.getHeader(FORWARDED_CONTEXT_HTTP_HEADER); logger.debug("Co...
java
12
0.685475
115
62.866667
15
/** * Determines the context path if populated in {@code X-ProxyContextPath} or {@code X-ForwardContext} headers. If not populated, returns an empty string. * * @param request the HTTP request * @return the provided context path or an empty string */
function
createPlaceholderSystemNote({ formContent, uniqueId }) { const $tempNote = $( `<li id="${uniqueId}" class="note system-note timeline-entry being-posted fade-in-half"> <div class="timeline-entry-inner"> <div class="timeline-content"> <i>${formContent}</i> </div> ...
javascript
8
0.550265
94
30.583333
12
/** * Create Placeholder System Note DOM element populated with quick action description */
function
private static Bitmap TryCaptureFullScreen() { int width = Screen.PrimaryScreen.Bounds.Width; int height = Screen.PrimaryScreen.Bounds.Height; if (width <= 0 || height <= 0) { return null; } var bitmap = new Bitmap(width, he...
c#
13
0.502469
71
37.619048
21
/// <summary> /// Captures the full screen to a <see cref="Bitmap"/>. /// </summary> /// <returns> /// A <see cref="Bitmap"/> containing the screen capture of the desktop, or null if a screen /// capture can't be created. /// </returns>
function
static uint32_t UTILS_GetPLLOutputFrequency(uint32_t PLL_InputFrequency, LL_UTILS_PLLInitTypeDef *UTILS_PLLInitStruct) { uint32_t pllfreq; assert_param(IS_LL_UTILS_PLLM_VALUE(UTILS_PLLInitStruct->PLLM)); assert_param(IS_LL_UTILS_PLLN_VALUE(UTILS_PLLInitStruct->PLLN)); assert_param(IS_LL_UTILS_PLLP_VALUE(UTILS_P...
c
9
0.786913
165
58.7
10
/** * @brief Function to check that PLL can be modified * @param PLL_InputFrequency PLL input frequency (in Hz) * @param UTILS_PLLInitStruct pointer to a @ref LL_UTILS_PLLInitTypeDef structure that contains * the configuration information for the PLL. * @retval PLL output frequ...
function
@POST @Path(CoordConsts.SVC_RSC_LIST_CONTAINERS) @Produces(MediaType.APPLICATION_JSON) @Deprecated public JSONArray listContainers( @FormDataParam(CoordConsts.SVC_KEY_API_KEY) String apiKey, @FormDataParam(CoordConsts.SVC_KEY_VERSION) String clientVersion) { return listNetworksHelper(apiKey, cli...
java
8
0.764881
73
36.444444
9
/** * List the networks that the specified API key can access * * @param apiKey The API key of the client * @param clientVersion The version of the client * @return TODO: document JSON response * @deprecated because containers were renamed to networks. Use {@link #listNetworks(String, * String)...
function
def nearest_neighbor_threshold( self, vectors, threshold=0.5, batch_size=100, show_progressbar=False, return_names=True, ): vectors = np.array(vectors) if np.ndim(vectors) == 1: vectors = vectors[None, :] return list( se...
python
9
0.519187
78
26.75
16
Find the nearest neighbors to some arbitrary vector. This function is meant to be used in composition operations. The most_similar function can only handle items that are in vocab, and looks up their vector through a dictionary. Compositions, e.g. "King - man + woman" are neces...
function
def interpolate_NaNs_in_feature_variables(ds=None, res='4x5', save2NetCDF=False, debug=False): months = np.arange(1, 13) filename = 'Oi_prj_feature_variables_{}.nc'.format(res) if isinstance(ds, type(None)): ds = xr.open_dataset(filename) for var in ds.d...
python
17
0.493885
78
38.953488
43
Interpolate the NaNs in 2D arrarys of feature variables Parameters ------- ds (xr.Dataset): dataset object with variables to interpolate res (str): horizontal resolution (e.g. 4x5) of Dataset save2NetCDF (bool): save interpolated Dataset to as a NetCDF? debug (bool): print out debugging ou...
function
fn cmp(&self, other: &Self) -> Ordering { fn to_tuple( report_body: &ReportBody, ) -> ( FamilyId, ProductId, SecurityVersion, ExtendedProductId, MrSigner, MrEnclave, Attributes, MiscSelect, ...
rust
8
0.455993
54
30.441176
34
/// Create an arbitrary sort order for report body types /// /// We sort by Family ID, ProdID, Extended ProdID, SVN, MrSigner, MrEnclave, Attributes, /// Misc Select, ConfigId, ConfigSVN, CPU SVN, and ReportData, in that order
function
def re_escape(pattern, chars=frozenset("()[]{}?*+|^$\\.-#")): escape = '\\{}'.format return ''.join( escape(c) if c in chars or c.isspace() else '\\000' if c == '\x00' else c for c in pattern )
python
11
0.480687
61
32.428571
7
Escape all special regex characters in pattern. Logic taken from regex module. :param pattern: regex pattern to escape :type patterm: str :returns: escaped pattern :rtype: str
function
@Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { flushChars(); write("<"); write(qName); outputAttributes(namespaces); outputAttributes(atts); write(">"); namespaces.clear(); }
java
7
0.720307
108
25.2
10
/** * Receive notification of the start of an element. * <p/> * <p>By default, do nothing. Application writers may override this * method in a subclass to take specific actions at the start of * each element (such as allocating a new tree node or writing * output to a file).</p> * * @param uri The Nam...
function
def decompr_files(dname, fnames): try: for fname in fnames: if os.path.exists(dname + fname): sh.gunzip(dname + fname) elif os.path.exists(dname + os.path.splitext(fname)[0]): return else: rai...
python
16
0.481876
79
38.166667
12
Runs gunzip on a list of files. Args: dname (str): The Dirname containing files to gunzip. fnames (list): list of filenames in dir. Examples: Pipe.decompr_files('user/inputs/', ['a.gz', 'b.gz'])
function
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "familyMember", propOrder = { "dateOfBirth", "fmemberIds", "fmemberName", "surname", "typeOfFmember" }) @Entity public class FamilyMember { @XmlElement(name = "date_of_birth") @NotNull(message = "Format: DD-MM-YYYY") protected String...
java
9
0.543629
52
20.546099
141
/** * <p>Java class for familyMember complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="familyMember"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * ...
class
public class ChecksCache { public static readonly Check ImageScanCheck = new Check { Id = "container_image.CVE_scan", Category = "Security", Severity = CheckSeverity.High, Description = "Container Image scan with trivy", Remediation = "Upda...
c#
20
0.539875
119
41.25
76
/// <summary> /// Keeps track of Check items to reduce amount of interactions with real database. /// The objects stores in memory identifiers of Checks, that are already in database. /// It does requests only to update expired items or query not cached yet records. /// The cache is expected to be used in Singleton mod...
class
class CThreadPool_Controller_PID : public CThreadPool_Controller { public: CThreadPool_Controller_PID(unsigned int max_threads, unsigned int min_threads); void SetQueuedTasksThreshold(double threshold); @sa SetQueuedTasksThreshold() double GetQueuedTasksThreshold(void);...
c++
8
0.699538
74
45.371429
70
/// Default ThreadPool controller based on Proportional-Integral-Derivative /// algorithm. Controller looks at number of tasks waiting in the queue /// per each thread running and adjusts number of threads with respect to /// all coefficients set in it. /// Implementation of the class assumes that all coefficients are ...
class
func NewConsulResolver(ctx context.Context, conf ResolverConfig) (*ServiceResolver, error) { if conf.Client == nil { return nil, errors.New("consul client must not be nil") } if conf.ServiceSpec.ServiceName == "" { return nil, errors.New("service name must not be empty") } if conf.Query == nil { conf.Query =...
go
15
0.663814
92
25.419355
31
// NewConsulResolver creates a new Consul Resolver // ctx - a context used for graceful termination of the consul-watcher go routine. // Note that canceling the context will render the resolver stale, and any attempt to use it will immediately return an error // conf - the resolver's config
function
draw_termini(termini_data) { let loop_length_calculation; let loop_drawing_shape; if (termini_data.terminus_type === "N") { loop_length_calculation = this.style_obj.protein.nter_loop_draw_opts.calc_len; loop_drawing_shape = this.style_obj.protein.nter_loop_draw_opts.shape...
javascript
12
0.647475
121
57.294118
17
/** * Function responsbile for controlling addition of points to termini data and drawing of termini curves * @namespace * @exports NaView * @name draw_termini * @param {Object} termini_data termini loop data Object generated by processRawUniProt */
function
def findMessages(): with open('hiddenMessageInput.txt', 'w') as hiddenMessageInputOutput: hiddenMessageInputOutput.write('') hiddenMessageInputOutput.close() logging.debug('Displaying confirmation screen.') print('''To find the hidden message, copy and paste the text into the file "hiddenMessageInput....
python
16
0.655158
159
41.925926
54
Find hidden messages in Romeo and Juliet. This function takes an input from the user, from a file (hiddenMessageInput.txt) and compares the input to storyMaster.txt and outputs any differences between the two files, the purpose of this function is to find/locate a hidden message in the text from...
function
public static List<Class> findClassesFromJar(JarFile jarFile, String packageName) throws ClassNotFoundException, MalformedURLException { List<Class> classes = new ArrayList<Class>(); if (jarFile == null || packageName == null) { return classes; } URL[] urls = { new URL("jar:f...
java
18
0.543015
136
51.833333
24
/** * Scans all classes in the specified jar file which belong to the given * package and its descendants. * * @param jarFile to search * @param packageName * @return list of classes found (never null) * @throws ClassNotFoundException * @throws IOException */
function
@ApiModel(value = "lookup-values-list", description = "[ { field : value} ]") @EqualsAndHashCode public class JSONLookupValuesList { public static final JSONLookupValuesList ofLookupValuesList( @Nullable final LookupValuesList lookupValues, @NonNull final String adLanguage) { if (lookupValues == null || looku...
java
16
0.749673
135
27.66875
160
/* * #%L * metasfresh-webui-api * %% * Copyright (C) 2016 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any late...
class
static llvm::Function *ImplementExplicitArgsEntryPoint( const NativeObject *cfg_func, const std::string &name) { auto num_args = FLAGS_explicit_args_count; if (name == "main") { num_args = 3; } auto bb = remill::BasicBlockFunction(gModule); auto state_ptr_arg = remill::NthArgument(bb, remill::kStatePo...
c++
10
0.699437
80
43.423077
52
// Implements a stub for an externally defined function in such a way that // the external is explicitly called, and arguments from the modeled CPU // state are passed into the external.
function
func (x *BindImageMemoryInfoKHX) Deref() { if x.reffcb13766 == nil { return } x.SType = (StructureType)(x.reffcb13766.sType) x.PNext = (unsafe.Pointer)(unsafe.Pointer(x.reffcb13766.pNext)) x.Image = *(*Image)(unsafe.Pointer(&x.reffcb13766.image)) x.Memory = *(*DeviceMemory)(unsafe.Pointer(&x.reffcb13766.memory)...
go
13
0.759441
71
43.75
16
// Deref uses the underlying reference to C object and fills the wrapping struct with values. // Do not forget to call this method whether you get a struct for C object and want to read its values.
function
public class SoapHeaderElementMethodArgumentResolver implements MethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { SoapHeader soapHeader = parameter.getParameterAnnotation(SoapHeader.class); if (soapHeader == null) { return false; } Class<?> parameterType = p...
java
15
0.750277
110
33.278481
79
/** * Implementation of {@link MethodArgumentResolver} that supports resolving {@link SoapHeaderElement} parameters. Target * method parameters must be annotated with {@link SoapHeader} to indicate the SOAP header to resolve. This resolver * supports simple {@link SoapHeaderElement} parameters and {@link List} param...
class
func New(deployment, cwd string, timeout time.Duration, logger log15.Logger, sudo bool, ram ...int) (*Scheduler, error) { cwd, err := pickCWD(cwd) if err != nil { return nil, err } jq, err := jobqueue.ConnectUsingConfig(clog.ContextWithLogHandler(context.Background(), logger.GetHandler()), deployment, timeout)...
go
15
0.652174
88
22.888889
27
// New returns a Scheduler that is connected to wr manager using the given // deployment, timeout and logger. If sudo is true, NewJob() will prefix 'sudo' // to commands. Added jobs will have the given cwd, which matters. If cwd is // blank, the current working dir is used. If ram is supplied, we set override // 1, oth...
function
public static PropertyInfo GetPropertyInfo(this Object obj, String name) { if (obj is null) { throw new ArgumentNullException(nameof(obj)); } return GetPropertyInfo(obj.GetType(), name); }
c#
13
0.544776
72
32.625
8
/// <summary> /// Gets the property information by name for the type of the object. /// </summary> /// <param name="obj">Object with a type that has the specified property.</param> /// <param name="name">The name of the property.</param>
function
def transformWalkDown(node, add=False, multi=False): oChild = [] if not isinstance(node, list): node = [node] for n in node: relatives = n.listRelatives(typ='transform') if relatives: if multi: oChild = oChild + relatives else: ...
python
14
0.553377
52
29.666667
15
Walks to the child transform dagNode on the hierarcy Arguments: node (dagNode or list of dagNode): dagNode to walk add (bool, optional): if True, will add to the selection multi (bool, optional): if True will select all the childrens
function
def divide_data_to_table_and_attribute( self,data,required_column='experiment_igf_id', table_columns=None,attribute_name_column='attribute_name', attribute_value_column='attribute_value'): try: if not isinstance(data, pd.DataFrame): data = pd.DataFrame(data) experiment_co...
python
12
0.527359
80
39.709677
31
A method for separating data for Experiment and Experiment_attribute tables :param data: A list of dictionaries or a Pandas DataFrame :param table_columns: List of table column names, default None :param required_column: column name to add to the attribute data :param attribute_name_colu...
function
@Override public SAMRecordIterator assertSorted(final SAMFileHeader.SortOrder sortOrder) { if (sortOrder != SAMFileHeader.SortOrder.coordinate) { throw new IllegalStateException("Cannot assort " + sortOrder + " when expecting coordinate sorted input"); } return this; }
java
11
0.690096
118
43.857143
7
/** * Establishes that records returned by this iterator are expected to * be in the specified sort order. If this method has been called, * then implementers must throw an IllegalStateException from tmpReadEnds() * when a samRecordWithOrdinal is read that violates the sort order. This method ...
function
def evolve_wavefn_free(psi_0, a, b, m, dt=(1e-4*SECOND), delay=(0*SECOND), N=100, show_components=True): delay = delay.to(SECOND).value step_quantity = (b - a) / (N - 1) X_quantity = [a + i*step_quantity for i in range(N)] Y_quantity = [psi_0(x).standardize() for x in X_quantity] if Y_quantity[0].di...
python
19
0.571359
132
47.738095
42
Generates a moving plot of the free wavefunction over time, in the interval [a, b], for a particle of mass m. psi_0 should be a function returning a Quantity, in appropriate units. a and b should be Quantities with units of length. dt should be a Quantity with units of time. N is an integer, the number of sample points...
function
public class SemaphoreHandlerLock : IHandlerLock { private readonly int _operationCost; private readonly System.Threading.Semaphore _semaphore; private int _acquired = 0; public SemaphoreHandlerLock(string semaphoreName, int maxConcurrency = 1, int operationCost = 1) { _operationCost = operationCost; _sem...
c#
17
0.687646
100
32.038462
26
/// <summary> /// An implementation of <seealso cref="IHandlerLock"/> which uses a machine wide <seealso cref="System.Threading.Semaphore"/> to provide single access saga controls to a single machine. If you have multiple worker machines you will need to use a distributed locking mechanism /// </summary>
class
@JsType(isNative = true, namespace = "PIXI") public class ObservablePoint { /** * The position of the displayObject on the x axis * relative to the local coordinates of the parent. */ @JsProperty public double x; /** * The position of the displayObject on the x axis * relative...
java
7
0.612691
79
24.886792
53
/** * Created by klaun on 12/09/16. * The Point object represents a location in a two-dimensional * coordinate system, where x represents the horizontal axis * and y represents the vertical axis. * An observable point is a point that triggers a callback when * the point's position is changed. * @see <a href="htt...
class
@Test public void choosing_new_card_twice_state_bug() throws InterruptedException, BSPaymentRequestException, JSONException { setupBeforeSubscription(true, false); onView(ViewMatchers.withId(R.id.newCardButton)).perform(click()); Espresso.pressBack(); onView(ViewMatchers.withId(R.id....
java
11
0.723127
132
54.909091
11
/** * Test a bug in new card subscription flow when trying to choose new card twice and then change the state. * For full billing with shipping with email new shopper * with price details presented */
function
func (cr *ChunkedReader) openRange() (err error) { now := time.Now() defer func() { promOpenTimes.Observe(time.Since(now).Seconds()) if err != nil { promOpenErrors.Add(1) } }() offset, length := cr.chunkOffset, cr.chunkSize fs.Debugf(cr.o, "ChunkedReader.openRange at %d length %d", offset, length) if cr....
go
17
0.632911
111
26
41
// openRange will open the source Object with the current chunk range // // If the current open reader implements RangeSeeker, it is tried first. // When RangeSeek fails, o.Open with a RangeOption is used. // // A length <= 0 will request till the end of the file
function
func (c *Client) readPump() { defer func() { c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err...
go
21
0.586854
107
22.677778
90
// readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine.
function
public static IApplicationBuilder MapVersion( this IApplicationBuilder app, string path, object source = null) { if (app == null) throw new ArgumentNullException(nameof(app)); switch (source ?? Assembly.GetEntryAssembly()) { ...
c#
16
0.51049
77
37.2
15
/// <summary> /// Adds a custom endpoint to the pipeline, /// responding only to GET requests with the output /// from the specified version source. /// </summary> /// <param name="app">The `IApplicationBuilder` instance from `Startup.Configure()`.</param> /// <param name="path">The endpoint path to use.</param> /// <p...
function
public class SolutionTester implements Function<SolutionTest, CompletableFuture<TestResults>> { /** * The {@link SolutionPrinter} to use. Can be null if not needed. * * @since 1.0.0 */ protected @Nullable SolutionPrinter printer; /** * Construct a new <code>SolutionTester</code> wi...
java
11
0.621069
114
29
88
/** * Tester for {@link SolutionTest} tests. Utilizes {@link SolutionTestSolver} and {@link SolutionPrinter} to test and * print results. * <p> * Use {@link SolutionTester#apply(SolutionTest)} for * inputting a <code>SolutionTest</code>. * * @author Mikedeejay2 * @since 1.0.0 */
class
func (c *Client) ApplyMacros(in string, r *Recipient) (string, error) { if c.macros == nil { return in, nil } tokens, err := Tokenize(in) if err != nil { return "", err } chunks := make([]string, len(tokens)) for idx, token := range tokens { switch token.Type { case StaticToken: chunks[idx] = token.Te...
go
16
0.561283
71
20.85
40
// ApplyMacros runs all Macros registered with the Client against the provided string, returning the result. // If a Recipient is provided, substitution is performed on the macro parameter before the macro runs. // Any placeholders not handled by a macro are left intact.
function
ruuvi_driver_status_t ruuvi_interface_communication_ble4_gatt_dis_init(const ruuvi_interface_communication_ble4_gatt_dis_init_t* const dis) { if(NULL == dis) { return RUUVI_DRIVER_ERROR_NULL; } ret_code_t err_code = NRF_SUCCESS; ble_dis_init_t dis_init; memset(&dis_init, 0, sizeof(dis_init)); ruuvi_interface_...
c
8
0.724022
139
51.705882
17
/** * Initialize BLE4 Device Information service * * parameter dis: pointer to data which should be presented over DIS. Memory will be deep-copied */
function
private boolean isUSLanguageRefex(DescriptionVersionBI<?> desc) throws Exception { for (RefexVersionBI<?> annotation : desc.getAnnotationsActive(OTFUtility .getViewCoordinate())) { if (annotation.getAssemblageNid() == Snomed.US_LANGUAGE_REFEX.getNid()) { return true; } } retu...
java
10
0.672673
79
32.4
10
/** * Indicates whether or not US language refex is the case. * * @param desc the desc * @return <code>true</code> if so, <code>false</code> otherwise * @throws Exception the exception */
function
public static IList<IODataRoutingConvention> CreateDefaultWithAttributeRouting( string routeName, IRouteBuilder builder) { if (builder == null) { throw Error.ArgumentNull(nameof(builder)); } return CreateDefaultWithAttribute...
c#
13
0.604278
89
36.5
10
/// <summary> /// Creates a mutable list of the default OData routing conventions with attribute routing enabled. /// </summary> /// <param name="routeName">The name of the route.</param> /// <param name="builder">The <see cref="IRouteBuilder"/> to add the route to.</param> /// <returns>A mutable list of the default OD...
function
function resizeHeight() { if ($('#console-page').hasClass('collapsed')) { return; } var rowHeight = 200; $('.console-leaf-category').each(function() { const thisContainer = $('.console-build-column-stacked .console-cell-container-inner').first(); const thisHeight = thisContainer.he...
javascript
16
0.609783
101
40.863636
22
/** * Resizes commit cells when the window resizes. * * In the expanded view, the width is set by the browser window size. * When the window sizes changes, it changes the height of all the cells * because the cells contains elements that flow left to right. * Because the commit description on the left...
function
public boolean process( List<AssociatedPair> points, DMatrixRMaj solution ) { if (points.size() < 8) throw new IllegalArgumentException("Must be at least 8 points. Was only " + points.size()); LowLevelMultiViewOps.computeNormalization(points, N1, N2); createA(points, A); if (process(A, solution)) return f...
java
10
0.749064
94
40.153846
13
/** * <p> * Computes a fundamental or essential matrix from a set of associated point correspondences. * </p> * * @param points List of corresponding image coordinates. In pixel for fundamental matrix or * normalized coordinates for essential matrix. * @return true If successful or false if it failed */
function
makeRequestHeader(uri, options = {}) { return { rejectUnauthorized: this.strictSSL, method: options.method || 'GET', uri, json: true, ...options, }; }
javascript
7
0.547368
41
20.222222
9
/** * @name makeRequestHeader * @function * Creates a requestOptions object based on the default template for one * @param {string} uri * @param {object} [options] - an object containing fields and formatting how the */
function
update(endPosX, endPosY, offsetX, offsetY) { let endPos = createVector(endPosX + offsetX, endPosY + offsetY); if (this.flying) { if (this.origin.y < 200) { this.forward(); } else { if (this.angX > -480) { this.loopDeLoop(); } else if (this.origin.y > 110) { ...
javascript
18
0.472492
68
24.791667
24
// the flight behaviour needs to be based on three parts in sequence: flight to rotation, then rotation, then flight to formation
function
static void checkDirectMemCapacity(final int k, final long n, final long memCapBytes) { final int reqBufBytes = getUpdatableStorageBytes(k, n); if (memCapBytes < reqBufBytes) { throw new SketchesArgumentException("Possible corruption: Memory capacity too small: " + memCapBytes + " < " + reqBufBy...
java
12
0.701493
92
47
7
/** * Checks the validity of the direct memory capacity assuming n, k. * @param k the given value of k * @param n the given value of n * @param memCapBytes the current memory capacity in bytes */
function
public class EvaluationRunner extends Thread { private final Field cells; private int delayMs = 300; private int limitPopulation = 200000; //stop evaluation, when reached this limit volatile boolean stopRequested = false; private NotificationReceiver receiver=null; private TotalisticRule rule; public Evaluat...
java
18
0.704532
129
27.590164
61
/**Thread, that runs in background and continuously evaluates the field, when requested*/
class
def IsConfigUserInputValid(user_input, valid_el): if not user_input: return False try: valid_el.index(str(user_input)) except ValueError: return False return True
python
10
0.730337
49
24.571429
7
Sanity check for user input. Args: user_input: str User input. valid_el: list List of valid elements. Returns: bool True if user input is valid, False otherwise.
function
@Async public Future<String> run(RasterCropRequest payload, String id) throws AmazonClientException, InvalidInputException, IOException, InterruptedException { ServiceResource serviceResource = new ServiceResource(); serviceResource.setServiceResourceId(id); int percent = (new SecureRandom()).nextInt(101); ...
java
9
0.800534
91
47.869565
23
/** * Asynchronous handler for cropping the image demonstrating service monitor capabilities of piazza. * * @return Future */
function
def PenalizedLoss(mask, loss_func, mask_prop=1.0, mask_scaling=1.0, preprocessing_func=None): def scale_mask(mask, scaling): if scaling != 1.0: size = round(1 / scaling) mask = K.pool2d(mask, pool_size=(size, size), ...
python
17
0.501658
94
43.703704
27
Plaidml + tf Penalized loss function mask_scaling: For multi-decoder output the target mask will likely be at full size scaling, so this is the scaling factor to reduce the mask by. preprocessing_func: The preprocessing function to use. Should take a Keras In...
function
function generateText(table, textSize) { var key = randomKey(table); var text = key.split(" "); var prefixSize = text.length; for (var i=0; i < textSize-prefixSize; i++) { word = randomArrayElement(table[key]) text.push(word); key = text.slice(text.length-prefixSize, text.len...
javascript
13
0.597297
72
27.538462
13
/* Generate text from a Markov Random Chain @param {Object} table - associative array mapping prefixes => list of words. @param {int} textSize - number of words to include in the generated text. */
function
public class BidirectionalMultiMap<K, V> { /** * The multimap holding mappings from K -> V. */ private final SetMultimap<K, V> _primaryMap; /** * The multimap holding mappings from V -> K. */ private final SetMultimap<V, K> _secondaryMap; /** * The inverted BidirectionalMultiMap which is a v...
java
11
0.672095
101
29.709459
148
/** * A cut down multimap that also provides an inverted version of itself. If * there are many to many mappings from types K -> V and V -> K, this provides * methods to lookup all Vs associated with a K. By using the {@link #inverse()} * method, it is then possible to lookup all Ks associated with a V. * <p> * M...
class
public class WeakReferenceObservable extends DefaultObservable { public WeakReferenceObservable(final Observable observable) { super(observable); } @Override public void addObserver(final Observer referent) { super.addObserver(new WeakReferenceObserver(referent)); } /** *...
java
12
0.636706
120
29.615385
52
/** * Implementation of Observable that holds references to Observers as * WeakReferences. * * @note This implementation notifies the observers in a synchronous * fashion. Note that this can cause trouble if you notify observers while * in a transactional context because the notification is then done also in the ...
class
pub fn validate(&self) -> Result<(), &'static str> { if let Err(err) = self.validate_head() { return Err(err); } if let Some(ref tail) = self.tail { Chain::validate(tail) } else if self.head .hash() .eq(Block::genesis_block(self.head.diffic...
rust
17
0.466518
74
28.933333
15
/// Checks that the chain is valid from head to tail and that it starts from the genesis block. /// The current implementation is not the most efficient but is efficient enough /// for this simulation.
function
public class Bitboards { // Section 1 - Basic areas of the board. /** * Array of 64 bitboards representing single squares on a chessboard. They are * ordered from h1 to a8, the reason for this seemingly strange ordering is due * to the fact this is the natural representation taking into account these * bitboa...
java
10
0.726717
113
39.468421
190
/** * A class initialising all the variables we need to implement board * representation via the well known magic bitboard approach. * * @author TB * @date 21 Jan 2017 */
class
public async Task<Tuple<string, string>> Read(string collectionName, string key) { var docID = GetDocumentID(collectionName, key); var result = await bucket.GetAsync<string>(docID); if (result.Success) return Tuple.Create<string, string>(result.Value, result.C...
c#
13
0.613383
93
52.9
10
/// <summary> /// Reads a document representing a grain state object. /// </summary> /// <param name="collectionName">The type of the grain state object.</param> /// <param name="key">The grain id string.</param> /// <returns>Completion promise for this operation.</returns>
function
public Object authenticate(HpcIntegratedSystemAccount dataTransferAccount, String s3URLorRegion, String encryptionAlgorithm, String encryptionKey) throws HpcException { if (dataTransferAccount.getIntegratedSystem().equals(HpcIntegratedSystem.AWS)) { return authenticateAWS(dataTransferAccount.getUsername(), data...
java
11
0.825255
110
59.384615
13
/** * Authenticate a (system) data transfer account to S3 (AWS or 3rd Party * Provider) * * @param dataTransferAccount A data transfer account to authenticate. * @param s3URLorRegion The S3 URL if authenticating with a 3rd party S3 * Provider (Cleversafe, Cloudian, etc), or ...
function
public class LineBasedProtocol : IInternetPacket { public static byte[] CRLF = { 0x0D, 0x0A }; public byte[] EndOfLine { get; set; } = CRLF; public bool UsePrompt { get; set; } = false; internal byte[] PromptSequence { get; set; } public string Prompt { ge...
c#
18
0.498604
97
39.451613
62
/// <summary> /// Defines the "packet type" of line-based internet protocols /// Optionally will block lines received until a prompt sequence is received /// </summary>
class
@ServerEndpoint("/wstraffic") public class TrafficEndpoint { /* Queue for all open WebSocket sessions */ static Queue<Session> queue = new ConcurrentLinkedQueue<>(); private static final Logger log = Logger.getLogger("TrafficEndpoint"); /* Called by WebMDB when it receives messages from t...
java
15
0.588603
84
32.488372
43
/* This endpoint forwards to web clients the JSON messages * received by the WebMDB bean from the JMS topic */
class
public async Task<string> TranslateAsync(string text, string fromLanguage = null, string toLanguage = null) { try { text = text.Replace(" ", "%20"); var requestMethod = string.Format(_translateTextRequest, text, fromLanguage ?? _defaultFromLanguage, toLang...
c#
21
0.508576
180
54.547619
42
/// <summary> /// Translates a specific text from a particular language to another language. /// </summary> /// /// <exception cref="Exception"> Thrown when an exception error condition occurs. </exception> /// /// <param name="text"> The text to translate. </param> /// <param name="fromLanguage"> (Optional...
function
def interamp(SegyData1, SegyData2, shot=1, shot2=None, n_blocks=2, cap=0., levels=50, vmin=None, vmax=None, cmap=plt.cm.seismic, wstart=0, wend=None, xstart=0, xend=None, save=False, save_path="./"): if not (isinstance(SegyData1, tools.SegyData) and isinstance(SegyData2, tools.SegyData)): raise...
python
12
0.637115
108
52.28
25
Plots the interleaving amplitude map of a SegyData1 and SegyData2 objects in timesamples vs receiver index. Uses properties of matplotlib.contourf. Parameters ---------- SegyData1: fullwaveqc.tools.SegyData object outputted from fullwaveqc.tools.load function for the segy data SegyData...
function
public class DbContextOperations { private readonly IOperationReporter _reporter; private readonly Assembly _assembly; private readonly Assembly _startupAssembly; private readonly string[] _args; private readonly AppServiceProviderFactory _appServicesFactory; public D...
c#
27
0.578403
119
47.380952
210
/// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowi...
class
static int32_t I2C_GetDataCount (I2C_RESOURCES *i2c) { int32_t val; if ((i2c->info->status.mode == I2C_MODE_SLAVE) && ((i2c->info->ctrl & XFER_CTRL_ADDR_DONE) == 0U)) { val = -1; } else { if (i2c->info->status.direction == I2C_DIR_TX) { val = (int32_t)i2c->info->tx.cnt; } else { val = (i...
c
15
0.552279
102
25.714286
14
/** \fn int32_t I2C_GetDataCount (void) \brief Get transferred data count. \return number of data bytes transferred; -1 when Slave is not addressed by Master */
function
def element_wise(counter_method): def _make_iterator(*args): monitor_level = args[1] arg_pid = args[2] if hasattr(arg_pid, '__iter__'): pid_itr = (i for i in xrange(arg_pid[0], arg_pid[1])) else: pid_itr = (arg_pid,) if monitor_level == 'Thread': ...
python
16
0.506569
79
38.171429
35
This is a decorator function allowing multi-process/thread input. Note that this decorator should always follow the decorator 'tag_maker'.
function
@XmlRootElement(name = "VehicleProfiles") @XmlAccessorType(XmlAccessType.NONE) private final class VehicleProfilesXML { /** * List of vehicle profiles. */ @XmlElement(name = "profile", required = false) private List<VehicleProfile> profiles = new LinkedList<>(); /** * Name of the sel...
java
9
0.592852
76
21.206897
58
/** * JAXB compatible class that wraps a list of profiles and optionally the name * of the selected profile. */
class
private void dumpIgnores(PhysicsCollisionObject pco, String indent) { stream.print(':'); long[] idList = pco.listIgnoredIds(); String moreIndent = indent + indentIncrement(); for (long otherId : idList) { addLine(moreIndent); PhysicsDescriber describer = getDescri...
java
9
0.611966
73
40.857143
14
/** * Dump all ignored objects in the specified collision object. * * @param pco the body to dump (not null, unaffected) * @param indent (not null) */
function
def plot_topomap(self, times=None, ch_type='mag', layout=None, vmax=None, cmap='RdBu_r', sensors='k,', colorbar=True, scale=None, unit=None, res=256, size=1, format="%3.1f", proj=False, show=True): plot_evoked_topomap(self, times=times, ch_type=ch_t...
python
7
0.526316
79
68
8
Plot topographic maps of specific time points Parameters ---------- times : float | array of floats | None. The time point(s) to plot. If None, 10 topographies will be shown will a regular time spacing between the first and last time instant. ch_type ...
function
func (kv KVStoreClientImpl) Get(key string, retry bool) ([]byte, error) { var err error = fmt.Errorf("DUMMY") var val []byte for err != nil { val, err = kv.getWithoutRetry(key) if !retry || !isRetryable(err) { return val, err } time.Sleep(RETRY_WAIT) } return val, nil }
go
10
0.65035
73
22.916667
12
// Inform the lock manager we're interested in reading the value for key. // Expected return value: // Current version number associated with key // Expected error conditions: // Network failure => Retryable failure // Key does not exist => Fail immediately // // Once current version number has been succe...
function
void on_each_cpu_cond_mask(smp_cond_func_t cond_func, smp_call_func_t func, void *info, bool wait, const struct cpumask *mask) { int cpu = get_cpu(); smp_call_function_many_cond(mask, func, info, wait, cond_func); if (cpumask_test_cpu(cpu, mask) && cond_func(cpu, info)) { unsigned long flags; local_irq_sav...
c
8
0.670103
75
28.923077
13
/* * on_each_cpu_cond(): Call a function on each processor for which * the supplied function cond_func returns true, optionally waiting * for all the required CPUs to finish. This may include the local * processor. * @cond_func: A callback function that is passed a cpu id and * the info parameter. The function i...
function
func (e *Engine) LedgerForPeer(p peer.ID) *Receipt { ledger := e.findOrCreate(p) ledger.lk.Lock() defer ledger.lk.Unlock() return &Receipt{ Peer: ledger.Partner.String(), Value: ledger.Accounting.Value(), Sent: ledger.Accounting.BytesSent, Recv: ledger.Accounting.BytesRecv, Exchanged: l...
go
13
0.682997
52
28
12
// LedgerForPeer returns aggregated data about blocks swapped and communication // with a given peer.
function
@Override public void destroy() throws IOException { close(); serializer = null; monitorCache = null; client = null; }
java
6
0.630435
44
18.857143
7
/** * Notes: All the nodes and their datum will be deleted once the connection is broken(by call * {@code destroy()} or session timeout) between the zookeeper's client and server. * */
function
internal void SetTypes(ITypeSymbol targeType, ITypeSymbol sourceType) { if (TargetType is not null || SourceType is not null) { throw MappaGeneratorDiagnostics.InternalError("Unexpectedly setting source/target types twice", Method?.GetLocation()).AsException(); } TargetTy...
c#
15
0.673797
145
40.666667
9
/// <summary> /// Set the source and targe types. /// </summary> /// <param name="targeType">The target mapping type.</param> /// <param name="sourceType">The source mapping type.</param> /// <exception cref="Exceptions.MappaGeneratorException">If either the target type or the soruce type have been set already.</except...
function
function useIsFontSizeDisabled( { name: blockName } = {} ) { const fontSizes = useFontSizes(); const hasFontSizes = fontSizes.length; return ( ! hasBlockSupport( blockName, FONT_SIZE_SUPPORT_KEY ) || ! hasFontSizes ); }
javascript
9
0.711111
73
31.285714
7
/** * Custom hook that checks if font-size settings have been disabled. * * @param {string} name The name of the block. * @return {boolean} Whether setting is disabled. */
function
public static bool IsDeepEqual<T>(this T x, T y, bool checkStrictTypeEquality = true) where T : class { if (x == y) return true; if (x == null || y == null) return false; var leftType = x.GetType(); var equatableType = leftType.GetI...
c#
18
0.437628
102
34.804878
41
/// <summary> /// The IsDeepEqual function detects if two objects have strictly the same properties (not necessarily the same object). /// </summary> /// <typeparam name="T">The type of objects that are compared.</typeparam> /// <param name="x">First object to compare.</param> /// <param name="y">Second object to compa...
function
bool idMatX::IsPositiveDefinite( const float epsilon ) const { int i, j, k; float d, s; idMatX m; if( !IsSquare() ) { return false; } m.SetData( numRows, numColumns, MATX_ALLOCA( numRows * numColumns ) ); m = *this; for( i = 0; i < numRows; i++ ) { for( j = 0; j < numColumns; j++ ) { m[i][j] += ( *th...
c++
15
0.457903
71
15.95
40
/* ============ idMatX::IsPositiveDefinite returns true if the matrix is Positive Definite (PD) A square matrix M of order n is said to be PD if y'My > 0 for all vectors y of dimension n, y != 0. ============ */
function
def _chooseBuild(self, buildrequests): if self.nextBuild: d = defer.gatherResults([ self._brdictToBuildRequest(brdict) for brdict in buildrequests ]) d.addCallback(lambda requestobjects : self.nextBuild(self, requestobjects)) ...
python
12
0.547244
72
41.416667
12
Choose the next build from the given set of build requests (represented as dictionaries). Defaults to returning the first request (earliest submitted). @param buildrequests: sorted list of build request dictionaries @returns: a build request dictionary or None via Deferred ...
function
public sealed class ClientModel { readonly IMessageQueue _queue; ImmutableDictionary<StuffId, ImmutableStuff> _stuffInInbox = ImmutableDictionary.Create<StuffId, ImmutableStuff>(); readonly List<MutableProject> _projectList = new List<MutableProject>(); readonly Dictionar...
c#
23
0.559069
111
38.262931
232
/// <summary> This is part of the "Client Model" or "UI" Context /// This context is similar to a read model but it also has certain behaviors. /// You can perceive this "client model context" as an Aggregate that reacts to /// Events that are published by the to Domain Model. /// This "aggregate" maintains its own in...
class
static int analogix_dp_prepare_panel(struct analogix_dp_device *dp, bool prepare, bool is_modeset_prepare) { int ret = 0; if (!dp->plat_data->panel) return 0; mutex_lock(&dp->panel_lock); if (dp->panel_is_modeset && !is_modeset_prepare) goto out; if (prepare) ret = drm_panel_prepare(dp->plat_data->p...
c
11
0.670543
67
23.619048
21
/* * This function is a bit of a catch-all for panel preparation, hopefully * simplifying the logic of functions that need to prepare/unprepare the panel * below. * * If @prepare is true, this function will prepare the panel. Conversely, if it * is false, the panel will be unprepared. * * If @is_modeset_prepare...
function
@Override public Map<String, Object> postProcessAllModels(Map<String, Object> objs) { final Map<String, Object> processed = super.postProcessAllModels(objs); postProcessEnumRefs(processed); updateValueTypeProperty(processed); updateNullableTypeProperty(processed); return proc...
java
7
0.710843
79
40.625
8
/** * Invoked by {@link DefaultGenerator} after all models have been post-processed, allowing for a last pass of codegen-specific model cleanup. * * @param objs Current state of codegen object model. * @return An in-place modified state of the codegen object model. */
function
public sealed class AssetArchive : Archive { public AssetArchive(IDictionary<string, AssetOrArchive> assets) : base(Constants.ArchiveAssetsName, assets.ToImmutableDictionary()) { } }
c#
9
0.654867
79
31.428571
7
/// <summary> /// An AssetArchive is an archive created from an in-memory collection of named assets or other /// archives. /// </summary>
class
def choose_move(self, move_temperature, random_move_probability=0.0): x = np.random.rand() if x < random_move_probability: valid_moves = (self.root.edge_stats['N'] > 0) probs = valid_moves.astype(np.float32) / np.sum(valid_moves) else: exponent = 1.0 / move_te...
python
16
0.552308
73
45.5
14
Chooses a move (policy) according to the MCTS stats. Args: move_temperature: float: exponential factor to rebalance the policy and control its level of exploration. This value corresponds to 1 / \tau in [1]. random_move_probability: float: probability of making a to...
function
@Test(groups = "functional", testName = "iteration.ReplicatedEntryRetrieverWithLoaderTest") public class ReplicatedEntryRetrieverWithLoaderTest extends BaseEntryRetrieverWithLoaderTest { public ReplicatedEntryRetrieverWithLoaderTest() { super(false, CacheMode.REPL_SYNC, "ReplicatedEntryRetrieverWithLoaderTest...
java
8
0.824242
94
46.285714
7
/** * Test to verify replicated entry behavior when a loader is present * * @author afield * @since 7.0 */
class
void AliQnCorrectionsQnVectorBuild::NormalizeQoverM() { if(fSumW < fMinimumSignificantValue) { SetGood(kFALSE); } else { for(Int_t h = 1; h < fHighestHarmonic + 1; h++){ if ((fHarmonicMask & harmonicNumberMask[h]) == harmonicNumberMask[h]) { fQnX[h] = (fQnX[h] / fSumW); fQnY[h] = (fQ...
c++
16
0.583099
77
26.384615
13
/// Normalizes the build Q vector for the whole harmonics set /// /// Normalizes the build Q vector as \f$ Qn = \frac{Qn}{M} \f$. /// A check for significant value is made. Not passing it /// does set the Q vector quality as bad
function
func (c *customDNSProviderSolver) Present(ch *v1alpha1.ChallengeRequest) error { cfg, err := loadConfig(ch.Config) if err != nil { return err } ib, err := c.getIbClient(&cfg, ch.ResourceNamespace) if err != nil { return err } recordName := c.DeDot(ch.ResolvedFQDN) recordRef, err := c.GetTXTRecord(ib, record...
go
11
0.676754
98
28.12
25
// Present is responsible for actually presenting the DNS record with the // DNS provider. // This method should tolerate being called multiple times with the same value. // cert-manager itself will later perform a self check to ensure that the // solver has correctly configured the DNS provider.
function
def _define_criteria( self, min_improvement_per_round: float = MIN_IMPROVEMENT_PER_ROUND, max_num_rounds: int = MAX_NUM_ROUNDS, distance_to_the_wall: float = DISTANCE_TO_THE_WALL, num_near_the_wall: int = NUM_NEAR_THE_WALL, min_num_init: int = MIN_NUM_INIT, max_nu...
python
6
0.610606
69
43.066667
15
Define criteria that control the number of iterations in the algorithm. There are two types of iterations in the algorithm: (i) Multiple rounds of coordinate descent until a local optimum is reached. (ii) Multiple choices of initial values until we have confidence that ...
function
pub fn new( irq: u32, ioapic: Arc<Mutex<Ioapic<WhpInterruptController>>>) -> Result<InterruptEvent> { Ok(InterruptEvent{ ioapic: ioapic, irq: irq, }) }
rust
10
0.484581
62
21.8
10
/// Create a new InterruptEvent object. // TODO(lpetrut): we may consider assigning those separately so that // we keep a similar interface with EventFd.
function
public Boolean IsAuthenticated(String domain, String username, String password) { bool stat = false; string path = String.Format("LDAP://{0}", domain.ToUpper()); DirectoryEntry entry = new DirectoryEntry(path, username, password); try { Object obj = entry....
c#
13
0.540293
81
41.076923
13
/// <summary> /// Checks to see if username and password are authenticatable. /// </summary> /// <param name="username">The username to use.</param> /// <param name="password">The password to use.</param> /// <returns>Return true if authenticated.</returns> ///
function
def _save_cluster_representatives(self, clusters, dataframe, path, representatives_criterion): import os from collections import defaultdict import numpy as np from pele_platform.Utilities.Helpers import get_suffix from pele_platform.Utilitie...
python
19
0.548617
78
51.602273
88
It saves the resulting clusters to disk. The selection of the representative structures is based on the total energy. The structure chosen as the representative will be the closer to the 5th percentile of total energy. Parameters ---------- clusters : a numpy.ar...
function
class HrefButtonArea extends ImageMapArea { /** The URL to be fetched when the user clicks on this area. */ URL anchor; /** The highlight image for the bright parts of the 3-D effect. */ Image brightImage; /** The highlight image for the dark parts of the 3-D effect. */ Image darkImage; ...
java
12
0.614413
74
31.259259
81
/** * An improved "Fetch a URL" ImageArea class. * This class extends the basic ImageArea Class to fetch a URL when * the user clicks in the area. In addition, special custom highlights * are used to make the area look and feel like a 3-D button. * * @author Jim Graham * @version %I%, %G% */
class
def scrape_meetings(self, meetings, group): for meeting in meetings: when = self.get_date(meeting) description = self.get_description(meeting) location = self.get_location(meeting) if when and description and location: kwargs = {} i...
python
13
0.51897
70
45.1875
16
Scrape and save event data from a list of meetings. Arguments: meetings -- A list of lxml elements containing event information group -- The type of meeting. The legislature site applies different formatting to events based on which group they correspo...
function
function registerSubscription(forceCreate) { return new Promise(function (resolve, reject) { var FILE_SUBSCRIPTION = 'subscription.id'; var subscriptionId; try { subscriptionId = fs.readFileSync(__dirname + '/' + FILE_SUBSCRIPTION, 'UTF-8'); } catch(e) ...
javascript
22
0.570444
79
29.395349
43
// Subscribes to context changes creating or renewing a subscription
function
public virtual CreateRegexMatchSetResponse CreateRegexMatchSet(CreateRegexMatchSetRequest request) { var options = new InvokeOptions(); options.RequestMarshaller = CreateRegexMatchSetRequestMarshaller.Instance; options.ResponseUnmarshaller = CreateRegexMatchSetResponseUnmarsh...
c#
10
0.747017
98
59
7
/// <summary> /// <note> /// <para> /// This is <b>AWS WAF Classic</b> documentation. For more information, see <a href="https://docs.aws.amazon.com/waf/latest/developerguide/classic-waf-chapter.html">AWS /// WAF Classic</a> in the developer guide. /// </para> /// /// <para> /// <b>For the latest version of AWS WAF...
function
@Variability(id = { AnnotationConstants.VAR_GATHER_DATA, AnnotationConstants.VAR_WIFI_DATA }, op = Operation.AND) public class Data implements DataMBean { /** * Instance of {@link IDataGatherer} for gathering required informations. * * @since 1.00 */ @Variability(id = { An...
java
10
0.633277
77
27
61
/** * Defines an object for delegation of the values from the interface * {@link IDataGatherer} to the {@link StandardMBeanAgent}. * * @author Stephan Dederichs * * @since 1.00 * @version 1.00 */
class
public class RemoveItem extends ShellCommands { /** * This method removes all the child node of the node tar * @param fileSys * @param tar */ private static void clearAllChildren(FileManager fileSys, FileSystemNode tar) { ArrayList<FileSystemNode> list = fileSys.getChildren(tar); if (list == nu...
java
12
0.65078
81
26.5
42
/** * This Class extends ShellCommands, Since users might frequently remove item * from the file system, this class is designed for this purpose */
class
public class Solution { // leetcode optimal solution public int largestPalindrome(int n) { if(n==1) return 9; int hiBound = (int)Math.pow(10,n)-1,lowBound = (int)Math.pow(10,n-1)-1; // if n = 3, first half would be 998001/1000 = 998 // the most tricky part about this problem woul...
java
15
0.534942
79
31.513514
37
/** * Find the largest palindrome made from the product of two n-digit numbers. * * Since the result could be very large, * you should return the largest palindrome mod 1337. * * Example: * Input: 2 * Output: 987 * Explanation: 99 x 91 = 9009, 9009 % 1337 = 987 * * Note: * The range of n is [1,8]. */
class
public class SongRecyclerViewAdapter extends RecyclerView.Adapter<SongRecyclerViewAdapter.ViewHolder> { private static final Comparator<DatabaseSong> mComparator = (a, b) -> { if (!a.getTitle().equalsIgnoreCase(b.getTitle())) return a.getTitle().compareToIgnoreCase(b.getTitle()); return...
java
19
0.61549
183
44.769634
191
/** * {@link RecyclerView.Adapter} that can display a {@link Song} and makes a call to the * specified {@link OnListFragmentInteractionListener}. */
class
public async Task<List<PropertyValueSuggestion>> GetAutomaticMetadataAsync(AutomaticMetadataRequestInfo requestInfo, CancellationToken token = default(CancellationToken)) { var request = new RestRequest($"/REST/objects/automaticmetadata.aspx"); request.AddJsonBody(requestInfo); var response = await this.M...
c#
17
0.792237
116
47.777778
9
/// <summary> /// Returns the IML metadata suggestions for the given temporary files and object version. /// </summary> /// <param name="requestInfo">The request for automatic metadata suggestions.</param> /// <param name="token">A cancellation token for the request.</param> /// <returns>An awaitable task for any metad...
function
public void RegisterCondition (string id, ConditionType type) { type.Id = id; ConditionInfo info = CreateConditionInfo (id); ConditionType ot = info.CondType as ConditionType; if (ot != null) ot.Changed -= new EventHandler (OnConditionChanged); info.CondType = type; type.Changed += new EventHand...
c#
11
0.716332
61
34
10
/// <summary> /// Registers a new condition in the extension context. /// </summary> /// <param name="id"> /// Identifier of the condition. /// </param> /// <param name="type"> /// Condition evaluator. /// </param> /// <remarks> /// The registered condition will be particular to this extension context. /// Any event th...
function
public static Gumshoe createDefaultInstance() { return new Gumshoe(new ConfigFinder() { public boolean pathExists(final String path) { return Files.exists(Path.of(path)); } public InputStream getInputStream(final String path) throws IOExcep...
java
15
0.577342
64
40.818182
11
/** * This is the normal way to create an instance of Gumshoe. * * @since 1.0.0 * @return A new Gumshoe instance that is capable of interacting with the * file system and system environment. */
function