code stringlengths 0 30.8k | source stringclasses 6
values | language stringclasses 9
values | __index_level_0__ int64 0 100k |
|---|---|---|---|
public new bool Equals(object obj)
{
var p = obj as WindowOpenMessage;
if (p == null)
{
return false;
}
return ((WindowOpenMessage)obj).WindowType == WindowType;
} | function | c# | 200 |
@Startup
@Singleton
@SuppressWarnings("unused")
public class DatabaseInitializer {
private static final int MAX_AMOUNT_OF_PERSONS_TO_GENERATE = 5;
@PersistenceContext
private EntityManager entityManager;
@PostConstruct
public void initializeDatabase() {
generatePersons(MAX_AMOUNT_OF_PERSON... | class | java | 201 |
private VOSubscription createAndSubscribeToServiceWithParameter(
String paraValue) throws Exception {
technicalServiceWithParameter = createTechnicalService("tp1");
List<VOParameter> params = createParametersForTechnicalService(
technicalServiceWithParameter, paraValue);
... | function | java | 202 |
public class ModelArrows : GeometricElement
{
public IList<(Vector3 origin, Vector3 direction, double magnitude, Color? color)> Vectors { get; set; }
public bool ArrowAtStart { get; set; }
public bool ArrowAtEnd { get; set; }
public double ArrowAngle { get; set; }
[JsonConstr... | class | c# | 203 |
class COMPSsConfiguration:
"""
Class containing the configuration options provided by the COMPSs test configuration file
:attribute user: User executing the tests
+ type: String
:attribute target_base_dir: Path to store the tests execution sandbox
+ type: String
:attribute compss_ba... | class | python | 204 |
int
debug_call_with_fault_handler(jmp_buf jumpBuffer, void (*function)(void*),
void* parameter)
{
cpu_ent* cpu = gCPU + sDebuggerOnCPU;
addr_t oldFaultHandler = cpu->fault_handler;
addr_t oldFaultHandlerStackPointer = cpu->fault_handler_stack_pointer;
int result = setjmp(jumpBuffer);
if (result == 0) {
arch_deb... | function | c++ | 205 |
public static void loadImageAssets(ImageCollection imageCollection,
String fileName) throws Exception {
try (ZipFile zipFile = new ZipFile(fileName)) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
ZipEntry entry;
while (entries.hasMoreElements()) {... | function | java | 206 |
public static BlangFile Parse(string path)
{
var blangFile = new BlangFile();
using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (var binaryReader = new BinaryReader(fileStream))
{
var blan... | function | c# | 207 |
fn name_to_properties(name: Name) -> (Vec<String>, Option<TypeQualifier>) {
let (bare_name, opt_q) = name.into_inner();
let raw_name: String = bare_name.into();
let raw_name_copy = raw_name.clone();
let split = raw_name_copy.split('.');
let mut parts: Vec<String> = vec![];
... | function | rust | 208 |
public virtual void ApplyTo(RSTR response)
{
if (response == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("response");
}
if (tokenType != null)
{
response.TokenType = tokenType;
}
... | function | c# | 209 |
public boolean execute(String command) {
String[] args = command.trim().split("[ ]{1,}");
if (args[0].isEmpty()) {
return true;
}
Log.log(Shell.class, "Invocation request: " + Arrays.toString(args));
Class<?> commandClass = classesMap.get(args[0]);
if (command... | function | java | 210 |
public void updateGame(Seed theSeed, int rowSelected, int colSelected) {
if (hasWon(theSeed, rowSelected, colSelected)) {
currentState = (theSeed == Seed.CROSS) ? GameState.CROSS_WON : GameState.NOUGHT_WON;
} else if (isDraw()) {
currentState = GameState.DRAW;
}
} | function | java | 211 |
public static ResultSet varArgsFunctionTable(int... values) throws SQLException {
if (values.length != 6) {
throw new SQLException("Unexpected argument count");
}
SimpleResultSet result = new SimpleResultSet();
result.addColumn("A", Types.INTEGER, 0, 0);
for (int valu... | function | java | 212 |
[Guid(Guids.ColorCoderOptionPackage)]
[DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\14.0")]
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideOptionPage(typeof(ChangeColorOptionGrid), "ColorCoder", "Colors", 1000, 1001, true)]
[ProvideOptionPage(typ... | class | c# | 213 |
public static String serialize(World w, Scene s, ActionCallback cb) {
String id = null;
if (cb == null)
return null;
id = serialize(cb, w.getUIActors());
if (id != null)
return id;
id = serialize(cb, w.getInventory());
if (id != null)
return id;
if (w.getInkManager() != null) {
id = serialize(... | function | java | 214 |
@Test
void isValidQuantityGreaterMaxQuantityOtherListings() throws Exception {
listing = new Listing(
inventoryItem,
15,
99.99,
"More info",
LocalDateTime.now(),
LocalDateTime.of(2022, 1,1, 0, 0)
);
... | function | java | 215 |
def create_snapshot_if_not_exist(volume_id, tags, time_limit):
try:
snap = check_snapshot_exist(volume_id, time_limit)
if snap:
logger.info("An existing snapshot was found: {0}" .format(snap))
return snap
logger.info("Launch of the snapshot creation process")
... | function | python | 216 |
def warp_image(image, warp_matrix, source_coords = None, dest_coords = None,
inverse = False, lines = False):
if inverse:
flags = cv2.WARP_INVERSE_MAP
else:
flags = cv2.INTER_LINEAR
img_size = (image.shape[1], image.shape[0])
warped = cv2.warpPerspective(image, M_warp, img_size, fl... | function | python | 217 |
static bool parseIncoming(HttpConn *conn, HttpPacket *packet)
{
HttpRx *rx;
ssize len;
char *start, *end;
if (packet == NULL) {
return 0;
}
if (mprShouldDenyNewRequests()) {
httpError(conn, HTTP_ABORT | HTTP_CODE_NOT_ACCEPTABLE, "Server terminating");
re... | function | c | 218 |
public class Utils {
/**
* Turn a string address or host name (IPV4, IPV6, host.domain.tld) into an InetAddress
* @param _addr
* @return the internet address IPV4 of the IP address, or host name in _addr
*/
public static InetAddress parseInetAddress(String _addr)
throws UnknownHo... | class | java | 219 |
def run(self, name: str = None):
if self.raise_if_missing and name not in os.environ:
raise ValueError("Environment variable not set: {}".format(name))
value = os.getenv(name)
if value is not None and self.cast is not None:
value = self.cast(value)
return value | function | python | 220 |
internal static BaseMock GetSolutionBuildManagerInstance()
{
if(solutionBuildManager == null)
{
solutionBuildManager = new GenericMockFactory("SolutionBuildManager", new Type[] { typeof(IVsSolutionBuildManager2), typeof(IVsSolutionBuildManager3) });
}
... | function | c# | 221 |
def _reg_std(self, result, rank, demeaned_df):
if (len(self.clusters) == 0) & (self.robust is False):
std_error = result.bse * np.sqrt((result.nobs - len(self.covariants)) / (result.nobs - len(self.covariants)
- ran... | function | python | 222 |
def live_migrate_instance(self, instance_id, dest_hostname,
block_migration=False, retry=120):
LOG.debug("Trying a live migrate of instance %s to host '%s'" % (
instance_id, dest_hostname))
instance = self.find_instance(instance_id)
if not instance:
... | function | python | 223 |
function mainDogAnim (e) {
if(e.which!=1)return;
if($(the_dog).is(':animated')) { _no=true; return; }
$(the_dog).animate({
width:520,
height:350,
top:"+=10px",
left:"+=6px"
},33,null);
} | function | javascript | 224 |
public bool IliasLogin(string sUser, string sPassword)
{
if (bLoggedIn)
{
return true;
}
else
{
if (sUser != "" && sPassword != "")
{
config.SetUser(sUser);
try
... | function | c# | 225 |
def first_or_default(behaviors, request):
address = str(request.questions[0].qname)
if behaviors == None or len(behaviors) == 0:
return Behavior(address)
for behavior in behaviors:
if (behavior.handles(address)):
return behavior
return Behavior(address) | function | python | 226 |
@Data
@JsonInclude(value = JsonInclude.Include.NON_EMPTY, content = JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class MscsConfigData {
/**
* The type of connectivity that is requested to be provided to the virtualized networks in the NFVI-PoP and characterizes the connectivi... | class | java | 227 |
func rowsToTest(rows *sql.Rows) (*Test, error) {
var test *Test
tests, err := rowsToTests(rows)
if len(tests) >= 1 {
test = tests[0]
}
return test, err
} | function | go | 228 |
async createUpdateTierConfigRequest(configId, params) {
return this.createTierConfigRequest({
configuration: {
id: configId,
},
params,
});
} | function | javascript | 229 |
public unsafe int CompareOrdinal(string s)
{
fixed (cef_string_utf16_t* self = &Base)
{
return CompareOrdinal((cef_string_t*)self, s);
}
} | function | c# | 230 |
static int
check_authkeys_file(struct ssh *ssh, struct passwd *pw, FILE *f,
char *file, struct sshkey *key, struct sshauthopt **authoptsp)
{
char *cp, *line = NULL, loc[256];
size_t linesize = 0;
int found_key = 0;
u_long linenum = 0;
if (authoptsp != NULL)
*authoptsp = NULL;
while (getline(&line, &linesize... | function | c | 231 |
private
class UpdateParamGroupsOpen
implements ActionListener
{
public
UpdateParamGroupsOpen
(
String name,
JDrawer drawer
)
{
pName = name;
pDrawer = drawer;
}
/**
* Invoked when an action occurs.
*/
public void
actionPerformed
(... | class | java | 232 |
private void registerDynamicPTsWithStream(
CallPeerMediaHandler<?> callPeerMediaHandler,
MediaStream stream)
{
DynamicPayloadTypeRegistry dynamicPayloadTypes
= callPeerMediaHandler.getDynamicPayloadTypes();
StringBuffer dbgMessage = new StringBuffer("Dynamic P... | function | java | 233 |
private void renderEpisodes(final TvShowViewModel tvShow) {
List<Renderer<EpisodeViewModel>> episodeRenderers =
new LinkedList<Renderer<EpisodeViewModel>>();
episodeRenderers.add(new EpisodeRenderer());
EpisodeRendererBuilder episodeRendererBuilder = new EpisodeRendererBuilder(episodeRenderers);
... | function | java | 234 |
float4 LightSample(GBufferValues sample, VSOutput geo, SystemInputs sys)
{
float3 directionToEye = 0.0.xxx;
#if (OUTPUT_WORLD_VIEW_VECTOR==1)
directionToEye = normalize(geo.worldViewVector);
#endif
float4 result = float4(
ResolveLitColor(
sample, directionToEye, GetWorldPosition(geo),
LightScreenDest_Crea... | function | c | 235 |
public abstract class PluginEvent {
/**
* Name of event source when plugin event is passed to
* another tool as cross-tool event.
*/
public static final String EXTERNAL_SOURCE_NAME = "External Tool";
private String eventName;
private String sourceName;
private PluginEvent triggerEvent;
/**
* Returns t... | class | java | 236 |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Method)]
public class ManagedNameAttribute : Attribute
{
string name;
public string Name
{
get { return name ; }
}
public ... | class | c# | 237 |
public override string ToString()
{
if (string.IsNullOrWhiteSpace(Namespace))
{
return ClassName.ToString();
}
return $"{Namespace}.{ClassName}";
} | function | c# | 238 |
public bool HasDuplicateRings()
{
for (IEnumerator nodeIt = nodeGraph.NodeIterator();
nodeIt.MoveNext(); )
{
RelateNode node = (RelateNode) nodeIt.Current;
for (IEnumerator i = node.Edges.Iterator(); i.MoveNext(); )
{
EdgeEndBundle eeb = (EdgeEndBundle) i.Current;
... | function | c# | 239 |
public long skip(long n) throws IOException {
if (vbits == 0) {
return in.skip(n);
} else {
int b = (vbits + 7) / 8;
in.skip(n - b);
int vbits = this.vbits;
resetBuffer();
fillBuffer(vbits);
return n;
}
} | function | java | 240 |
def optimize(self, bounds, tol=1.0e-6, verbose=False):
if len(bounds) != self.ndims + 1:
raise ValueError("Number of bounds (min, max) pairs not equal to N dimensions + 1")
self.normal_bounds = self._convert_bounds(bounds)
result = differential_evolution(lambda *args: -self._lnpost(*... | function | python | 241 |
def dispersion(x, y, bins, method):
d, k = [np.zeros(len(bins)-1) for i in range(2)]
for i in range(len(bins)-1):
m = (bins[i] < x) * (x < bins[i+1])
if method == "std":
d[i] = np.std(y[m])
if method == "mad":
d[i] = 1.5*np.median(np.abs(y[m] - np.median(y[m])))
... | function | python | 242 |
public class RuleMaintenanceActionRequestCodeValuesFinder extends ActionRequestCodeValuesFinder {
/**
* @see org.kuali.rice.krad.keyvalues.KeyValuesFinder#getKeyValues()
*/
@Override
public List<KeyValue> getKeyValues() {
final List<KeyValue> actionRequestCodes = new ArrayList<KeyValue>();
// Acquir... | class | java | 243 |
def sierpinski_triangle(order, length, upper_left_x, upper_left_y):
pause(10)
line1 = GLine(upper_left_x, upper_left_y, upper_left_x+length, upper_left_y)
line2 = GLine(upper_left_x, upper_left_y, upper_left_x+length*0.5, upper_left_y+length*0.866)
line3 = GLine(upper_left_x+length, upper_left_y, upper_left_x+lengt... | function | python | 244 |
pub unsafe fn convert<X>(mut self) -> TwoUnorderedVecs<X> {
assert_eq!(core::mem::size_of::<X>(), core::mem::size_of::<T>());
assert_eq!(core::mem::align_of::<X>(), core::mem::align_of::<T>());
let ptr = self.inner.as_mut_ptr();
let len = self.inner.len();
let cap = self.inner.ca... | function | rust | 245 |
def _check_finished(self, pr, build_number):
pr_number = str(pr.number)
log.info('CI for PR %s: FINISHED', pr_number)
project_name_full = self._ci_job_name + '/PR-' + pr_number
build_output = self._jenkins.get_build_console_output(project_name_full, build_number)
if _CI_BUILD_FAI... | function | python | 246 |
def _create_resource(
cls,
client: utils.MetadataClientWithOverride,
parent: str,
schema_title: str,
state: gca_execution.Execution.State = gca_execution.Execution.State.RUNNING,
resource_id: Optional[str] = None,
display_name: Optional[str] = None,
schema... | function | python | 247 |
Node *NodeBody_new(NodeArray *node_array, int tokens) {
Node *node = (Node *)malloc(sizeof(Node));
node->type = NodeType_BODY;
node->body = node_array;
node->body_tokens = tokens;
return node;
} | function | c | 248 |
func (s *Server) JWTInterceptor() grpc.UnaryServerInterceptor {
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (interface{}, error) {
authLock.RLock()
shouldAuthenticate := !noAuthPaths[info.FullMethod]
authLock.RUnlock()
if shouldAuthentica... | function | go | 249 |
private boolean hasLangPref() {
ContentResolver resolver = getContentResolver();
String language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
if ((language == null) || (language.length() < 1)) {
return false;
}
String country = Settings.Secure.getString(re... | function | java | 250 |
_setVisibilityObjects(layerId, objectIds, visibility = false) {
return new Ember.RSVP.Promise((resolve, reject) => {
if (Ember.isArray(objectIds)) {
let [layer, leafletObject] = this._getModelLeafletObject(layerId);
if (Ember.isNone(layer)) {
return reject(`Layer '${layerId}' not fou... | function | javascript | 251 |
public abstract class EffectMatricesEffect : Effect, IEffectMatrices
{
#region Private Fields
private Matrix _projection;
private Matrix _view;
private Matrix _world;
private Boolean _dirty;
private EffectParameter _worldViewProjectionParam;
#endregion
... | class | c# | 252 |
def _validate_permissions(self, block, prev_state_root):
block_header = BlockHeader()
block_header.ParseFromString(block.header)
if block_header.block_num != 0:
for batch in block.batches:
if not self._permission_verifier.is_batch_signer_authorized(
... | function | python | 253 |
def command(self,
command,
timeout=60,
expected_prompt=None):
status = True
try:
if len(command) + 50 > self.command_width:
logging.debug(u'Resizing pty!')
self.command_width = len(command) + 50
s... | function | python | 254 |
public class MergeIntervals {
public static List<Interval> merge(List<Interval> intervals) {
List<Interval> mergedIntervals = new LinkedList<>();
if (intervals.size() < 2) {
return intervals;
}
intervals.sort(Comparator.comparingInt(a -> a.start));
Iterator<In... | class | java | 255 |
public class PartCover:
ToolTask
{
protected override string GenerateFullPathToTool()
{
string versionValueName=null;
for (int i=0; i<_PartCoverComponentRegValues.Length; ++i)
if (_PartCoverComponentRegValues[i, 0]==ToolsVersion)
{
... | class | c# | 256 |
[Ignore("obsolete work, mark for removal")]
[Obsolete("marked for removal")]
[TestMethod]
public void PowerSpectrumDensityTest()
{
var inputPath = @"C:\Users\kholghim\Mahnoosh\Liz\TrainSet\";
var resultPsdPath = @"C:\Users\kholghim\Mahnoosh\Liz\PowerSpectrumDensit... | function | c# | 257 |
func (c *Memory) Get(ctx context.Context, key string) ([]byte, time.Duration, error) {
c.mx.RLock()
v, ok := c.values[key]
c.mx.RUnlock()
if !ok {
return nil, 0, fmt.Errorf("key %q: %w", key, ErrNotFound)
}
var ttl time.Duration
if !v.expiresAt.IsZero() {
ttl = time.Until(v.expiresAt)
if ttl <= 0 {
c.fo... | function | go | 258 |
def is_containers_started(self, pod_id, containers_counter,
namespace=DEFAULT_NAMESPACE):
events_list = self.client_core.list_namespaced_event(
namespace=namespace, field_selector=f"involvedObject.uid=={pod_id}")
for event in events_list.items:
if AU... | function | python | 259 |
bool
CDs::reinsert(CDo *odesc, const BBox *nBB)
{
if (!odesc)
return (false);
if (odesc->type() == CDINSTANCE)
setInstNumValid(false);
CDtree *l = db_find_layer_head(odesc->ldesc());
if (l) {
if (l->is_deferred()) {
if (nBB && odesc->oBB() != *nBB)
ode... | function | c++ | 260 |
class OSCRecordSigReader:
"""Reads a recording made by OSCRecord as a sig tree with the same API as the OSCTosig class.
Reads at a steady 24 fps by default but supports external frame advance triggers."""
def __init__(self, foldername, framerate=24, trigsource=None, buffersize=None):
buffersize = fr... | class | python | 261 |
public static void ensureHasBackpackLayer(Class<? extends EntityLivingBase> entityClass) {
if (!_hasLayerChecked.add(entityClass)) return;
RenderManager manager = Minecraft.getMinecraft().getRenderManager();
Render<?> render = manager.getEntityClassRenderObject(entityClass);
if (!(render instanceof RenderLiving... | function | java | 262 |
private final void checkStateBeforeMutator() {
if (this.closed.get()) {
throw new IllegalStateException("Already closed");
}
if (this.started.get()) {
throw new IllegalStateException("Already started");
}
} | function | java | 263 |
public abstract class AbstractServlet extends HttpServlet {
/**
* Logic layer object - validator.
*/
protected static final Validator<User> VALIDATOR = DatabaseValidator.getInstance();
/**
* Logic layer object - servlet actions dispatch.
*/
protected static final ActionsDispatch DISP... | class | java | 264 |
protected final MethodNode createMethod(int maxLocals, int maxStack) {
MethodNode method = this.info.getMethod();
MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name,
method.desc, null, null);
accessor... | function | java | 265 |
public class CreateVariables extends AirsJavaDatabaseApp implements Runnable {
private enum VariableCounters {
NORATINGS, NOTRAILINGRATINGS, PLAYERS, TOURNAMENTS, GAMES, NOTRAILING
}
private static final Log LOGGER = LogFactory.getLog(CreateVariables.class);
private static boolean f_incremental;
priva... | class | java | 266 |
public async Task<bool> EditCommentAsync(int id, string message)
{
IdValidator idValidator = new IdValidator();
idValidator.ValidateAndThrow(id);
CommentMessageValidator messageValidator = new CommentMessageValidator();
messageValidator.ValidateAndThrow(message);
... | function | c# | 267 |
def segment_synchronization(pos_start, pos_end, vel_start, vel_end,
abs_max_pos, abs_max_vel, abs_max_acc, abs_max_jrk):
rospy.logdebug(">> pos_start:\n{}".format(pos_start))
rospy.logdebug(">> pos_end:\n{}".format(pos_end))
rospy.logdebug(">> vel_start:\n{}".format(vel_start))
rospy.logde... | function | python | 268 |
class ReceivedPing
{
public:
ReceivedPing()
{
throw std::logic_error{"ReceivedPing can't be default-constructed"};
}
ReceivedPing(QUdpSocket *pServerSocket, QHostAddress remoteAddress,
quint16 remotePort,
QSharedPointer<ServerLocation> pLocation)
: _pSer... | class | c++ | 269 |
private ScheduledFuture<?> handleInstantNull() {
LOGGER.debug("Handling Instant null");
ScheduledFuture<?> future = getDefaultFuture();
taskState = true;
if (taskName != null && taskLeaderElectionServiceMap.get(taskName) != null) {
taskLeaderElectionServiceMap.get(taskName).removeListene... | function | java | 270 |
def random_starts_goals_in_subsquare(n, width=10, sub_width=10):
assert n*2 <= sub_width*sub_width, f"can't place n distincts starts and goals in a sub square of size {sub_width}"
(top_x, top_y) = (random.randrange(0, width-sub_width+1), random.randrange(0, width-sub_width+1))
_start_bounds = ((top_x, top_x... | function | python | 271 |
function drupalgap_views_render_rows(variables, results, root, child, open_row, close_row) {
try {
var html = '';
for (var count in results[root]) {
if (!results[root].hasOwnProperty(count)) { continue; }
var object = results[root][count];
var row = object[child];
row._position = count... | function | javascript | 272 |
public static Modifier makeTimedModifier(String id, Modifier template,
Turn start) {
Modifier modifier = new Modifier(id, template);
float inc = template.getIncrement();
int duration = template.getDuration();
modifier.setTemporary(template.isT... | function | java | 273 |
public void save (FileHandle file, PixmapPacker packer, SaveParameters parameters) throws IOException {
Writer writer = file.writer(false);
int index = 0;
for (Page page : packer.pages) {
if (page.rects.size > 0) {
FileHandle pageFile = file.sibling(file.nameWithoutExtension() + "_" + (++index) + parameter... | function | java | 274 |
def send_signal(process_id, signal_to_send):
if process_id:
signal_name = signal_to_send.name
logging.info('Requested to send {} to process (id: {})'.format(signal_name, process_id))
if _send_signal_to_process_tree(process_id, signal_to_send):
logging.info('Successfully sent {} t... | function | python | 275 |
impl<L, R> Sender for Either<L, R>
where
L: 'static + Sender,
R: 'static + Sender,
{
type Output = Either<L::Output, R::Output>;
type Scheduler = ImmediateScheduler;
fn start<Recv>(self, receiver: Recv)
where
Recv: 'static + Send + Receiver<Input = Self::Output>,
{
match sel... | class | rust | 276 |
static bool checkFieldArrayStore1nr(RegType instrType, RegType targetType)
{
if (instrType == targetType)
return true;
if ((instrType == kRegTypeInteger && targetType == kRegTypeFloat) ||
(instrType == kRegTypeFloat && targetType == kRegTypeInteger))
{
return true;
}
... | function | c | 277 |
@Slf4j
public class ProfilerMiddleware implements Middleware {
/**
* Report execution of the said job
*
* @param job the running job
* @param executionTime execution time
*/
protected void report(Job job, Duration executionTime) {
log.info(
"Queue: {}, Job: {} took {}Ms",
job.ge... | class | java | 278 |
public CourseAssistant retrieveCAById(int caID, int termForCA)
throws FileNotFoundException, NullPointerException, IOException, ParseException {
String fileToRetrieve = "SID" + caID + ".json";
CourseAssistant foundca = new CourseAssistant(caID);
boolean fileExists = false;
if (taschdCheck()) {
if (taschdT... | function | java | 279 |
public final class Sequence<T> implements Generatable<T>
{
private final Generator<T> mInitialValue;
private final Function<? super T, ? extends T> mFunction;
public Sequence(Generator<T> initialValue, Function<? super T, ? extends T> function)
{
mInitialValue = initialValue;
mFunction... | class | java | 280 |
def one_d_extract(self, data=[], file='', badpix=[], lenslet_profile='sim', rnoise=3.0):
if len(data)==0:
if len(file)==0:
print("ERROR: Must input data or file")
else:
data = pyfits.getdata(file).T
ny = self.x_map.shape[1]
nm = self.x_map.... | function | python | 281 |
@Entity
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Table(name="SYSTEM_CODES", uniqueConstraints = @UniqueConstraint(columnNames = "KEY_"))
public class SystemCodes extends BaseProtectedEntity
implements Serializable, Searchable, Auditable, Sortable {
private static final long serialVersionUID = -41... | class | java | 282 |
static void synthesizeTrivialGetter(FuncDecl *getter,
AbstractStorageDecl *storage,
TypeChecker &TC) {
auto &ctx = TC.Context;
Expr *result = createPropertyLoadOrCallSuperclassGetter(getter, storage, TC);
ASTNode returnStmt = new (ctx) Return... | function | c++ | 283 |
def Search(self, cls_type, list_id=-1):
options = {
"pre": self.prenotation,
"post": self.postnotation,
"wrap": self.wrap_notation}
if list_id in options:
for item in options[list_id]:
if type(item) == cls_type:
return i... | function | python | 284 |
func (s routeStrategy) allocateHost(ctx context.Context, route *routeapi.Route) field.ErrorList {
hostSet := len(route.Spec.Host) > 0
certSet := route.Spec.TLS != nil && (len(route.Spec.TLS.CACertificate) > 0 || len(route.Spec.TLS.Certificate) > 0 || len(route.Spec.TLS.DestinationCACertificate) > 0 || len(route.Spec.... | function | go | 285 |
public abstract class AbstractCommonAttributeInstance {
private final Long abstractFileObjectId;
private final String caseName;
private final String dataSource;
// Reference to the AbstractFile instance in the current case
// that matched on one of the common properties.
protected AbstractFile... | class | java | 286 |
public class ReadOneOrder {
public static void main(String[] args) {
try {
System.out.println("Reading order from server via rest service:");
Order order = fetchById("42");
if (order!=null) {
System.out.println(order);
}
}
catc... | class | java | 287 |
def amplicon_range(self, popt=None, method='erf'):
if popt is None or np.isnan(popt[0]):
if self.success:
popt = self.popt[method]
if popt is not None:
shift = popt[-1]
if method == 'erf':
dist = scipy.stats.norm(loc=popt[2], scale=popt... | function | python | 288 |
static void insertModuleInit() {
forv_Vec(ModuleSymbol, mod, allModules) {
SET_LINENO(mod);
mod->initFn = new FnSymbol(astr("chpl__init_", mod->name));
mod->initFn->retType = dtVoid;
mod->initFn->addFlag(FLAG_MODULE_INIT);
mod->initFn->addFlag(FLAG_INSERT_LINE_FILE_INFO);
move module... | function | c++ | 289 |
func (c *Client) CreateDemoWAFRules(stack *Stack, site *Site) error {
reqBody := bytes.NewBuffer([]byte(`{
"name": "block access to blockme",
"description": "A simple path block to demo WAF capabilities",
"conditions": [
{
"url": {
"url": "/blockme",
"exactMatch": true
}
}
]... | function | go | 290 |
void neoPointDetection(signed char* pointArr, int size){
if (size % 2 == 0) {
int numberOfPoints = (int)(size / 2);
strip.clear();
for (int i = 0; i < numberOfPoints; i++) {
signed char xPos = pointArr[(i * 2)];
signed char yPos = pointArr[(i * 2) + 1];
fl... | function | c++ | 291 |
static int
dc_resume(device_t dev)
{
struct dc_softc *sc;
struct ifnet *ifp;
int s;
s = splimp();
sc = device_get_softc(dev);
ifp = &sc->arpcom.ac_if;
if (ifp->if_flags & IFF_UP)
dc_init(sc);
sc->suspended = 0;
splx(s);
return (0);
} | function | c | 292 |
def _train_epoch(self, data_batches):
def compute_epoch_average(vals, n):
weights = np.true_divide(n, np.sum(n))
avg = np.dot(weights, vals)
return avg
n_batches = len(data_batches)
batch_losses = np.zeros(n_batches)
batch_grad_norms = np.zeros(n_batch... | function | python | 293 |
protected Specification<ProductVersion> createSpecification(ProductVersionCriteria criteria) {
Specification<ProductVersion> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecific... | function | java | 294 |
public class ConfigurationItem
{
private const string FILE_EXTENSION = ".config";
private string folderPath = "";
private string name = "";
private readonly EventLog.EventLog eventLog = null;
private readonly bool readOnly = true;
public string FilePath
{
... | class | c# | 295 |
func Make(peers []*labrpc.ClientEnd, me int,
persister *Persister, applyCh chan ApplyMsg) *Raft {
rf := &Raft{}
rf.peers = peers
rf.persister = persister
rf.me = me
rf.Log = []Entry{Entry{}}
rf.CurrentTerm = 0
rf.ElectionTimeout = time.Duration(RandomInt(150, 300)) * time.Millisecond
rf.Role = "follower"
rf.V... | function | go | 296 |
static
seal_err_t
stop_then_clean_queue(seal_src_t* src)
{
seal_err_t err;
if ((err = change_state(src, alSourceStop)) != SEAL_OK)
return err;
return clean_queue(src);
} | function | c | 297 |
internal async static Task<string> ExecInPodAsync(IKubernetes ops, V1Pod pod, string @namespace, string[] commands)
{
var webSockTask = ops.WebSocketNamespacedPodExecAsync(pod.Metadata.Name, @namespace, commands, pod.Spec.Containers[0].Name,
stderr: true, stdin: false, stdout: true, ... | function | c# | 298 |
public async Task StartAsync(CancellationToken cancellationToken)
{
_cts?.Cancel();
await _syncTask;
_cts?.Dispose();
_cts = new CancellationTokenSource();
_syncTask = LoopSyncAsync(_cts.Token);
} | function | c# | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.