code stringlengths 0 30.8k | source stringclasses 6
values | language stringclasses 9
values | __index_level_0__ int64 0 100k |
|---|---|---|---|
saveExisting(event) {
event.preventDefault();
this.props.saveLoopThunk(this.props.sounds, this.props.loopId);
toast('Loop Saved!', {
position: 'bottom-right',
autoClose: 2000
});
} | function | javascript | 0 |
public boolean isModletIncluded( final Modlet modlet )
{
if ( modlet == null )
{
throw new NullPointerException( "modlet" );
}
for ( final NameType include : this.getModletIncludes() )
{
if ( include.getName().equals( modlet.getName() ) )
{... | function | java | 1 |
public static string CreateMessageForInaccessibleType(Type inaccessibleType, Type typeToProxy)
{
var targetAssembly = typeToProxy.Assembly;
string inaccessibleTypeDescription = inaccessibleType == typeToProxy
? "it"
: "type " + inaccessibleType.GetBestName();
var messageFormat = "Can not create proxy... | function | c# | 2 |
def app():
app = create_app()
db_fd, db_filepath = tempfile.mkstemp(suffix=".sqlite3")
app.config["DATABASE"] = {
"name": db_filepath,
"engine": "peewee.SqliteDatabase",
}
db.init_app(app)
with db.database.bind_ctx(MODELS):
db.database.create_tables(MODELS)
db.clo... | function | python | 3 |
public class ArmstrongNumber {
public static void main(String[] args) {
Integer givenNumber = 153;
Boolean isArmstrongNumber = isArmstrongNumber(givenNumber);
if (isArmstrongNumber) {
System.out.println(givenNumber + " " + "is an Armstrong number.");
} else {
System.out.println(givenNumber + " " + "is ... | class | java | 4 |
private IEnumerator<ITask> LightsControlLoop()
{
int i = 0;
List<pololumaestro.ChannelValuePair> channelValues = new List<pololumaestro.ChannelValuePair>();
while (!_state.Dropping)
{
switch (lightsTestMode)
{
ca... | function | c# | 5 |
private XDataFrameGroupingCols<R,C> combine(XDataFrameGroupingCols<R,C> other) {
other.groupKeysMap.forEach((groupKey1, groupKeys1) -> {
final Array<C> groupKeys2 = this.groupKeysMap.get(groupKey1);
if (groupKeys2 == null) {
this.groupKeysMap.put(groupKey1, groupKeys1);
... | function | java | 6 |
public IEnumerable<TModel> Create<TModel>(ICollection<TModel> itemsToCreate)
where TModel : EndpointModelBase
{
string requestXml = ModelSerializer.Serialize(itemsToCreate);
string responseXml = _proxy.CreateElements(typeof(TModel).Name, requestXml);
Response resp... | function | c# | 7 |
public void AddBlueprint(string blueprintId, Blueprint blueprint)
{
if (blueprintId == null)
{
throw new ArgumentNullException("blueprintId", "No blueprint id provided.");
}
if (string.IsNullOrEmpty(blueprintId))
{
throw... | function | c# | 8 |
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Beans:");
Arrays.stream(appContext.getBeanDefinitionNames()).forEach(System.out::println);
System.out.println("===================");
System.out.println("Demonstrate how you can use the applicationC... | function | java | 9 |
def add(self, other):
self._previous = self._current.copy()
if isinstance(other, set):
self._current.update(other)
else:
if other in self._current:
self._current.add('GROUP')
else:
if len(self._current) != 0:
... | function | python | 10 |
char *rfctimestamp(u32 stamp) {
time_t atime = stamp;
struct tm tmbuf, *tp;
if (IS_INVALID_TIME_T(atime)) {
gpg_err_set_errno(EINVAL);
return NULL;
}
tp = gnupg_gmtime(&atime, &tmbuf);
if (!tp) return NULL;
return xtryasprintf(
"%.3s, %02d %.3s %04d %02d:%02d:%02d +0000",
&"SunMonTueWe... | function | c++ | 11 |
static int btreeBtSharedGet(
BtShared **ppBt,
const char *fullname,
sqlite3 *db,
int vfsFlags)
{
Btree *pExisting;
BtShared *next_bt;
int iDb;
char *fullBuf[BT_MAX_PATH];
#ifdef SQLITE_DEBUG
sqlite3_mutex *mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
assert(sqlite3_mutex_held(mutexOpen... | function | c | 12 |
public class ValidateVObject implements Validate<Object, VObject> {
public boolean validate(final AnnotationMetaData annotationMetaData, Object value, VObject annotation, ViolationInfoHandler violationInfoHandler) {
if (value == null) {
if (annotation.mandatory()) {
violationIn... | class | java | 13 |
async def rutrivia_leaderboard_global(
self, ctx: commands.Context, sort_by: str = "wins", top: int = 10
):
key = self._get_sort_key(sort_by)
if key is None:
await ctx.send(
_(
"Unknown field `{field_name}`, see `{prefix}help rutrivia leaderboa... | function | python | 14 |
async function buyStarByToken() {
const {lookUptokenIdToStarInfo, buyStar} = props.instance.methods;
const tokenId = parseInt(tokenHash.value, 16);
if (isNaN(tokenId)) {
alertMsg({msg: `${tokenHash.value} is not a valid ID`, variant: 'warning'});
} else {
try {
... | function | javascript | 15 |
private Node box(Node node, int modifier) {
if (node.getModifier() == Node.ONE_OF || node.getModifier() == Node.ONE_TERMINAL_OF) {
return nodeCreator.oneNode(listOf(node)).clone(modifier);
}
if (node.getModifier() == Node.ZERO_OR_MORE) {
return node;
}
ret... | function | java | 16 |
def generate_slack_report(self):
_report = ""
_report = _report + self.generate_header() + "\n"
_report = _report + self.generate_metadata() + "\n"
_report = _report + self.generate_summary() + "\n"
_full_body = self.generate_body_full()
if (len(_report) + len(_full_body)... | function | python | 17 |
internal void DerivePhysicsTransformation(out Matrix derivedTransformation)
{
Matrix rotation;
Vector3 translation;
Vector3 scale;
Entity.Transform.WorldMatrix.Decompose(out scale, out rotation, out translation);
var translationMatrix = Matrix.Translat... | function | c# | 18 |
private List<ProcessResultMessage> ValidateFHS(ReadOnlySpan<char> fhsSegment)
{
var errorMessages = new List<ProcessResultMessage>();
if (fhsSegment.Length >= 8)
{
ReadOnlySpan<char> fhsEncodingCharacters = fhsSegment.Slice(3, 5);
if (fhsEncodi... | function | c# | 19 |
function buffer(func, timeBetweenCalls, bufferSize) {
const bufferingOn = (bufferSize !== undefined && bufferSize > 0);
const argBuffer = (bufferingOn) ? [] : undefined;
const addToBuffer = (item)=>{
if (argBuffer.length >= bufferSize) {
argBuffer.pop();
}
argBuffer.unshift(item);
};
let blo... | function | javascript | 20 |
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
if(this._Bill < (int)0)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for _Bill, must be a val... | function | c# | 21 |
def _check_and_get_mask(logu, joint_sample_mask=None, validate_args=False):
with tf.name_scope('get_default_mask'):
logu = tf.convert_to_tensor(
logu, dtype_hint=tf.float32, name='logu')
if joint_sample_mask is None:
num_rows, num_cols = tf.unstack(tf.shape(logu)[-2:])
joint_sample_mask = ... | function | python | 22 |
[MethodImpl(MethodImplOptions.NoInlining)]
private static ExitType OldOMBuildProject(ExitType exitType, string projectFile, string[] targets, string toolsVersion, Dictionary<string, string> globalProperties, ILogger[] loggers, LoggerVerbosity verbosity, bool needToValidateProject, string schemaFile, int cpuCoun... | function | c# | 23 |
def extract_narr_aux_data(espa_metadata, aux_path):
logger = logging.getLogger(__name__)
(dummy, t0_date, t1_date) = util.NARR.dates(espa_metadata)
logger.info('Before Date = {}'.format(str(t0_date)))
logger.info(' After Date = {}'.format(str(t1_date)))
for aux_set in aux_filenames(aux_path, PARMS_T... | function | python | 24 |
public class EnvironmentNameResolver {
private static volatile EnvironmentNameResolver defaultEnvironmentNameResolver = new EnvironmentNameResolver();
/**
* Set default EnvironmentNameResolver instance.
*
* @param resolver new default resolver
*/
public static void setDefaultEnvironmentNameResolve... | class | java | 25 |
def predict_sequence(self,sequence,pred,peptideList=False):
if not peptideList:
peptide_list = get_peptides(sequence, self.length)
else:
peptide_list = sequence
scores = self.predict_peptide_list(peptide_list)
return scores | function | python | 26 |
public class InterceptingReduxMiddleware : IReduxMiddleware
{
private readonly Action<IReduxMessage, IReduxDispatcher> _dispatch;
public InterceptingReduxMiddleware(Action<IReduxMessage, IReduxDispatcher> dispatch)
{
_dispatch = dispatch ?? throw new ArgumentNullException(nameof(... | class | c# | 27 |
def _assert_internal_invariants(self, fast=True):
if self._Xarr is None:
assert self._Yarr is None
assert self._Xview is None
assert self._Yview is None
else:
assert self._Yarr is not None
assert self._Xview is not None
assert self.... | function | python | 28 |
[Export(typeof(IVsOptionalService<,>))]
internal class VsOptionalService<TService, TInterface> : VsOptionalService<TInterface>, IVsOptionalService<TService, TInterface>
{
[ImportingConstructor]
public VsOptionalService([Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider, IProjec... | class | c# | 29 |
public boolean isOwnerPassword(byte[] ownerPassword, byte[] user, byte[] owner,
int permissions, byte[] id, int encRevision, int length,
boolean encryptMetadata) throws IOException
{
if (encRevision == 6 || encRevision == 5)
{
byte[] truncatedOwnerPassword = truncate127(ownerPassword);
byte... | function | java | 30 |
def stategraph(automaton, fmt=None, traversal=None):
graph = automaton.__graph__
source_nodes = filter(lambda n: not graph.in_edges(n), graph.nodes())
sink_nodes = filter(lambda n: not graph.out_edges(n), graph.nodes())
sources = [('[*]', node) for node in source_nodes]
sinks = [(node, '[*]') for ... | function | python | 31 |
def generator(z):
with tf.variable_scope("generator"):
img = tf.layers.dense(z,4*4*512,activation=tf.nn.relu,use_bias=True)
img = tf.layers.batch_normalization(img,axis=1,training=True)
img = tf.reshape(img,[-1,4,4,512])
print(img.shape)
img = tf.layers.conv2d_transpose(img,2... | function | python | 32 |
HRESULT
ValidateUserObject(
POBJECTINFO pObjectInfo
)
{
NWCONN_HANDLE hConn = NULL;
HRESULT hr = S_OK;
DWORD dwResumeObjectID = 0xffffffff;
if (pObjectInfo->NumComponents != 2) {
RRETURN(E_ADS_BAD_PATHNAME);
}
hr = NWApiGetBinderyHandle(
&hConn,
pObjec... | function | c++ | 33 |
private void init(final Persistit persistit, final Class clientClass, final boolean mustBeSerializable) {
_clazz = clientClass;
_persistit = persistit;
_serializable = Serializable.class.isAssignableFrom(clientClass);
if (_serializable) {
_externalizable = Externalizable.clas... | function | java | 34 |
def genFile(files,fName,postfix):
script = open(fName,"w")
firstline='dbName,simuType,nside,coadd,fieldtype,nproc\n'
script.write(firstline)
r = []
for fi in files:
dbName = fi.split('/')[-1].split('.db')[0]
r.append(len(dbName))
for fi in files:
dbName = fi.split('/')[-1... | function | python | 35 |
protected virtual void Dispose( bool disposing )
{
if ( disposed )
{
return;
}
disposed = true;
if ( !disposing )
{
return;
}
lock ( syncRoot )
{
foreach ( ... | function | c# | 36 |
def _drop_obsolete_columns(self, df_season: pd.DataFrame) -> pd.DataFrame:
if self._mode == "time_series":
df_season = df_season.drop("month", axis=1)
elif self._mode in ["climatology", "departures"]:
df_season = df_season.drop(["year", "month"], axis=1)
else:
... | function | python | 37 |
private ReadOnlyCollection<LoadedAssemblyDetails> GetAssembliesInternal()
{
lock (_explicitLoadedAssemblies)
{
return _explicitLoadedAssemblies
.Distinct()
.ToList().AsReadOnly();
}
} | function | c# | 38 |
public XmlDocument parseInputStream(InputStream is, String encoding) throws XmlBuilderException
{
XmlPullParser pp = null;
try {
pp = factory.newPullParser();
pp.setInput(is, encoding);
} catch (XmlPullParserException e) {
throw new XmlBuilderException("co... | function | java | 39 |
public void SynchronizeSlimChain(SlimChain chain, uint256 hashStop = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (chain is null)
throw new ArgumentNullException(nameof(chain));
AssertState(NodeState.HandShaked, cancellationToken);
Logs.NodeServer.LogInformation("Building ... | function | c# | 40 |
func (bm *BoundedMeanFloat64) Result() float64 {
if bm.state != defaultState {
log.Fatalf("Mean's noised result cannot be computed. Reason: " + bm.state.errorMessage())
}
bm.state = resultReturned
noisedCount := math.Max(1.0, float64(bm.Count.Result()))
noisedSum := bm.NormalizedSum.Result()
clamped, err := Cla... | function | go | 41 |
public static double[] ComputeDiscardComplementsGaussLegendreAltInvariant(Normal[] distributions, double[] evalPoints, double[] weights)
{
if (evalPoints.Length != weights.Length) { throw new ArgumentException("Error: Evaluation points must have same length as weights."); }
int fevals = ... | function | c# | 42 |
async def _create_rev_reg(self, rr_id: str, rr_size: int = None) -> None:
LOGGER.debug('Issuer._create_rev_reg >>> rr_id: %s, rr_size: %s', rr_id, rr_size)
rr_size = rr_size or 256
(cd_id, tag) = rev_reg_id2cred_def_id__tag(rr_id)
LOGGER.info('Creating revocation registry (capacity %s) f... | function | python | 43 |
class AxisView extends LayerView {
/**
* @param {Axis} axisProps
* @param {import("./viewUtils").ViewContext} context
* @param {string} type Data type (quantitative, ..., locus)
* @param {import("./containerView").default} parent
*/
constructor(axisProps, type, context, parent) {
... | class | javascript | 44 |
int columnar_get_col_width(int typid, int width, bool aligned)
{
if (COL_IS_ENCODE(typid)) {
if (aligned) {
return alloc_trunk_size(width);
} else {
return width;
}
} else
return 0;
} | function | c++ | 45 |
public String serialize(XMLStreamReader reader) {
if (reader == null) {
throw new IllegalArgumentException("XMLStreamReader cannot be null");
}
try {
if (transformer == null) {
transformer = transformerFactory.newTransformer();
... | function | java | 46 |
def plot_coverage(self,spheres):
box = self.domain_dimensions
if box.dim_z != 0:
for sph in spheres:
dent = 2*sph.r*(0.4/1.18)
circle = plt.Circle((sph.x, sph.z), dent/2 , edgecolor = 'black', facecolor = 'red', alpha = 0.08)
plt.gca().add_patc... | function | python | 47 |
def ExecuteQuery(self, query_name: Text) -> Tuple[float, Dict[str, str]]:
query_command = (
'python script_driver.py --script={} --server={} --database={} '
'--user={} --password={} --query_timeout={}').format(
query_name, self.server_name, self.database, self.user,
self.pass... | function | python | 48 |
public List<ColumnType> types() {
List<ColumnType> columnTypes = new ArrayList<>(columnCount());
for (int i = 0; i < columnCount(); i++) {
columnTypes.add(columns().get(i).type());
}
return columnTypes;
} | function | java | 49 |
private String longTo3String(long l) {
String[] returnThis = new String[3];
String longS = Long.toString(l);
int div = longS.length()/3;
returnThis[0]=longS.substring(0, div);
returnThis[1]=longS.substring(div, (2*div));
returnThis[2]=longS.substring(2*div);
String returnme = returnThis[0]+" " + returnThis[1]+"... | function | java | 50 |
def EnumToRegex(enum_type: Optional[Type[E]] = None,
omit: Optional[List[E]] = None,
exactly: Optional[E] = None) -> syaml.Regex:
if exactly:
if enum_type or omit:
raise ValueError('Cannot specify an exact value with other constraints')
return _OrRegex([exactly.value])
... | function | python | 51 |
def shorten_url(url: str) -> str:
The performance of this algorithm in the worst case is terrible, but per
the current parameters there are 7**62 possible shortkeys, so it is
unlikely that step 3 of the algorithms will ever be reached.
InvalidURLError is propogated to caller
url = _validate_url(... | function | python | 52 |
static void
gtaskqueue_drain_tq_active(struct gtaskqueue *queue)
{
struct gtaskqueue_busy tb_marker, *tb_first;
if (TAILQ_EMPTY(&queue->tq_active))
return;
queue->tq_callouts++;
tb_marker.tb_running = TB_DRAIN_WAITER;
TAILQ_INSERT_TAIL(&queue->tq_active, &tb_marker, tb_link);
while (TAILQ_FIRST(&queue->tq_activ... | function | c | 53 |
private object GetStoryParameter(object p, bool viewerNeeded)
{
object parameter = null;
StoryViewer storyViewer = p as StoryViewer;
if (storyViewer != null)
{
if (viewerNeeded)
{
parameter = storyViewer;
... | function | c# | 54 |
fn parse_set_args(args: Vec<String>) -> Subcommand {
let mut simple = HashMap::new();
let mut json = None;
let mut iter = args.into_iter();
while let Some(arg) = iter.next() {
match arg.as_ref() {
"-j" | "--json" if json.is_some() => {
usage_msg(
"... | function | rust | 55 |
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"spottingPattern",
"orientation"
})
public static class Pattern {
@XmlElement(required = true)
protected OntologyEntryType spottingPattern;
@XmlElement(required = true)
protecte... | class | java | 56 |
public static Constructor<?> lookup(final Class<?> clazz, final Class<?>[] argTypes) {
final Constructor<?> cachedConstructor = get(clazz, argTypes);
if (cachedConstructor != null) {
return cachedConstructor;
} else {
final Constructor<?> uncachedConstructor = directConst... | function | java | 57 |
private void prepareForNewBatchQuery() {
if (completed) {
LOG.debug().$("prepare for new query").$();
isEmptyQuery = false;
bindVariableService.clear();
currentCursor = Misc.free(currentCursor);
typesAndInsert = null;
clearCursorAndFactory(... | function | java | 58 |
parseOptions(tokens) {
const options = emptyTextureOptions();
let option;
let values;
const optionsToValues = {};
tokens.reverse();
while (tokens.length) {
const token = tokens.pop();
if (token.startsWith("-")) {
option = token.subs... | function | javascript | 59 |
bool SpdyAltSvcWireFormat::ParseProbability(StringPiece::const_iterator c,
StringPiece::const_iterator end,
double* probability) {
if (c == end) {
return false;
}
if (end - c == 1 && *c == '.') {
return false;
}
if... | function | c++ | 60 |
def screenSelect(self, direction):
lstScreens = self.root.screen_names
screenIndex = lstScreens.index(self.root.current)
if direction == 'previous':
screenIndex -= 1
self.root.transition = SlideTransition(direction='right')
if screenIndex < 0:
self.root.transition = SlideTransition... | function | python | 61 |
public static int register(Class<? extends JHeader> c,
List<HeaderDefinitionError> errors) {
AnnotatedHeader annotatedHeader = inspect(c, errors);
if (errors.isEmpty() == false) {
return -1;
}
Entry e = mapByClassName.get(c.getCanonicalName());
if (e == null) {
e = createNewEntry(c);
}
int id = e... | function | java | 62 |
private Watchlist decode(String line) {
String[] lineSplit = line.split(WATCHLIST_LINE_DELIMITER_FOR_DECODE, 2);
if (!isValidWatchlistString(lineSplit)) {
return null;
}
String watchlistName = lineSplit[0].trim();
if (watchlistName.isBlank()) {
return null... | function | java | 63 |
function generateListOfAllTests(callback) {
mkdirp(TEMPORARY_DIRECTORY, function(err) {
if (err) {
logError(err);
return;
}
glob(TEST_DIRECTORY + '/**/*_test.html', {}, function(er, file_names) {
fs.writeFile(
TEMPORARY_DIRECTORY + '/all_tests.js',
'var _allTests = ' ... | function | javascript | 64 |
def call(
self,
inputs: tf.Tensor,
states: Optional[States] = None,
output_states: bool = True,
) -> Union[tf.Tensor, Tuple[tf.Tensor, States]]:
states = dict(states) if states is not None else {}
num_frames = tf.shape(inputs)[1]
frame_count = tf.cast(states.get(self._frame_count_n... | function | python | 65 |
def save(self, flush=True, **kwargs):
self.new_objects = []
self.changed_objects = []
self.deleted_objects = []
saved_instances = []
for form in self.extra_forms:
if not form.has_changed():
continue
if self.can_delete and self._should_delet... | function | python | 66 |
public class BFileReader {
public final static String CVSID = "@(#) $Id: BFileReader.java 744 2011-07-26 06:29:20Z gfis $";
/** log4j logger (category) */
private Logger log;
/* local copy of the sequence read from the b-file */
private ArrayList<BigInteger> sequence;
/** No-args Constructor
... | class | java | 67 |
def viz(mode, annot_subset, banlist):
print('start')
img_dir = '../InterHand2.6M_5fps_batch0/images'
annot_path = '../InterHand2.6M_5fps_batch0/annotations'
joint_num = 21
root_joint_idx = {'right': 20, 'left': 41}
joint_type = {'right': np.arange(0, joint_num), 'left': np.arange(joint_num, jo... | function | python | 68 |
public class EjbJar30DataLoader extends EjbJarDataLoader{
private static final long serialVersionUID = 1L;
private static final String REQUIRED_MIME_PREFIX_3 = "text/x-dd-ejbjar3.0"; // NOI18N
private static final String REQUIRED_MIME_PREFIX_3_1 = "text/x-dd-ejbjar3.1"; // NOI18N
private static fin... | class | java | 69 |
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
setupEventList();
BottomNavigationView navigation = (BottomNavigationView)
findViewById(R.id.navigation);
navigation.... | function | java | 70 |
long ctslab (cplx *contrast, cplx *k, real *r, real *lr,
real *nr, cplx kbg, long nx, long ny, real delta) {
long i, npx;
real rval;
npx = nx * ny;
#pragma omp parallel for default(shared) private(rval,i)
for (i = 0; i < npx; ++i) {
contrast[i] = k[i] / kbg;
contrast[i] = contrast[i] * contrast[i] - 1;
rval... | function | c | 71 |
public void createGrid(int numRows, int numCols) {
createGrid(new String[numRows][numCols]);
for(int i = 0; i<getRows();i++)
{
for(int j = 0; j<getCols();j++)
{
double choice = Math.random();
if (choice<=percentEmpty) {
... | function | java | 72 |
constructMovieArray (revisedMoviesAvailable, revisedPageOptionNumber) {
const resultArray = []
for (let i = 0; i < revisedMoviesAvailable.length; i++) {
const newObject = {
movie: revisedMoviesAvailable[i],
option: parseFloat(revisedPageOptionNumber[i])
}
resultArray.push(newOb... | function | javascript | 73 |
void ChromeMiniInstaller::UnInstall() {
printf("Verifying if Chrome is installed...\n");
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!CheckRegistryKey(dist->GetVersionKey())) {
printf("Chrome is not installed.\n");
return;
}
printf("\nClosing Chrome processes, if any...\n")... | function | c++ | 74 |
public class BookingEndorsementFilter implements AcceptIfResolver {
@Override
public boolean accept(Element element, Object parentObject) {
Elements endorsementName = element.select("div:nth-child(1) > div:nth-child(1) > div:nth-child(2) > p:nth-child(1)");
return !endorsementName.get(0).text()... | class | java | 75 |
func (s ServiceCommonGeneratorV1) validate() error {
if len(s.Name) == 0 {
return fmt.Errorf("name must be specified")
}
if len(s.Type) == 0 {
return fmt.Errorf("type must be specified")
}
if s.ClusterIP == v1.ClusterIPNone && s.Type != v1.ServiceTypeClusterIP {
return fmt.Errorf("ClusterIP=None can only be ... | function | go | 76 |
private Observable<Event> fileSelected(Path filePath) {
return Observable.just(
Event.of(Event.MARKUP_PROPERTIES, Event.MARKUP_CONTROLLER, FILE_SELECTED, filePath),
Event.of(Event.MARKUP_PROPERTIES, Event.PROPERTY_SELECTOR, CLEAR_SELECTION, null),
Event.of... | function | java | 77 |
private static boolean lockFile(File file)
throws IOException, FileStateException
{
boolean bReturn = true;
RandomAccessFile raf = null;
if (!file.exists())
{
throw new FileNotFoundException("The file " + file.getAbsolutePath() +
... | function | java | 78 |
public static String findFreeCamelContextName(BundleContext context, String prefix, String key, AtomicInteger counter, boolean checkFirst) {
String candidate = null;
boolean clash = false;
do {
try {
clash = false;
if (candidate == null && checkFirst) ... | function | java | 79 |
public class ArrayIndexedPriorityQueue<T> implements ReactionManager<T> {
private static final long serialVersionUID = 8064379974084348391L;
private final TObjectIntMap<Reaction<T>> indexes = new ObjectIntHashMap<>();
private transient FastReadWriteLock rwLock = new FastReadWriteLock();
private fina... | class | java | 80 |
public GameBoard doMove(Move m, int color) throws InvalidMoveException{
if(!isLegal(m,color)){
throw new InvalidMoveException();
}
GameBoard temp = new GameBoard();
for(int j = 0; j <= 7; j++){
for (int i = 0; i<= 7; i++){
temp.board[j][i] = board[... | function | java | 81 |
func (broker *TaskBroker) PublishTasks(queueName string, settings []models.TaskSetting) (err error) {
logrus.Info(fmt.Sprintf("To schedule %d tests.", len(settings)))
_, ch, err := broker.QueueDeclare(queueName)
if err != nil {
return fmt.Errorf("fail to decalre queue: %s", err.Error())
}
logrus.Info(fmt.Sprintf... | function | go | 82 |
def add(self, spec, method, level=0, authn_authority="", reference=None):
if spec.authn_context_class_ref:
key = spec.authn_context_class_ref.text
_info = {
"class_ref": key,
"method": method,
"level": level,
"authn_auth": a... | function | python | 83 |
function mockSDKApi(apiPath, value) {
var __toString = Object.prototype.toString;
module(function ($provide) {
var pathAssign = function (obj, pathStr, value) {
var paths = pathStr.split(/\./);
if (paths.length === 0) {
return;
}
var path = paths.shift();
if (paths.length =... | function | javascript | 84 |
@Slf4j
public class ContentJobWriteInterceptor extends ContentWriteInterceptorBase {
protected static final String EXPORT_STORAGE_URL = "export-storage-url";
protected static final String LOCAL_SETTINGS = "localSettings";
protected static final String JOB_TYPE = "job-type";
protected static final Strin... | class | java | 85 |
def step_full(self) -> None:
c, c_test = 0, 0
losses, losses_test = 0, 0
if self.compute_accuracy:
acc, acc_test = 0, 0
for features, targets in self.train_loader:
if self.augment_fn is not None:
features, targets = self.augment_fn(
... | function | python | 86 |
hciStatus_t HCI_EXT_AdvEventNoticeCmd(uint8 taskID, uint16 taskEvent)
{
uint8_t taskId = ICall_getLocalMsgEntityId(ICALL_SERVICE_CLASS_BLE_MSG,
taskID);
return hciSendParamsCmd(HCI_EXT_ADV_EVENT_NOTICE, taskId,
taskEvent, 0, matchHciExtAdvEventN... | function | c | 87 |
void
Draw::Camera::update (const float ,
const float elapsedTime,
const bool simulationPaused)
{
const AbstractVehicle& v = *vehicleToTrack;
const bool noVehicle = vehicleToTrack == NULL;
Vec3 newPosition = position();
Vec3 newTarget = target;
Vec3 ne... | function | c++ | 88 |
private static void selection(Cell[] arr, int length, int k) {
if (QUICKSELECT_BASED_PARTITION) {
shuffle(arr, length);
quickselect(arr, 0, length - 1, k - 1);
} else {
Arrays.sort(arr, 0, length, Comparator.comparing(c -> c.dist));
}
} | function | java | 89 |
int bluez_subscribe_signals(void) {
g_dbus_connection_signal_subscribe(config.dbus, BLUEZ_SERVICE,
DBUS_IFACE_OBJECT_MANAGER, "InterfacesAdded", NULL, NULL,
G_DBUS_SIGNAL_FLAGS_NONE, bluez_signal_interfaces_added, NULL, NULL);
g_dbus_connection_signal_subscribe(config.dbus, BLUEZ_SERVICE,
DBUS_IFACE_OBJECT_M... | function | c | 90 |
int
suser(kauth_cred_t cred, u_short *acflag)
{
#if DIAGNOSTIC
if (!IS_VALID_CRED(cred))
panic("suser");
#endif
if (kauth_cred_getuid(cred) == 0) {
if (acflag)
*acflag |= ASU;
return (0);
}
return (EPERM);
} | function | c | 91 |
func FilterPublicAddress(ips []string) (string, bool) {
for _, address := range ips {
address = strings.TrimSpace(address)
ipAddress := net.ParseIP(address)
if ipAddress == nil {
continue
}
var isPrivate bool
for i := range cidrs {
if cidrs[i].Contains(ipAddress) {
isPrivate = true
}
}
if ... | function | go | 92 |
private Map<String, Integer> processLast(Tree last) {
Map<String, Integer> result = new HashMap<>();
if (last.getChildCount() == 1) {
int numberOfLast = Integer.valueOf(last.getChild(0).getText());
result.put("lastFrom", numberOfLast);
result.put("howMany", numberOfL... | function | java | 93 |
public class MultipleRpcCommand extends BaseRpcInvokingCommand {
public static final byte COMMAND_ID = 2;
private static final Log log = LogFactory.getLog(MultipleRpcCommand.class);
private static final boolean trace = log.isTraceEnabled();
private ReplicableCommand[] commands;
private MultipleRpcCom... | class | java | 94 |
def weather_fit(data):
data = np.array(data)
transition_counts = np.zeros((3, 3))
emission_counts = np.zeros((3, 2))
for index, datapoint in enumerate(data):
if index != len(data)-1:
transition_counts[data[index][0], data[index+1][0]] += 1
emission_counts[data[index][0], data... | function | python | 95 |
public void read(EquipmentModelList emList)
throws DatabaseException, SQLException
{
Logger.instance().log(Logger.E_DEBUG1,"Reading EquipmentModels...");
_emList = emList;
Statement stmt = createStatement();
String q = "SELECT id, name, company, model, description, equipmentType " +
"FROM Equip... | function | java | 96 |
void* Partitions::FastMalloc(size_t n, const char* type_name) {
#if !BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
return FastMallocPartition()->Alloc(n, type_name);
#else
return malloc(n);
#endif
} | function | c++ | 97 |
class EmailAddress extends SystemObject {
static fromJson(text) {
return new EmailAddress(text);
}
constructor(text) {
super();
Preconditions.requireText(text, "text");
this.textValue = text;
}
text() {
return this.textValue;
}
toJson() {
... | class | javascript | 98 |
public void killAlgorithm() {
killThread.set(true);
algorithmThread.interrupt();
if(isPaused.get()) {
threadKillCleanup();
}
} | function | java | 99 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.