code
stringlengths 0
30.8k
| source
stringclasses 6
values | language
stringclasses 9
values | __index_level_0__
int64 0
100k
|
---|---|---|---|
def update(adapter, host_wrapper, instance, entry=None, name=None):
if not entry:
entry = get_instance_wrapper(adapter, instance)
lpar_b = VMBuilder(host_wrapper, adapter, cur_lpar_w=entry).lpar_builder(
instance)
lpar_b.rebuild(entry)
if name:
entry.name = pvm_util.sanitize_partition_name_for_api(name)
return entry.update()
|
function
|
python
| 700 |
func (m *Macaroon) UnmarshalJSON(data []byte) error {
var m1 macaroonJSON
if err := json.Unmarshal(data, &m1); err != nil {
return errgo.Mask(err)
}
if m1.Macaroon == nil {
return m.unmarshalJSONOldFormat(data)
}
if m1.Version < Version3 || m1.Version > LatestVersion {
return errgo.Newf("unexpected bakery macaroon version; got %d want %d", m1.Version, Version3)
}
if got, want := m1.Macaroon.Version(), MacaroonVersion(m1.Version); got != want {
return errgo.Newf("underlying macaroon has inconsistent version; got %d want %d", got, want)
}
caveatData := make(map[string][]byte)
for id64, data64 := range m1.CaveatData {
id, err := macaroon.Base64Decode([]byte(id64))
if err != nil {
return errgo.Notef(err, "cannot decode caveat id")
}
data, err := macaroon.Base64Decode([]byte(data64))
if err != nil {
return errgo.Notef(err, "cannot decode caveat")
}
caveatData[string(id)] = data
}
m.caveatData = caveatData
m.m = m1.Macaroon
m.namespace = m1.Namespace
m.version = m1.Version
return nil
}
|
function
|
go
| 701 |
public class EmailPropertiesFile extends AbstractPropertiesFile {
private static final long serialVersionUID = 12947850247524578L;
/**
* To file "{@link ConfigurationDirectory}/email.properties"
*
* @param confdir An {@link ConfigurationDirectory} representing the conf directory.
*/
@Inject
public EmailPropertiesFile(ConfigurationDirectory confdir) {
super(confdir, "email.properties");
}
}
|
class
|
java
| 702 |
public class NavigationLoader
extends GenericLoader<Navigation>
{
/** The single instance of this class. */
private static NavigationLoader instance = new NavigationLoader();
/**
* These ctor's are private to force clients to use getInstance()
* to access this class.
*/
private NavigationLoader()
{
super(Navigation.class,
() -> Turbine.getConfiguration().getInt(Navigation.CACHE_SIZE_KEY,
Navigation.CACHE_SIZE_DEFAULT));
}
/**
* Attempts to load and execute the external Navigation. This is
* used when you want to execute a Navigation which returns its
* output via a MultiPartElement instead of out the data.getPage()
* value. This allows you to easily chain the execution of
* Navigation modules together.
*
* @param pipelineData Turbine information.
* @param name Name of object that will execute the navigation.
* @return the navigation module output
* @throws Exception a generic exception.
*/
public String eval(PipelineData pipelineData, String name)
throws Exception
{
// Execute Navigation
return getAssembler(name).build(pipelineData);
}
/**
* Attempts to load and execute the external Navigation.
*
* @param pipelineData Turbine information.
* @param name Name of object instance.
* @throws Exception a generic exception.
*/
@Override
public void exec(PipelineData pipelineData, String name)
throws Exception
{
this.eval(pipelineData, name);
}
/**
* The method through which this class is accessed.
*
* @return The single instance of this class.
*/
public static NavigationLoader getInstance()
{
return instance;
}
}
|
class
|
java
| 703 |
private final static boolean shouldStart(String inpath) throws Exception {
synchronized (BulkEmbeddedJsonDownloader.class) {
inpath = inpath.toUpperCase();
FileOutputStream out = new FileOutputStream(LOCK_FILE, /* append = */true);
try {
FileLock lock = null;
try {
lock = out.getChannel().lock();
List<String> lines = Files.readLines(STARTED_TASKS_FILE, Charsets.UTF_8);
if (!lines.contains(inpath)) {
lines.add(inpath);
Files.write(Joiner.on('\n').join(lines), STARTED_TASKS_FILE, Charsets.UTF_8);
return true;
}
} catch (Exception e) {
LOG.error(
"Can't acquire lock on lock-file " + LOCK_FILE
+ " or can't access running tasks file " + STARTED_TASKS_FILE + " : "
+ e.getMessage(), e);
throw e;
} finally {
if (lock != null)
lock.release();
}
} finally {
out.close();
}
return false;
}
}
|
function
|
java
| 704 |
@Test
public void testGenerateAndCountAbsencesOverYears() {
Mockito.when(userService.findByCompanyAndUserName(anyString(), anyString())).thenReturn(User.builder()
.company("MyCompany")
.firstName("Chris")
.lastName("Smith")
.leaveEntitlementPerYear(5)
.position("Doctor")
.workingDays(List.of(DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY, DayOfWeek.SATURDAY))
.startDate(LocalDate.of(2015,4,1))
.userName(SECOND_EMPLOYEE_USERNAME)
.build());
absenceService.delete("MyCompany", SECOND_EMPLOYEE_USERNAME, LocalDate.of(2015,12,29), LocalDate.of(2016,1,4));
assertTrue(absenceService.save(Absence.builder()
.company("MyCompany")
.category(AbsenceCategory.HOLIDAY)
.startDate(LocalDate.of(2015,12,29))
.endDate(LocalDate.of(2016,1,4))
.username(SECOND_EMPLOYEE_USERNAME)
.build()));
absenceService.delete("MyCompany", SECOND_EMPLOYEE_USERNAME, LocalDate.of(2015,12,20), LocalDate.of(2016,1,4));
assertFalse(absenceService.save(Absence.builder()
.company("MyCompany")
.category(AbsenceCategory.HOLIDAY)
.startDate(LocalDate.of(2015,12,20))
.endDate(LocalDate.of(2016,1,4))
.username(SECOND_EMPLOYEE_USERNAME)
.build()));
absenceService.delete("MyCompany", SECOND_EMPLOYEE_USERNAME, LocalDate.of(2015,12,29), LocalDate.of(2016,1,15));
assertFalse(absenceService.save(Absence.builder()
.company("MyCompany")
.category(AbsenceCategory.HOLIDAY)
.startDate(LocalDate.of(2015,12,29))
.endDate(LocalDate.of(2016,1,15))
.username(SECOND_EMPLOYEE_USERNAME)
.build()));
absenceService.delete("MyCompany", SECOND_EMPLOYEE_USERNAME, LocalDate.of(2015,12,29), LocalDate.of(2017,1,15));
assertFalse(absenceService.save(Absence.builder()
.company("MyCompany")
.category(AbsenceCategory.HOLIDAY)
.startDate(LocalDate.of(2015,12,29))
.endDate(LocalDate.of(2017,1,15))
.username(SECOND_EMPLOYEE_USERNAME)
.build()));
}
|
function
|
java
| 705 |
private boolean processNonDynamic(final AsyncNodeClassContext context, final JPPFResourceWrapper resource) throws Exception {
byte[] b = null;
final String name = resource.getName();
final TraversalList<String> uuidPath = resource.getUuidPath();
final AsyncNodeClassNioServer server = context.getServer();
String uuid = (uuidPath.size() > 0) ? uuidPath.getCurrentElement() : null;
if (((uuid == null) || uuid.equals(driver.getUuid())) && (resource.getCallable() == null)) {
final boolean fileLookup = (Boolean) resource.getData(ResourceIdentifier.FILE_LOOKUP_ALLOWED, true) && isFileLookup;
final ClassLoader cl = getClass().getClassLoader();
if (resource.getData(ResourceIdentifier.MULTIPLE) != null) {
final List<byte[]> list = server.getResourceProvider().getMultipleResourcesAsBytes(name, cl, fileLookup);
if (debugEnabled) log.debug("multiple resources {}found [{}] in driver's classpath for node {}", list != null ? "" : "not ", name, context);
if (list != null) resource.setData(ResourceIdentifier.RESOURCE_LIST, list);
} else if (resource.getData(ResourceIdentifier.MULTIPLE_NAMES) != null) {
final String[] names = (String[]) resource.getData(ResourceIdentifier.MULTIPLE_NAMES);
final Map<String, List<byte[]>> map = server.getResourceProvider().getMultipleResourcesAsBytes(cl, fileLookup, names);
resource.setData(ResourceIdentifier.RESOURCE_MAP, map);
} else {
if ((uuid == null) && !resource.isDynamic()) uuid = driver.getUuid();
if (uuid != null) b = classCache.getCacheContent(uuid, name);
final boolean alreadyInCache = (b != null);
if (debugEnabled) log.debug("resource {}found [{}] in cache for node {}", alreadyInCache ? "" : "not ", name, context);
if (!alreadyInCache) {
b = server.getResourceProvider().getResource(name, cl, fileLookup);
if (debugEnabled) log.debug("resource {}found [{}] in the driver's classpath for node {}", b == null ? "not " : "", name, context);
}
if ((b != null) || !resource.isDynamic()) {
if ((b != null) && !alreadyInCache) classCache.setCacheContent(driver.getUuid(), name, b);
resource.setDefinition(b);
}
}
}
resource.setState(JPPFResourceWrapper.State.NODE_RESPONSE);
return true;
}
|
function
|
java
| 706 |
def visualize_predictions(measurements, x_prediction, x_updated, camera,
frame):
world2cam = np.asarray(camera['TMatrixWorldToCam'])
cam2im = np.asarray(camera['ProjectionMatrix'])
measurement_im_space = convert_to_image_space(measurements, world2cam,
cam2im)
x_pred_im_space = convert_to_image_space(x_prediction, world2cam, cam2im)
x_upd_im_space = convert_to_image_space(x_updated, world2cam, cam2im)
plt.figure()
image = camera['Sequence'][str(frame)]['Image']
im_arr = np.zeros(image.shape)
image.read_direct(im_arr)
plt.imshow(im_arr, cmap='gray')
plt.scatter(measurement_im_space[0], measurement_im_space[1],
c = 'blue', label="Measurement")
plt.scatter(x_pred_im_space[0], x_pred_im_space[1],
c='red', label="Prediction")
plt.scatter(x_upd_im_space[0], x_upd_im_space[1],
c = 'green', label="A posteriori estimate")
plt.legend()
plt.show()
|
function
|
python
| 707 |
def makeBenchmarkInfo(benchmarkName, path, cpuInfo, events=None):
path = os.path.join(path, BENCHMARK_FILE_NAME)
config = configparser.RawConfigParser()
config.add_section(BENCHMARK_SECTION)
config.set(BENCHMARK_SECTION, BENCHMARK_NAME_KEY, benchmarkName)
legend = '{} run at {}'.format(benchmarkName, str(date.today()))
config.set(BENCHMARK_SECTION, BENCHMARK_LEGEND_KEY, legend)
config.add_section(BENCHMARK_CPU_INFO_SECTION)
config.set(BENCHMARK_CPU_INFO_SECTION, BENCHMARK_CPU_ID_KEY, cpuInfo.cpuId)
config.set(BENCHMARK_CPU_INFO_SECTION, BENCHMARK_CPU_FREQUENCY_KEY, cpuInfo.frequency)
if events:
config.add_section(BENCHMARK_PMC_SECTION)
config.set(BENCHMARK_PMC_SECTION, BENCHMARK_PMC_COUNTER_COUNT, len(events))
for i, event in enumerate(events):
value = '{},{},{},{}'.format(event.name, event.uarchName, event.user, event.kernel)
config.set(BENCHMARK_PMC_SECTION, BENCHMARK_PMC_COUNTER.format(i), value)
with open(path, 'w') as configfile:
config.write(configfile)
|
function
|
python
| 708 |
pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
if nums.len() == 0 {
return 0;
}
let mut count = 0;
loop {
let temp = count;
while temp + 1 < nums.len() && nums[temp] == nums[temp + 1] {
nums.remove(temp);
}
if count + 1 >= nums.len() {
break;
}
count += 1;
}
return nums.len() as i32;
}
|
function
|
rust
| 709 |
[DebuggerNonUserCode]
internal class MessageSourceProvider : IMessageSourceProvider
{
private string _methodName;
private string _className;
private string _fileName;
private int _lineNumber;
private string _formattedStackTrace;
public MessageSourceProvider(string className, string methodName)
{
_methodName = methodName;
_className = className;
_fileName = null;
_lineNumber = 0;
}
public MessageSourceProvider(string className, string methodName, string fileName, int lineNumber)
{
_methodName = methodName;
_className = className;
_fileName = fileName;
_lineNumber = lineNumber;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public MessageSourceProvider(int skipFrames)
{
FindMessageSource(skipFrames + 1);
}
public string StackTrace
{
[MethodImpl(MethodImplOptions.NoInlining)]
get
{
lock(this)
{
if (string.IsNullOrEmpty(_formattedStackTrace))
{
try
{
_formattedStackTrace = new StackTrace(1, true).ToString();
}
catch
{
_formattedStackTrace = null;
}
}
}
return _formattedStackTrace;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void FindMessageSource(int skipFrames)
{
try
{
var stackTrace = new StackTrace(skipFrames + 1, true);
StackFrame frame = null;
MethodBase method = null;
var selectedFrameIndex = 0;
var frameIndex = 0;
while (true)
{
try
{
frame = stackTrace.GetFrame(frameIndex);
selectedFrameIndex = frameIndex;
frameIndex++;
method = frame?.GetMethod();
if (method == null)
{
break;
}
var frameNamespace = (method.DeclaringType == null) ? null : method.DeclaringType.FullName;
if (frameNamespace != null &&
frameNamespace.StartsWith("System.") == false &&
frameNamespace.StartsWith("Gibraltar.") == false)
{
break;
}
}
catch
{
DebugBreak();
selectedFrameIndex = 0;
break;
}
method = null;
if (frameIndex > 200)
{
DebugBreak();
selectedFrameIndex = 0;
break;
}
}
if (frame == null || method == null)
{
frame = stackTrace.GetFrame(0);
selectedFrameIndex = 0;
}
_formattedStackTrace = new StackTrace(selectedFrameIndex + skipFrames + 1, true).ToString();
method = frame?.GetMethod();
if (method == null)
{
_methodName = null;
_className = null;
_fileName = null;
_lineNumber = 0;
}
else
{
try
{
_className = (method.DeclaringType == null) ? null : method.DeclaringType.FullName;
_methodName = method.Name;
}
catch
{
_methodName = null;
_className = null;
}
try
{
_fileName = frame.GetFileName();
if (string.IsNullOrEmpty(_fileName) == false)
{
_lineNumber = frame.GetFileLineNumber();
}
else
{
_lineNumber = 0;
}
}
catch
{
_fileName = null;
_lineNumber = 0;
}
}
}
catch
{
DebugBreak();
_methodName = null;
_className = null;
_fileName = null;
_lineNumber = 0;
}
}
[Conditional("DEBUG")]
private static void DebugBreak()
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
#region IMessageSourceProvider properties
public string MethodName { get { return _methodName; } }
public string ClassName { get { return _className; } }
public string FileName { get { return _fileName; } }
public int LineNumber { get { return _lineNumber; } }
#endregion
}
|
class
|
c#
| 710 |
static associate(models) {
Order.hasOne(models.BillingDetail, {
foreignKey: 'orderId',
as: 'billingDetail',
});
Order.hasOne(models.PackagingProcesse, {
foreignKey: 'orderId',
as: 'packagingProcesse',
});
Order.belongsTo(models.User, {
as: 'user',
});
Order.belongsToMany(models.Product, {
through: 'OrdersProducts',
foreignKey: 'orderId',
as: 'products',
});
}
|
function
|
javascript
| 711 |
public static VersionInfo Load(string fileName)
{
if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException(nameof(fileName));
if (!File.Exists(fileName)) throw new Exception($"Version file {fileName} doesn't exist");
var document = XDocument.Load(fileName);
var projectNode = GetOrCreateElement(document, "Project");
var retVal = new VersionInfo
{
Major = GetProjectPropertyNode(projectNode, "RadMajor", IntNotAvailable),
Minor = GetProjectPropertyNode(projectNode, "RadMinor", IntNotAvailable),
Patch = GetProjectPropertyNode(projectNode, "RadPatch", IntNotAvailable),
BuildNumber = GetProjectPropertyNode(projectNode, "RadBuild", IntNotAvailable),
GitCommit = GetProjectPropertyNode(projectNode, "GitCommit", StringNotAvailable),
gitBranch = GetProjectPropertyNode(projectNode, "GitBranch", StringNotAvailable),
gitCommits = GetProjectPropertyNode(projectNode, "GitCommits", StringNotAvailable),
PackageVersionShort = GetProjectPropertyNode(projectNode, "PackageVersionShort", StringNotAvailable),
packageVersionFull = GetProjectPropertyNode(projectNode, "PackageVersionFull", StringNotAvailable),
VersionFile = fileName
};
return retVal;
}
|
function
|
c#
| 712 |
fn read_next_character(&mut self) -> Option<char> {
// Get the current character.
let current_character = self.current_character;
// Replace the current character with the next character.
self.current_character = self.next_character;
// Get the character of the next position and replace the next character with it.
self.next_character =
self.content.chars().skip(self.next_position).next();
// Append one to the current position.
self.current_position += 1;
// Append one to the next position.
self.next_position += 1;
// Append one to the current column.
self.current_column += 1;
// Return the current character copy.
current_character
}
|
function
|
rust
| 713 |
[Service]
public class ActionEventHandler<TEvent> : ILocalEventHandler<TEvent>
{
public Func<TEvent, Task> Action { get; }
public ActionEventHandler(Func<TEvent, Task> handler)
{
Action = handler;
}
public async Task HandleEventAsync(TEvent eventData)
{
await Action(eventData);
}
}
|
class
|
c#
| 714 |
class Param<T extends Comparable<T>> {
/**
* Interface for a parsing functor.
*
* @param <U> The type returned by the call to parse()
*/
interface Parser<U> {
/**
* @param string The string to parse
* @return An object of type {@code U} which was parsed from the input
* @throws IllegalArgumentException If a value of type {@code U} can't be parsed from the input string
*/
U parse(String string) throws IllegalArgumentException;
}
/**
* Interface for a value verification functor.
*
* @param <U> The type being verified; must be comparable
*/
interface Verifier<U extends Comparable<U>> {
/**
* @param value The value to verify
* @param bound An bound for the value (see static methods in {@code Params} for examples
* @throws IllegalArgumentException If the value is outside the allowed range
*/
void verify(U value, U bound) throws IllegalArgumentException;
}
// Value of the parameter
private T value;
// A short (1-3 word) name for the parameter
private transient String name;
// A longer string giving details about the parameter's usage and units
private transient String hint;
/**
* @return A reference to the value
*/
T value() {
return value;
}
/**
* @return An empty string if {@code value} is null, {@code value.toString()} otherwise
*/
String string() {
return value == null ? "" : value.toString();
}
/**
* Sets the name string.
*
* @param name The name to assign
*/
void setName(String name) {
this.name = name;
}
/**
* @return An empty string if {@code name} is null, {@code name} otherwise
*/
String name() {
return name == null ? "" : name;
}
/**
* Sets the hint string.
*
* @param hint The hint to assign
*/
void setHint(String hint) {
this.hint = hint;
}
/**
* @return An empty string if {@code hint} is null, {@code hint} otherwise
*/
String hint() {
return hint == null ? "" : hint;
}
/**
* Attempts to parse a value of type {@code T} from a string.
*
* @param string The string to parse
* @param parser An instance of {@code Parser<T>} which defines the parsing behavior
* @throws IllegalArgumentException If the string contains only whitespace or the parse fails
*/
void parse(String string, Parser<T> parser) throws IllegalArgumentException {
if (string.replaceAll("\\s+", "").isEmpty()) {
throw new IllegalArgumentException("Value of \"" + name() + "\" must be non-empty");
}
try {
value = parser.parse(string);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to parse value \"" + string + "\" for parameter \"" + name() + '\"');
}
}
/**
* Verifies that the value of this parameter is in the correct range.
*
* @param bound The bound against which this parameter's value is checked by a call to {@code
* verifier.verify(value, bound)}
* @param verifier An instance of {@code Verifier<T>} which throws an exception if the value is out of range
* @throws IllegalArgumentException If {@code verifier.verify(value, bound)} fails (throws an exception)
*/
void verify(T bound, Verifier<T> verifier) throws IllegalArgumentException {
try {
verifier.verify(value, bound);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Value of \"" + name() + "\" " + e.getMessage() + " " + bound);
}
}
/**
* Used as a {@code Verifier} to check that the value is less than the bound.
*
* @param value The value to check
* @param max The bound; in this case the non-inclusive maximum
* @param <U> The type of {@code value} and {@code max}
*/
static <U extends Comparable<U>> void less(U value, U max) {
if (value.compareTo(max) >= 0) {
throw new IllegalArgumentException("must be less than");
}
}
/**
* Used as a {@code Verifier} to check that the value is greater than than the bound.
*
* @param value The value to check
* @param min The bound; in this case the non-inclusive minimum
* @param <U> The type of {@code value} and {@code max}
*/
static <U extends Comparable<U>> void greater(U value, U min) {
if (value.compareTo(min) <= 0) {
throw new IllegalArgumentException("must be greater than");
}
}
/**
* Used as a {@code Verifier} to check that the value is less than or equal to the bound.
*
* @param value The value to check
* @param max The bound; in this case the inclusive maximum
* @param <U> The type of {@code value} and {@code max}
*/
static <U extends Comparable<U>> void lessEq(U value, U max) {
if (value.compareTo(max) > 0) {
throw new IllegalArgumentException("must be less than or equal to");
}
}
/**
* Used as a {@code Verifier} to check that the value is greater than or equal to than the bound.
*
* @param value The value to check
* @param min The bound; in this case the inclusive minimum
* @param <U> The type of {@code value} and {@code max}
*/
static <U extends Comparable<U>> void greaterEq(U value, U min) {
if (value.compareTo(min) < 0) {
throw new IllegalArgumentException("must be greater than or equal to");
}
}
}
|
class
|
java
| 715 |
function LoadingSwitch(_ref) {
var children = _ref.children,
error = _ref.error,
errorWhenMissing = _ref.errorWhenMissing,
loading = _ref.loading,
renderError = _ref.renderError,
renderLoading = _ref.renderLoading,
require = _ref.require;
if (error) {
return renderError(error);
}
if (!require) {
if (loading) {
return renderLoading();
}
if (errorWhenMissing) {
return renderError(typeof errorWhenMissing === 'function' ? errorWhenMissing() : errorWhenMissing);
}
}
return children(require);
}
|
function
|
javascript
| 716 |
def compile_model(
self, model: Union[Model, str], device_name: str = None, config: dict = None,
) -> CompiledModel:
if device_name is None:
return CompiledModel(
super().compile_model(model, {} if config is None else config),
)
return CompiledModel(
super().compile_model(model, device_name, {} if config is None else config),
)
|
function
|
python
| 717 |
public static Cell parse(final String worldName, final int x, final int z) {
int cellSize = Coord.getCellSize();
int xResult = x / cellSize;
int zResult = z / cellSize;
boolean xNeedFix = x % cellSize != 0;
boolean zNeedFix = z % cellSize != 0;
return new Cell(worldName, xResult - (x < 0 && xNeedFix ? 1 : 0), zResult - (z < 0 && zNeedFix ? 1 : 0));
}
|
function
|
java
| 718 |
def open_with_correct_rotation(im_dir, file_name):
picture = Image.open(os.path.join(im_dir, file_name))
exif = picture._getexif()
if exif:
for orientation in ExifTags.TAGS.keys():
if ExifTags.TAGS[orientation] == 'Orientation':
break
if exif[orientation] == 3:
picture = picture.transpose(Image.ROTATE_180)
elif exif[orientation] == 6:
picture = picture.transpose(Image.ROTATE_270)
elif exif[orientation] == 8:
picture = picture.transpose(Image.ROTATE_90)
return picture
|
function
|
python
| 719 |
func NewDuplicateVoteEvidence(vote1, vote2 *Vote, blockTime time.Time, valSet *ValidatorSet) (*DuplicateVoteEvidence, error) {
var voteA, voteB *Vote
if vote1 == nil || vote2 == nil {
return nil, errors.New("missing vote")
}
if valSet == nil {
return nil, errors.New("missing validator set")
}
idx, val := valSet.GetByProTxHash(vote1.ValidatorProTxHash)
if idx == -1 {
return nil, errors.New("validator not in validator set")
}
if strings.Compare(vote1.BlockID.Key(), vote2.BlockID.Key()) == -1 {
voteA = vote1
voteB = vote2
} else {
voteA = vote2
voteB = vote1
}
return &DuplicateVoteEvidence{
VoteA: voteA,
VoteB: voteB,
TotalVotingPower: valSet.TotalVotingPower(),
ValidatorPower: val.VotingPower,
Timestamp: blockTime,
}, nil
}
|
function
|
go
| 720 |
public int deleteEntitiesById(final String matchField, final Model... entities) {
try {
if (entities != null && entities.length > 0) {
final List<Object> ids = new ArrayList<>(entities.length);
for (final Model e : entities) {
ids.add(invokeGet(e, matchField));
}
final String q = String.format(
"DELETE FROM %1$s AS m WHERE m.%2$s IN :inMatches",
entities[0].getClass().getName(), matchField);
return getEntityManager().createQuery(q)
.setParameter("inMatches", ids)
.executeUpdate();
}
} catch (final ConstraintViolationException e) {
log.warn("Unable to delete entities", e);
}
return -1;
}
|
function
|
java
| 721 |
public class Principal
{
public static readonly Principal AllUsers = new Principal("*");
public const string AWS_PROVIDER = "AWS";
public const string CANONICAL_USER_PROVIDER = "CanonicalUser";
private string id;
private string provider;
public Principal(string accountId)
{
this.provider = AWS_PROVIDER;
if (accountId == null)
{
throw new ArgumentNullException("accountId");
}
this.id = accountId.Replace("-", "");
}
public Principal(string provider, string id)
{
this.provider = provider;
if (string.Equals(provider, AWS_PROVIDER))
{
id = id.Replace("-", "");
}
this.id = id;
}
public string Provider
{
get
{
return provider;
}
set
{
provider = value;
}
}
public string Id
{
get
{
return id;
}
}
}
|
class
|
c#
| 722 |
public class ExampleDeepClass
{
public delegate void NestedDelegate();
public class NestedClass
{
public struct VeryNestedStruct
{
public bool IsDeep { get; set; }
public interface VeryVeryNestedInterface
{
}
}
}
protected class ProtectedNestedClass
{
}
internal class InternalNestedClass
{
}
protected internal class ProtectedInternalNestedClass
{
}
private class PrivateNestedClass
{
}
}
|
class
|
c#
| 723 |
public class FieldAliasingMapper extends MapperWrapper {
protected final Map fieldToAliasMap = new HashMap();
protected final Map aliasToFieldMap = new HashMap();
private final ElementIgnoringMapper elementIgnoringMapper;
public FieldAliasingMapper(Mapper wrapped) {
super(wrapped);
elementIgnoringMapper =
(ElementIgnoringMapper)lookupMapperOfType(ElementIgnoringMapper.class);
}
public void addFieldAlias(String alias, Class type, String fieldName) {
fieldToAliasMap.put(key(type, fieldName), alias);
aliasToFieldMap.put(key(type, alias), fieldName);
}
/**
* @deprecated As of 1.4.9 use {@link ElementIgnoringMapper#addElementsToIgnore(Pattern)}.
*/
public void addFieldsToIgnore(final Pattern pattern) {
if (elementIgnoringMapper != null) {
elementIgnoringMapper.addElementsToIgnore(pattern);
}
}
/**
* @deprecated As of 1.4.9 use {@link ElementIgnoringMapper#omitField(Class, String)}.
*/
public void omitField(Class definedIn, String fieldName) {
if (elementIgnoringMapper != null) {
elementIgnoringMapper.omitField(definedIn, fieldName);
}
}
private Object key(Class type, String name) {
return new FastField(type, name);
}
public String serializedMember(Class type, String memberName) {
String alias = getMember(type, memberName, fieldToAliasMap);
if (alias == null) {
return super.serializedMember(type, memberName);
} else {
return alias;
}
}
public String realMember(Class type, String serialized) {
String real = getMember(type, serialized, aliasToFieldMap);
if (real == null) {
return super.realMember(type, serialized);
} else {
return real;
}
}
private String getMember(Class type, String name, Map map) {
String member = null;
for (Class declaringType = type;
member == null && declaringType != Object.class && declaringType != null;
declaringType = declaringType.getSuperclass()) {
member = (String) map.get(key(declaringType, name));
}
return member;
}
}
|
class
|
java
| 724 |
internal bool IsCommunicationErrorContained(ErrorObject Error)
{
if (IsErrorContained())
{
foreach (ErrorObject Err in mErrorObjects)
{
if (Err != null && Err.MessageCode.Equals(Error.MessageCode))
{
if (Err.MessageParams != null && Error.MessageParams != null)
{
if (Err.MessageParams[0].Equals(Error.MessageParams[0]))
{
return true;
}
}
}
}
return false;
}
return false;
}
|
function
|
c#
| 725 |
func (integration *OpenMessagingIntegration) SendInboundMessageWithAttachment(context context.Context, from *OpenMessageFrom, messageID, text string, attachmentURL *url.URL, attachmentMimeType, attachmentID string, metadata map[string]string) (id string, err error) {
if integration.ID == uuid.Nil {
return "", errors.ArgumentMissing.With("ID")
}
if len(messageID) == 0 {
return "", errors.ArgumentMissing.With("messageID")
}
if attachmentURL == nil {
return "", errors.ArgumentMissing.With("url")
}
var attachmentType string
switch {
case len(attachmentMimeType) == 0:
attachmentType = "Link"
case strings.HasPrefix(attachmentMimeType, "audio"):
attachmentType = "Audio"
case strings.HasPrefix(attachmentMimeType, "image"):
attachmentType = "Image"
case strings.HasPrefix(attachmentMimeType, "video"):
attachmentType = "Video"
default:
attachmentType = "File"
}
var attachmentFilename string
if attachmentType != "Link" {
fileExtension := path.Ext(attachmentURL.Path)
if fileExtensions, err := mime.ExtensionsByType(attachmentMimeType); err == nil && len(fileExtensions) > 0 {
fileExtension = fileExtensions[0]
}
fileID, _ := nanoid.New()
attachmentFilename = strings.ToLower(attachmentType) + "-" + fileID + fileExtension
}
result := OpenMessageText{}
err = integration.client.Post(
integration.logger.ToContext(context),
"/conversations/messages/inbound/open",
&OpenMessageText{
Direction: "Inbound",
Channel: NewOpenMessageChannel(
messageID,
&OpenMessageTo{ ID: integration.ID.String() },
from,
),
Text: text,
Content: []*OpenMessageContent{
{
Type: "Attachment",
Attachment: &OpenMessageAttachment{
Type: attachmentType,
ID: attachmentID,
Mime: attachmentMimeType,
URL: attachmentURL,
Filename: attachmentFilename,
},
},
},
Metadata: metadata,
},
&result,
)
return result.ID, err
}
|
function
|
go
| 726 |
protected void transform(float[][] m, float[] v)
{
float vx,vy; float[] mp = m[0];
vx = mp[0]*v[0] + mp[1]*v[1] + mp[2];
mp = m[1];
vy = mp[0]*v[0] + mp[1]*v[1] + mp[2];
v[0] = vx; v[1] = vy;
}
|
function
|
java
| 727 |
def pack_public_bytes(self) -> bytes:
key_byte_stream = PascalStyleByteStream()
key_byte_stream.write_from_format_instructions_dict(
Key.HEADER_FORMAT_INSTRUCTIONS_DICT,
self.header
)
self_params_types: typing.Sequence[typing.Type[typing.Any]] = \
type(self.params).mro()
first_public_key_params_type = next(
(
params_type for params_type in self_params_types
if not issubclass(params_type, PrivateKeyParams)
),
PublicKeyParams
)
key_byte_stream.write_from_format_instructions_dict(
first_public_key_params_type.FORMAT_INSTRUCTIONS_DICT,
self.params
)
key_byte_stream.write_from_format_instructions_dict(
Key.FOOTER_FORMAT_INSTRUCTIONS_DICT,
self.footer
)
return key_byte_stream.getvalue()
|
function
|
python
| 728 |
private synchronized static boolean checkCanRun() {
if (!getRunning()) {
setRunning(true);
return true;
}
else {
return false;
}
}
|
function
|
java
| 729 |
public static TSelf ConvertFromId(TId id)
{
if (ExecutionContext.HasCurrent)
{
var rdc = ReferenceDataOrchestrator.Current[typeof(TSelf)];
if (rdc != null && rdc.TryGetById(id, out var rd))
return (TSelf)rd!;
}
var rdx = new TSelf { Id = id };
((IReferenceData)rdx).SetInvalid();
return rdx;
}
|
function
|
c#
| 730 |
public static void RegisterDefault<T, TProperty>(
Expression<Func<T, TProperty>> propertyExpression,
Func<IAnonymousData, TProperty> factory)
{
Argument.NotNull(propertyExpression, nameof(propertyExpression));
Argument.NotNull(factory, nameof(factory));
var member = ReflectionExtensions.GetMemberInfo(propertyExpression);
var property = member?.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("Invalid property expression.");
}
RegisterDefault(property, f => factory(f));
}
|
function
|
c#
| 731 |
public static unsafe void CPUCopyToCPU(
ref byte sourcePtr,
ref byte targetPtr,
long sourceLengthInBytes,
long targetLengthInBytes) =>
Buffer.MemoryCopy(
Unsafe.AsPointer(ref sourcePtr),
Unsafe.AsPointer(ref targetPtr),
sourceLengthInBytes,
targetLengthInBytes);
|
function
|
c#
| 732 |
def create_adversarial_negation(sample_list, MAX_SEQ_LEN):
def cut_at_max_seq_len(sent, orig_wp_len):
def undo_wp(sent_wp):
sent_redo = ""
for index, t in enumerate(sent_wp):
if t.startswith("##"):
sent_redo += t[2:]
elif index == 0:
sent_redo += t
else:
sent_redo += " " + t
return sent_redo
sent_wp = bert_tokenizer.tokenize(sent)
sent_wp = sent_wp[:orig_wp_len]
sent_wp = undo_wp(sent_wp)
return sent_wp
print("Add negation word to test set sentences.")
if "hypothesis" in sample_list[0].keys():
for sample in tqdm(sample_list):
prem_orig_wp_len, hypo_orig_wp_len = get_sent_original_seq_len(sample['hypothesis'], sample['premise'], MAX_SEQ_LEN)
sample['premise'] = cut_at_max_seq_len(sample['premise'], prem_orig_wp_len)
sample['hypothesis'] = cut_at_max_seq_len(sample['hypothesis'], hypo_orig_wp_len)
sample['hypothesis'] = "false is not true and " + sample['hypothesis']
else:
for sample in tqdm(sample_list):
sample['premise'] = cut_at_max_seq_len(sample['premise'], MAX_SEQ_LEN-3)
sample['premise'] = "false is not true and " + sample['premise']
return sample_list
|
function
|
python
| 733 |
fn _email_fetch() -> imap::error::Result<Option<String>> {
let domain = "imap.gmail.com";
let tls = native_tls::TlsConnector::builder().build().unwrap();
// we pass in the domain twice to check that the server's TLS
// certificate is valid for the domain we're connecting to.
let client = imap::connect((domain, 993), domain, &tls).unwrap();
// the client we have here is unauthenticated.
// to do anything useful with the e-mails, we need to log in
let user_name = "Masoncw777@gmail.com";
let pass_word = "wzrfxxevmwnogqbl";
let mut imap_session = client
.login(user_name, pass_word)
.map_err(|e| e.0)?;
// we want to fetch the first email in the INBOX mailbox
imap_session.select("INBOX")?;
// fetch message number 1 in this mailbox, along with its RFC822 field.
// RFC 822 dictates the format of the body of e-mails
let messages = imap_session.fetch("1", "RFC822")?;
let message = if let Some(m) = messages.iter().next() {
m
} else {
println!("No Messages Found");
return Ok(None);
};
// extract the message's body
let body = message.body().expect("message did not have a body!");
let body = std::str::from_utf8(body)
.expect("message was not valid utf-8")
.to_string();
// be nice to the server and log out
println!("Logging out...");
imap_session.logout()?;
Ok(Some(body))
}
|
function
|
rust
| 734 |
def compile_custom_op(header, source, op_name, warp=True):
if warp:
header = f"""
#pragma once
#include "op.h"
#include "var.h"
namespace jittor {{
{header}
}}
"""
source = f"""
#include "{op_name}_op.h"
namespace jittor {{
{source}
}}
"""
cops_dir = os.path.join(cache_path, "custom_ops")
make_cache_dir(cops_dir)
hname = os.path.join(cops_dir, op_name+"_op.h")
ccname = os.path.join(cops_dir, op_name+"_op.cc")
with open(hname, 'w') as f:
f.write(header)
with open(ccname, 'w') as f:
f.write(source)
m = compile_custom_ops([hname, ccname])
return getattr(m, op_name)
|
function
|
python
| 735 |
public class EXTBlendMinmax {
/** Accepted by the {@code mode} parameter of BlendEquationEXT. */
public static final int
GL_FUNC_ADD_EXT = 0x8006,
GL_MIN_EXT = 0x8007,
GL_MAX_EXT = 0x8008;
/** Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. */
public static final int GL_BLEND_EQUATION_EXT = 0x8009;
protected EXTBlendMinmax() {
throw new UnsupportedOperationException();
}
static boolean isAvailable(GLCapabilities caps) {
return checkFunctions(
caps.glBlendEquationEXT
);
}
// --- [ glBlendEquationEXT ] ---
public static void glBlendEquationEXT(int mode) {
long __functionAddress = GL.getCapabilities().glBlendEquationEXT;
if ( CHECKS )
checkFunctionAddress(__functionAddress);
callV(__functionAddress, mode);
}
}
|
class
|
java
| 736 |
@Nonnull
@CheckReturnValue
default WebhookMessageAction<T> addActionRows(@Nonnull Collection<? extends ActionRow> rows)
{
Checks.noneNull(rows, "ActionRows");
return addActionRows(rows.toArray(new ActionRow[0]));
}
|
function
|
java
| 737 |
HRESULT CShellUrl::SetPidl(LPCITEMIDLIST pidl)
{
HRESULT hr = S_OK;
ASSERT(!pidl || IS_VALID_PIDL(pidl));
Reset();
return _SetPidl(pidl);
}
|
function
|
c++
| 738 |
def run_classifier(clf, in_source_id='myuid323457', out_source_id='classifier_output', stream_no=0, window_size=None):
print('classifier process starting...')
if not window_size:
if hasattr(clf, 'window_size') and clf.window_size:
window_size = clf.window_size
else:
raise ValueError('Window size must be specified when creating ClassifierProcess if the classifier does not have a window_size attribute.')
print('making window inlet')
winlet = WindowInlet(in_source_id, window_size=window_size, stream_no=stream_no)
start = time.time()
total_buffered = len(winlet.pull_window())
while total_buffered < window_size:
print('Buffered samples: ' +str(total_buffered) + '/' + str(window_size))
if time.time() - start > 5:
raise TimeoutError('Insuficient data buffered, timeout expired.')
total_buffered = len(winlet.pull_window())
print('creating stream \"'+str(out_source_id)+'\"...')
info = StreamInfo(source_id=out_source_id)
outlet = StreamOutlet(info)
print('done')
while True:
pulled = winlet.pull_window()
print('clf input shape:', np.array(pulled).shape)
proba = clf.predict_proba([pulled])
outlet.push_sample([proba])
|
function
|
python
| 739 |
_handleClusterTap(evt) {
const latLngBounds = evt.layer.getBounds();
const markers = evt.layer.getAllChildMarkers();
const features = [];
for (let i=0; i<markers.length; i++) {
features.push(markers[i].featureProperties);
}
const detail = {
bounds: latLngBounds,
features: features
};
this.fire('px-map-marker-group-cluster-tapped', detail);
}
|
function
|
javascript
| 740 |
sendAttachmentFromURLTo(type, url, recipientId) {
const attachment = {
type,
payload: {
url,
},
};
return this.sendAttachmentTo(attachment, recipientId);
}
|
function
|
javascript
| 741 |
class NotebookManager:
"""Manage any number of detached running Notebook instances.
* Start instance by name, assign a port
* Get instance by name
* Stop instance by name
* Pass extra parameters to IPython Nobetook
"""
def __init__(self, notebook_folder, min_port=40000, port_range=10, kill_timeout=50, python=None):
"""
:param notebook_folder: A folder containing a subfolder for each named IPython Notebook. The subfolder contains pid file, log file, default.ipynb and profile files.
"""
self.min_port = min_port
self.port_range = port_range
self.notebook_folder = notebook_folder
self.kill_timeout = kill_timeout
if python:
self.python = python
else:
self.python = self.discover_python()
os.makedirs(notebook_folder, exist_ok=True)
self.cmd = self.get_manager_cmd()
def discover_python(self):
"""Get the Python interpreter we need to use to run our Notebook daemon."""
python = sys.executable
#: XXX fix this hack, uwsgi sets itself as Python
#: Make better used Python interpreter autodiscovery
if python.endswith("/uwsgi"):
python = python.replace("/uwsgi", "/python")
return python
def get_work_folder(self, name):
work_folder = os.path.join(self.notebook_folder, name)
os.makedirs(work_folder, exist_ok=True)
return work_folder
def get_log_file(self, name):
log_file = os.path.join(self.get_work_folder(name), "ipython.log")
return log_file
def get_pid(self, name):
"""Get PID file name for a named notebook."""
pid_file = os.path.join(self.get_work_folder(name), "notebook.pid")
return pid_file
def get_context(self, name):
return comm.get_context(self.get_pid(name))
def get_manager_cmd(self):
"""Get our daemon script path."""
cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py"))
assert os.path.exists(cmd)
return cmd
def pick_port(self):
"""Pick open TCP/IP port."""
ports = set(range(self.min_port, self.min_port + self.port_range))
return port_for.select_random(ports)
def get_notebook_daemon_command(self, name, action, port=0, *extra):
"""
Assume we launch Notebook with the same Python which executed us.
"""
return [self.python, self.cmd, action, self.get_pid(name), self.get_work_folder(name), port, self.kill_timeout] + list(extra)
def exec_notebook_daemon_command(self, name, cmd, port=0):
"""Run a daemon script command."""
cmd = self.get_notebook_daemon_command(name, cmd, port)
# Make all arguments explicit strings
cmd = [str(arg) for arg in cmd]
logger.info("Running notebook command: %s", " ".join(cmd))
# print("XXX - DEBUG - Running notebook command:", " ".join(cmd))
# Add support for traceback dump on stuck
env = os.environ.copy()
env["PYTHONFAULTHANDLER"] = "true"
p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=env)
time.sleep(0.2)
stdout, stderr = p.communicate()
if b"already running" in stderr:
raise RuntimeError("Looks like notebook_daemon is already running. Please kill it manually pkill -f notebook_daemon. Was: {}".format(stderr.decode("utf-8")))
if p.returncode != 0:
logger.error("STDOUT: %s", stdout)
logger.error("STDERR: %s", stderr)
raise RuntimeError("Could not execute notebook command. Exit code: {} cmd: {}".format(p.returncode, " ".join(cmd)))
return stdout
def get_notebook_status(self, name):
"""Get the running named Notebook status.
:return: None if no notebook is running, otherwise context dictionary
"""
context = comm.get_context(self.get_pid(name))
if not context:
return None
return context
def start_notebook(self, name, context: dict, fg=False):
"""Start new IPython Notebook daemon.
:param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed.
:param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to identify the launch parameters for the notebook
"""
assert context
assert type(context) == dict
assert "context_hash" in context
assert type(context["context_hash"]) == int
http_port = self.pick_port()
assert http_port
context = context.copy()
context["http_port"] = http_port
# We can't proxy websocket URLs, so let them go directly through localhost or have front end server to do proxying (nginx)
if "websocket_url" not in context:
context["websocket_url"] = "ws://localhost:{port}".format(port=http_port)
if "{port}" in context["websocket_url"]:
# Do port substitution for the websocket URL
context["websocket_url"] = context["websocket_url"].format(port=http_port)
pid = self.get_pid(name)
assert "terminated" not in context
comm.set_context(pid, context)
if fg:
self.exec_notebook_daemon_command(name, "fg", port=http_port)
else:
self.exec_notebook_daemon_command(name, "start", port=http_port)
def stop_notebook(self, name):
self.exec_notebook_daemon_command(name, "stop")
def is_running(self, name):
status = self.get_notebook_status(name)
if status:
return status.get("pid") is not None
return False
def is_same_context(self, context_a, context_b):
if context_a == context_b:
return True
context_a = context_a or {}
context_b = context_b or {}
return context_a.get("context_hash") == context_b.get("context_hash")
def start_notebook_on_demand(self, name, context):
"""Start notebook if not yet running with these settings.
Return the updated settings with a port info.
:return: (context dict, created flag)
"""
if self.is_running(name):
last_context = self.get_context(name)
logger.info("Notebook context change detected for %s", name)
if not self.is_same_context(context, last_context):
self.stop_notebook(name)
# Make sure we don't get race condition over context.json file
time.sleep(2.0)
else:
return last_context, False
err_log = os.path.join(self.get_work_folder(name), "notebook.stderr.log")
logger.info("Launching new Notebook named %s, context is %s", name, context)
logger.info("Notebook log is %s", err_log)
self.start_notebook(name, context)
time.sleep(1)
context = self.get_context(name)
if "notebook_name" not in context:
# Failed to launch within timeout
raise RuntimeError("Failed to launch IPython Notebook, see {}".format(err_log))
return context, True
|
class
|
python
| 742 |
std::string ParticleData::getNameByType(unsigned int type) const
{
if (type >= getNTypes())
{
m_exec_conf->msg->error() << "Requesting type name for non-existent type " << type << endl;
throw runtime_error("Error mapping type name");
}
return m_type_mapping[type];
}
|
function
|
c++
| 743 |
static struct clk_hw *_sci_clk_build(struct sci_clk_provider *provider,
u16 dev_id, u8 clk_id)
{
struct clk_init_data init = { NULL };
struct sci_clk *sci_clk = NULL;
char *name = NULL;
char **parent_names = NULL;
int i;
int ret;
sci_clk = devm_kzalloc(provider->dev, sizeof(*sci_clk), GFP_KERNEL);
if (!sci_clk)
return ERR_PTR(-ENOMEM);
sci_clk->dev_id = dev_id;
sci_clk->clk_id = clk_id;
sci_clk->provider = provider;
ret = provider->ops->get_num_parents(provider->sci, dev_id,
clk_id,
&init.num_parents);
if (ret)
goto err;
name = kasprintf(GFP_KERNEL, "%s:%d:%d", dev_name(provider->dev),
sci_clk->dev_id, sci_clk->clk_id);
init.name = name;
if (init.num_parents < 2)
init.num_parents = 0;
if (init.num_parents) {
parent_names = kcalloc(init.num_parents, sizeof(char *),
GFP_KERNEL);
if (!parent_names) {
ret = -ENOMEM;
goto err;
}
for (i = 0; i < init.num_parents; i++) {
char *parent_name;
parent_name = kasprintf(GFP_KERNEL, "%s:%d:%d",
dev_name(provider->dev),
sci_clk->dev_id,
sci_clk->clk_id + 1 + i);
if (!parent_name) {
ret = -ENOMEM;
goto err;
}
parent_names[i] = parent_name;
}
init.parent_names = (void *)parent_names;
}
init.ops = &sci_clk_ops;
sci_clk->hw.init = &init;
ret = devm_clk_hw_register(provider->dev, &sci_clk->hw);
if (ret)
dev_err(provider->dev, "failed clk register with %d\n", ret);
err:
if (parent_names) {
for (i = 0; i < init.num_parents; i++)
kfree(parent_names[i]);
kfree(parent_names);
}
kfree(name);
if (ret)
return ERR_PTR(ret);
return &sci_clk->hw;
}
|
function
|
c
| 744 |
private class OpenSCADPathFinder
{
private readonly string[] possibleFilePaths = new string[]
{
@"C:\Program Files (x86)\OpenSCAD\openscad.exe",
@"C:\Program Files\OpenSCAD\openscad.exe"
};
internal string GetPath()
{
foreach (string path in possibleFilePaths)
{
if (File.Exists(path))
return path;
}
return null;
}
}
|
class
|
c#
| 745 |
@SuppressWarnings("serial")
public class ExternalGroup extends DomainObject {
private String identifier;
private String name;
private String description;
private String groupProviderIdentifier;
/**
* Field not stored in this database
*/
private ExternalGroupProvider groupProvider;
public ExternalGroup() {
}
public ExternalGroup(String id, String name, String description, ExternalGroupProvider groupProvider) {
this.setIdentifier(id);
this.setName(name);
this.setDescription(description);
this.setGroupProvider(groupProvider);
this.setGroupProviderIdentifier(groupProvider.getIdentifier());
}
/**
* @return identifier of the group {@literal urn:collab:groups:university.nl:students}
*/
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
/**
* @return human readable name of the group {@literal University: Students}
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* @return long description of the group
* {@literal This is the group that contains all students from the University}
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* @return identifier of the group provider, e.g. {@literal University.nl}
*/
public String getGroupProviderIdentifier() {
return groupProviderIdentifier;
}
public void setGroupProviderIdentifier(String groupProviderIdentifier) {
this.groupProviderIdentifier = groupProviderIdentifier;
}
public ExternalGroupProvider getGroupProvider() {
return groupProvider;
}
public void setGroupProvider(ExternalGroupProvider groupProvider) {
this.groupProvider = groupProvider;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ExternalGroup that = (ExternalGroup) o;
if (identifier != null ? !identifier.equals(that.identifier) : that.identifier != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (identifier != null ? identifier.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer();
sb.append("ExternalGroup");
sb.append("{id='").append(getId()).append('\'');
sb.append(", identifier='").append(identifier).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", groupProviderIdentifier='").append(groupProviderIdentifier).append('\'');
sb.append('}');
return sb.toString();
}
}
|
class
|
java
| 746 |
public class Switch {
private boolean _value;
/**
* Allocates a Switch object representing the value argument.
*
* @param value to turn on or off
*/
public Switch(boolean value) {
this._value = value;
}
/**
* Returns a String representation of the value of the Switch object.
*
* @return "on" or "off".
*/
public String toString() {
return (this._value) ? "on" : "off";
}
/**
* Returns a Switch object with a value represented by the
* specified String.
*
* @param value "on" => true, null and all other strings, false.
* @return a Swing object instance
*/
public static Switch valueOf(String value) {
if (value != null && value.equalsIgnoreCase("on"))
return new Switch(true);
return new Switch(false);
}
}
|
class
|
java
| 747 |
public final class Converter {
public static final byte [] NullByteArray = new byte [1];
public static final byte [] EmptyByteArray = new byte [0];
public static final char [] EmptyCharArray = new char [0];
/**
* Returns the default code page for the platform where the
* application is currently running.
*
* @return the default code page
*/
public static String defaultCodePage () {
return "UTF8";
}
public static char [] mbcsToWcs (String codePage, byte [] buffer) {
try {
return new String (buffer, defaultCodePage ()).toCharArray ();
} catch (UnsupportedEncodingException e) {
return EmptyCharArray;
}
}
public static byte [] wcsToMbcs (String codePage, String string, boolean terminate) {
try {
if (!terminate) return string.getBytes (defaultCodePage ());
byte [] buffer1 = string.getBytes (defaultCodePage ());
byte [] buffer2 = new byte [buffer1.length + 1];
System.arraycopy (buffer1, 0, buffer2, 0, buffer1.length);
return buffer2;
} catch (UnsupportedEncodingException e) {
return terminate ? NullByteArray : EmptyByteArray;
}
}
public static byte [] wcsToMbcs (String codePage, char [] buffer, boolean terminate) {
try {
if (!terminate) return new String (buffer).getBytes (defaultCodePage ());
byte [] buffer1 = new String (buffer).getBytes (defaultCodePage ());
byte [] buffer2 = new byte [buffer1.length + 1];
System.arraycopy (buffer1, 0, buffer2, 0, buffer1.length);
return buffer2;
} catch (UnsupportedEncodingException e) {
return terminate ? NullByteArray : EmptyByteArray;
}
}
}
|
class
|
java
| 748 |
def expectation(self, diag_hermitian: bk.TensorLike,
trials: int = None) -> bk.BKTensor:
if trials is None:
probs = self.probabilities()
else:
probs = bk.real(bk.astensorproduct(self.sample(trials) / trials))
diag_hermitian = bk.astensorproduct(diag_hermitian)
return bk.sum(bk.real(diag_hermitian) * probs)
|
function
|
python
| 749 |
func (c *Chunk) GetTheRenderable(textureIndexes fizzle.TextureArrayIndexes) *fizzle.Renderable {
if c.Renderable != nil {
return c.Renderable
}
c.Renderable = c.buildVoxelRenderable(textureIndexes)
return c.Renderable
}
|
function
|
go
| 750 |
def update_email_settings(self, email_settings):
name = email_settings.get('sender_name', None)
email = email_settings.get('sender_email', None)
if name is None or email is None:
raise SDKException('Organization', 114, 'No configurable settings were set in the input')
req_json = {
"senderSmtp": email,
"senderName": name
}
self._update_properties_json(req_json)
self._update_properties()
|
function
|
python
| 751 |
public static SleepResult Sleep(uint waitTimeMillisec)
{
if(waitTimeMillisec == 0)
return SleepResult.Completed;
if(ApplicationExiting.WaitOne((int)waitTimeMillisec))
return SleepResult.Aborted;
return SleepResult.Completed;
}
|
function
|
c#
| 752 |
def cluster_update_task(self, brokers, broker_ca, managers, manager_ca):
self._assert_name('cluster-update')
factory = DaemonFactory()
daemon = factory.load(self.name)
os.environ[constants.REST_HOST_KEY] = \
u','.join(managers).encode('utf-8')
with open(daemon.local_rest_cert_file, 'w') as f:
f.write(manager_ca)
with open(daemon.broker_ssl_cert_path, 'w') as f:
f.write(broker_ca)
daemon.rest_host = managers
daemon.broker_ip = brokers
daemon.create_broker_conf()
daemon.create_config()
factory.save(daemon)
|
function
|
python
| 753 |
def granule_info(data_dict):
granule_search_url = 'https://cmr.earthdata.nasa.gov/search/granules'
data_dict['page_size'] = 2000
data_dict['page_num'] = 1
granules = []
headers={'Accept': 'application/json'}
while True:
response = requests.get(granule_search_url, params=data_dict, headers=headers)
results = json.loads(response.content)
if len(results['feed']['entry']) == 0:
data_dict['page_num'] -= 1
break
granules.extend(results['feed']['entry'])
data_dict['page_num'] += 1
granule_sizes = [float(granule['granule_size']) for granule in granules]
print('There are', len(granules), 'files of', data_dict['short_name'], 'version', data_dict['version'], 'over my area and time of interest.')
print(f'The average size of each file is {mean(granule_sizes):.2f} MB and the total size of all {len(granules)} granules is {sum(granule_sizes):.2f} MB')
return len(granules)
|
function
|
python
| 754 |
int FDTools_::mySelect_ (int nfds,
fd_set* readfds, fd_set* writefds, fd_set* errfds,
struct timeval *passed_timeout_p)
{
int r;
struct timeval time_out, *time_out_p;
if (passed_timeout_p==NULL) {
time_out_p = NULL;
} else {
time_out = *passed_timeout_p;
time_out_p = &time_out;
}
while (1) {
struct timeval mark_time = now();
r = select(nfds, readfds, writefds, errfds, time_out_p);
if (r==-1 && errno==EINTR) {
if (time_out_p==NULL) continue;
struct timeval current_time = now();
time_out = subTimes(time_out, subTimes(current_time, mark_time));
if (time_out.tv_sec<0 || time_out.tv_usec<0) {
struct timeval zero;
zero.tv_usec = 0; zero.tv_sec = 0;
time_out = zero;
}
continue;
} else {
break;
}
}
return r;
}
|
function
|
c++
| 755 |
private static Apartment generateRandomApartment(boolean realAddress)
throws ClientErrorException, AddressApiException {
double floorArea = simulateRandomDraw(65d, 21d);
String address = realAddress ? getOnlineRandomAddress() : getRandomAddress();
int averageRoomArea = 10 + rand.nextInt(20);
int nbBedrooms = Math.max(((int) (floorArea / averageRoomArea)) - 1, 1);
int nbSleeping = (1 + rand.nextInt(4)) * nbBedrooms;
int nbBathrooms = 1 + rand.nextInt(nbBedrooms);
boolean hasTerrace = Math.random() >= 0.5;
double floorAreaTerrace = (hasTerrace) ? simulateRandomDraw(15d, 2d) : 0;
String title = "Location Apartement " + rand.nextInt(10000);
String description =
"This apartment has "
+ nbBedrooms
+ " bedrooms and a size of "
+ floorArea
+ "square meters";
boolean wifi = Math.random() >= 0.5;
double pricePerNight = floorArea * simulateRandomDraw(11d, 3d);
boolean tele = Math.random() >= 0.5;
int nbMinNight = rand.nextInt(700) + 1;
Builder apartBuilder = new Builder();
return apartBuilder
.setFloorArea(floorArea)
.setAddress(address)
.setNbBedrooms(nbBedrooms)
.setNbSleeping(nbSleeping)
.setNbBathrooms(nbBathrooms)
.setTerrace(hasTerrace)
.setFloorAreaTerrace(floorAreaTerrace)
.setDescription(description)
.setTitle(title)
.setWifi(wifi)
.setPricePerNight(pricePerNight)
.setNbMinNight(nbMinNight)
.setTele(tele)
.build();
}
|
function
|
java
| 756 |
pub unsafe extern "C" fn sched() {
let p = myproc();
if (!holding(&mut ptable.lock as *mut Spinlock)) {
cpanic("sched ptable.lock");
}
if ((*mycpu()).ncli != 1) {
cpanic("sched locks");
}
if ((*p).state == RUNNING) {
cpanic("sched running");
}
if (readeflags() & FL_IF) != 0 {
cpanic("sched interruptible");
}
let intena = (*mycpu()).intena;
swtch(&mut (*p).context as *mut *mut Context, (*mycpu()).scheduler);
(*mycpu()).intena = intena;
}
|
function
|
rust
| 757 |
@Override
public int sizeFromValues(T lo, T hi) {
requireNonNull(lo);
requireNonNull(hi);
if (lo.compareTo(hi) > 0) return 0;
if (contains(hi)) return rankFromValues(hi) - rankFromValues(lo) + 1;
else return rankFromValues(hi) - rankFromValues(lo);
}
|
function
|
java
| 758 |
@SuppressWarnings("unchecked")
<T> Class<? extends ReactorCacheListener<T>> generateListenerClass(Class<T> eventClass) {
return (Class<? extends ReactorCacheListener<T>>) eventClassToListener.computeIfAbsent(eventClass, eventClazz ->
new ByteBuddy().subclass(ReactorCacheListener.class)
.defineMethod("listenGenerated", void.class).withParameter(eventClazz)
.intercept(MethodDelegation.to(ListenerFactory.class))
.annotateMethod(LISTENER_ANNOTATIONS)
.make()
.load(ClassLoader.getSystemClassLoader())
.getLoaded());
}
|
function
|
java
| 759 |
def transverse_isotropic_material(stiffness, poisson, density, *args, **kwargs):
name = kwargs.get('name', None)
strength = kwargs.get('strength', None)
e1 = float(stiffness['e1'])
e2 = float(stiffness['e2'])
g12 = float(stiffness['g12'])
nu12 = float(poisson['nu12'])
nu23 = float(poisson['nu23'])
nu21 = e2 / e1 * nu12
g23 = e2 / (2 * (1 + nu23))
stiffnesses = [(e1, g23), (e2, g12), (e2, g12)]
poissons = [(nu23, nu23), (nu12, nu21), (nu12, nu21)]
material = ElasticMaterial(
name=name,
stiffness=stiffnesses,
poisson=poissons,
strength=strength,
density=density)
return material
|
function
|
python
| 760 |
@Override public void init(boolean expensive) {
super.init(expensive);
if( _parms._regex == null ) {
error("_regex", "regex is missing");
} else {
try { _pattern = Pattern.compile(_parms._regex); }
catch( PatternSyntaxException pse ) { error("regex", pse.getMessage()); }
}
if( _parms._train == null ) return;
Vec[] vecs = _parms.train().vecs();
if( vecs.length != 1 )
error("_train","Frame must contain exactly 1 Vec (of raw text)");
if( !(vecs[0] instanceof ByteVec) )
error("_train","Frame must contain exactly 1 Vec (of raw text)");
}
|
function
|
java
| 761 |
void
CPersStream::PersStream()
{
if (PR_htValid) {
switch (PR_htInst) {
case STRM_RECV:
{
if (RecvHostDataBusy()) {
HtRetry();
break;
}
if (RecvHostDataMarker()) {
HtContinue(STRM_RTN);
} else {
P_rcvData = RecvHostData();
HtContinue(STRM_ECHO);
}
}
break;
case STRM_ECHO:
{
if (SendHostDataBusy()) {
HtRetry();
break;
}
SendHostData(PR_rcvData);
HtContinue(STRM_RECV);
}
break;
case STRM_RTN:
{
if (SendReturnBusy_htmain()) {
HtRetry();
break;
}
SendReturn_htmain();
}
break;
default:
assert(0);
}
}
}
|
function
|
c++
| 762 |
fn check(&self) -> Result<(), &str> {
// Compare Whole protein and Box modes
if self.settings.modes.whole_protein_mode == self.settings.modes.box_mode {
return Err(
"Invalid parameters file! Whole protein and box modes cannot be equal!",
);
}
// Compare resolution mode
if self.settings.modes.resolution_mode != KVSResolution::Low {
return Err("Invalid parameters file! Resolution mode is restricted to Low option on this web service!");
}
// Probe In
if self.settings.probes.probe_in < 0.0 || self.settings.probes.probe_in > 5.0 {
return Err("Invalid parameters file! Probe In must be between 0 and 5!");
}
// Probe Out
if self.settings.probes.probe_out < 0.0 || self.settings.probes.probe_out > 50.0 {
return Err("Invalid parameters file! Probe Out must be between 0 and 50!");
}
// Compare probes
if self.settings.probes.probe_out < self.settings.probes.probe_in {
return Err("Invalid parameters file! Probe Out must be greater than Probe In!");
}
// Removal distance
if self.settings.cutoffs.removal_distance < 0.0
|| self.settings.cutoffs.removal_distance > 10.0
{
return Err("Invalid parameters file! Removal distance must be between 0 and 10!");
}
// Volume Cutoff
if self.settings.cutoffs.volume_cutoff < 0.0 {
return Err("Invalid parameters file! Volume cutoff must be greater than 0!");
}
// Cavity representation
if self.settings.modes.kvp_mode {
return Err("Invalid parameters file! Cavity Representation (kvp_mode) must be false on this webservice!");
}
// Ligand mode and pdb
if self.settings.modes.ligand_mode && self.pdb_ligand == None {
return Err("Invalid parameters file! A ligand must be provided when Ligand mode is set to true!");
} else if !self.settings.modes.ligand_mode && self.pdb_ligand != None {
return Err("Invalid parameters file! The Ligand mode must be set to true when providing a ligand!");
}
// Ligand Cutoff
if self.settings.cutoffs.ligand_cutoff <= 0.0 {
return Err("Invalid parameters file! Ligand cutoff must be greater than 0!");
}
// Box inside pdb boundaries
if self.settings.modes.box_mode {
if let Ok(pdb_boundaries) = self.get_pdb_boundaries() {
if !pdb_boundaries.contains(&self.settings.internalbox) {
return Err("Invalid parameters file! Inconsistent box coordinates!");
}
} else {
return Err("parsing error");
}
}
Ok(())
}
|
function
|
rust
| 763 |
def swap(self, index1, index2):
if self.valid_swap(index1, index2):
color1, swap1 = self.get(index1)
color2, swap2 = self.get(index2)
self.set_value(index1, color2, swap2 - 1)
self.set_value(index2, color1, swap1 - 1)
swapping_points = self.swapping_points
one_swap = self.one_swap_points
if swap2 < 2:
swapping_points[index1] = False
one_swap[index1] = False
if swap1 < 2:
swapping_points[index2] = False
one_swap[index2] = False
if swap2 == 3:
one_swap[index1] = True
if swap1 == 3:
one_swap[index2] = True
self.swaps_left -= 2
return True
return False
|
function
|
python
| 764 |
func NewEngineForTests() *Engine {
se := &Engine{
isOpen: true,
tables: make(map[string]*Table),
}
return se
}
|
function
|
go
| 765 |
public ColumnVector solve (final ColumnVector b, final boolean improve) throws MatrixException
{
if (b.m_nRows != m_nRows)
{
throw new MatrixException (MatrixException.INVALID_DIMENSIONS);
}
decompose ();
final ColumnVector y = _forwardSubstitution (b);
final ColumnVector x = _backSubstitution (y);
if (improve)
_improve (b, x);
return x;
}
|
function
|
java
| 766 |
protected override void OnContentClick(DataGridViewCellEventArgs e)
{
IndicatorColumn owner = base.OwningColumn as IndicatorColumn;
if(this.IsClickable && base.DataGridView != null && owner != null && this.MouseImageIndex != -1 &&
this.MouseImageIndex < owner.ImageList.Images.Count)
{
IndicatorClickEventArgs clickArgs = new IndicatorClickEventArgs(e.ColumnIndex, e.RowIndex,
this.MouseImageIndex, base.NewValue);
owner.OnIndicatorClicked(clickArgs);
if(!base.ReadOnly && ((clickArgs.Value == null && base.NewValue != null) ||
(clickArgs.Value != null && !clickArgs.Value.Equals(base.NewValue))))
{
base.NewValue = clickArgs.Value;
base.DataGridView.NotifyCurrentCellDirty(true);
base.DataGridView.InvalidateCell(this);
}
}
}
|
function
|
c#
| 767 |
protected Size GetElementDesiredSize(View view)
{
#if __WASM__
return view.DesiredSize;
#else
return (_layouter as ILayouter).GetDesiredSize(view);
#endif
}
|
function
|
c#
| 768 |
public class UserRequestRateControlInterceptor extends AbstractUsernameRequestInterceptor implements EndpointInterceptor {
private final Logger logger = LoggerFactory.getLogger(UserRequestRateControlInterceptor.class);
private final int MAX_REQUESTS_PER_SECOND = 20;
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
boolean concurrencyLevelsAcceptable = true;
WebServiceMessage message = messageContext.getRequest();
if (message instanceof SoapMessage) {
SoapMessage soapMessage = (SoapMessage)message;
Optional<String> soapUserName = getSoapUserName(soapMessage);
if (soapUserName.isPresent() && StringUtils.hasText(soapUserName.get())) {
int currentHitRate = requestHitCounter.registerHit(soapUserName.get());
logger.info("User {} hit rate: {}", soapUserName.get(), currentHitRate);
if (currentHitRate > MAX_REQUESTS_PER_SECOND) {
concurrencyLevelsAcceptable = false;
}
}
}
return concurrencyLevelsAcceptable;
}
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
}
|
class
|
java
| 769 |
updateClassListWhenError() {
if (!this._valid && !this._readOnly) {
this.classList.remove('slds-has-error');
this.startDateInput.classList.add('slds-has-error');
this.startDateInput.classList.add('avonni-date-range__input_error');
this.endDateInput.classList.add('slds-has-error');
this.endDateInput.classList.add('avonni-date-range__input_error');
if (this.showTime) {
this.startTimeInput.classList.add('slds-has-error');
this.endTimeInput.classList.add('slds-has-error');
}
}
if (this._valid && !this._readOnly) {
this.startDateInput.classList.remove('slds-has-error');
this.startDateInput.classList.remove(
'avonni-date-range__input_error'
);
this.endDateInput.classList.remove('slds-has-error');
this.endDateInput.classList.remove(
'avonni-date-range__input_error'
);
if (this.showTime) {
this.startTimeInput.classList.remove('slds-has-error');
this.endTimeInput.classList.remove('slds-has-error');
}
}
}
|
function
|
javascript
| 770 |
def write_list_redis(server, key, values):
try:
if server.exists(key):
server.delete(key)
server.rpush(key, *values)
log.debug("Pushed to list: {} --> {}".format(key, values))
return True
except:
log.error("Failed to rpush to {}".format(key))
return False
|
function
|
python
| 771 |
public override async Task<IReadOnlyList<IStockQuoteFromDataSource>> GetHistoricalQuotesAsync(Country country, string stockId, DateTime start, DateTime end, Action<Exception> writeToErrorLogAction)
{
string stockFullId = country == Country.USA ? stockId : $"{stockId}.{country.GetShortName()}";
string avUrl = Configuration["AlphaVantageDailyUrl"];
if ((end - start).TotalDays > 120)
{
avUrl = Configuration["AlphaVantageDailyFullOutputUrl"];
}
string key = Configuration["AlphaVantageKey"];
(string JsonContent, IReadOnlyList<Cookie> Cookies) response = await GetHttpContentAsync(string.Format(avUrl, stockFullId, key)).ConfigureAwait(false);
IReadOnlyList<IStockQuoteFromDataSource> quotes = _parser.ParseMultiQuotes(country, stockId, response.JsonContent, writeToErrorLogAction);
return quotes.Where(a => a.TradeDateTime >= start && a.TradeDateTime <= end).ToList();
}
|
function
|
c#
| 772 |
@ApiOperation(httpMethod = "POST", value = "Update Asset values")
@PostMapping(value = "/v1/update-asset")
public ResponseEntity<Object> updateAsset(@RequestBody(required = true) AssetUpdateRequest request)
throws DataException {
String assetGroup = request.getAg();
if (Strings.isNullOrEmpty(assetGroup)) {
return ResponseUtils.buildFailureResponse(new Exception("Asset group is Mandatory"));
}
String targettype = request.getTargettype();
if (Strings.isNullOrEmpty(targettype)) {
return ResponseUtils.buildFailureResponse(new Exception("Target type is Mandatory"));
}
String updatedBy = request.getUpdateBy();
if (Strings.isNullOrEmpty(updatedBy)) {
updatedBy = "";
}
Map<String, Object> resources = request.getResources();
int totalRows = assetService
.updateAsset(assetGroup, targettype, resources, updatedBy, request.getUpdates());
if (totalRows > 0) {
return ResponseUtils.buildSucessResponse(HttpStatus.OK);
} else {
return ResponseUtils.buildFailureResponse(new Exception("Update failed"));
}
}
|
function
|
java
| 773 |
def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName,
skipLabelList=None, startT=None, stopT=None):
minT = tg.minTimestamp
maxT = tg.maxTimestamp
wordTier = tg.tierDict[wordTierName]
phoneTier = tg.tierDict[phoneTierName]
if skipLabelList is None:
skipLabelList = []
syllableEntryList = []
tonicSEntryList = []
tonicPEntryList = []
if startT is not None or stopT is not None:
if startT is None:
startT = minT
if stopT is None:
stopT = maxT
wordTier = wordTier.crop(startT, stopT, "truncated", False)
for start, stop, word in wordTier.entryList:
if word in skipLabelList:
continue
subPhoneTier = phoneTier.crop(start, stop, "strict", False)
phoneList = [entry[2] for entry in subPhoneTier.entryList
if entry[2] != '']
try:
sylTmp = pronunciationtools.findBestSyllabification(isleDict,
word,
phoneList)
except isletool.WordNotInISLE:
print("Word ('%s') not is isle dictionary -- skipping syllabification" % word)
continue
except pronunciationtools.NullPronunciationError:
print("Word ('%s') has no provided pronunciation" % word)
continue
except AssertionError:
print("Unable to syllabify '%s'" % word)
continue
stressI = sylTmp[0]
stressJ = sylTmp[1]
syllableList = sylTmp[2]
if stressI is not None and stressJ is not None:
syllableList[stressI][stressJ] += u"ˈ"
i = 0
for k, syllable in enumerate(syllableList):
j = len(syllable)
stubEntryList = subPhoneTier.entryList[i:i + j]
i += j
if len(stubEntryList) == 0:
continue
syllableStart = stubEntryList[0][0]
syllableEnd = stubEntryList[-1][1]
label = "-".join([entry[2] for entry in stubEntryList])
syllableEntryList.append((syllableStart, syllableEnd, label))
if k == stressI:
tonicSEntryList.append((syllableStart, syllableEnd, 'T'))
if k == stressI:
syllablePhoneTier = phoneTier.crop(syllableStart,
syllableEnd,
"strict", False)
phoneList = [entry for entry in syllablePhoneTier.entryList
if entry[2] != '']
justPhones = [phone for _, _, phone in phoneList]
cvList = pronunciationtools.simplifyPronunciation(justPhones)
try:
tmpStressJ = cvList.index('V')
except ValueError:
for char in [u'r', u'n', u'l']:
if char in cvList:
tmpStressJ = cvList.index(char)
break
syllableTier = tgio.IntervalTier('syllable', syllableEntryList,
minT, maxT)
tonicSTier = tgio.IntervalTier('tonicSyllable', tonicSEntryList,
minT, maxT)
tonicPTier = tgio.IntervalTier('tonicVowel', tonicPEntryList,
minT, maxT)
syllableTG = tgio.Textgrid()
syllableTG.addTier(syllableTier)
syllableTG.addTier(tonicSTier)
syllableTG.addTier(tonicPTier)
return syllableTG
|
function
|
python
| 774 |
def write_index(filepath, repo, version=-1):
if version == -1:
version = 1
try:
cls = globals()['PackagesCacheV%i' % version]
except KeyError:
raise ValueError("unknown version")
return cls.write_repo(filepath, repo)
|
function
|
python
| 775 |
func (b Blacklist) Actors(w http.ResponseWriter, actors ...string) bool {
for _, a := range actors {
if bad, err := b.actorBlacklisted(a); bad || err != nil {
b.HandleForbidden(w, err)
return true
}
}
return false
}
|
function
|
go
| 776 |
cv::Mat lanedetector::createMask(const cv::Mat inpImg) {
cv::Mat outImg;
cv::Mat mask = cv::Mat::zeros(inpImg.size(), inpImg.type());
cv::Point vertices[4] = { cv::Point(210, 650), cv::Point(550, 450), cv::Point(
717, 450), cv::Point(1280, 650) };
cv::fillConvexPoly(mask, vertices, 4, cv::Scalar(255, 0, 0));
cv::bitwise_and(inpImg, mask, outImg);
return outImg;
}
|
function
|
c++
| 777 |
func (s *stream) acceptable(segSeq seqnum.Value, segLen seqnum.Size) bool {
wnd := s.una.Size(s.end)
if wnd == 0 {
return segLen == 0 && segSeq == s.una
}
if segLen == 0 {
segLen = 1
}
return seqnum.Overlap(s.una, wnd, segSeq, segLen)
}
|
function
|
go
| 778 |
public virtual IXmlElement GetSafeElement(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
if (path.Length == 0)
{
return this;
}
if (path.StartsWith("/"))
{
return Root.GetSafeElement(path.Substring(1));
}
int of = path.IndexOf('/');
string name;
string remain;
if (of < 0)
{
name = path;
remain = null;
}
else
{
name = path.Substring(0, of);
remain = path.Substring(of + 1);
}
IXmlElement element;
if (name.Equals(".."))
{
element = Parent;
if (element == null)
{
throw new ArgumentException("Invalid path " + path);
}
}
else
{
element = GetElement(name);
if (element == null)
{
element = InstantiateElement(name, null);
element.Parent = this;
if (element is SimpleElement)
{
((SimpleElement) element).IsMutable = false;
}
}
}
return remain == null ? element : element.GetSafeElement(remain);
}
|
function
|
c#
| 779 |
def combineSolids(
self, otherCQToCombine: Optional["Workplane"] = None
) -> "Workplane":
toCombine = cast(List[Solid], self.solids().vals())
if otherCQToCombine:
otherSolids = cast(List[Solid], otherCQToCombine.solids().vals())
for obj in otherSolids:
toCombine.append(obj)
if len(toCombine) < 1:
raise ValueError("Cannot Combine: at least one solid required!")
ctxSolid = self._findType(
(Solid, Compound), searchStack=False, searchParents=True
)
if ctxSolid is None:
ctxSolid = toCombine.pop(0)
s: Shape = ctxSolid
if toCombine:
s = s.fuse(*_selectShapes(toCombine))
return self.newObject([s])
|
function
|
python
| 780 |
func GetProcessCgroups(pid int) (map[string]string, error) {
fname := fmt.Sprintf("/proc/%d/cgroup", pid)
cgroups := make(map[string]string)
f, err := os.Open(fname)
if err != nil {
return nil, fmt.Errorf("Cannot open %s: %s", fname, err)
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
parts := strings.SplitN(scanner.Text(), ":", 3)
if len(parts) < 3 {
return nil, fmt.Errorf("Cannot parsing %s: unknown format", fname)
}
subsystemsParts := strings.Split(parts[1], ",")
for _, s := range subsystemsParts {
cgroups[s] = parts[2]
}
}
return cgroups, nil
}
|
function
|
go
| 781 |
static public final String arrayToRLEString(int[] a) {
StringBuilder buffer = new StringBuilder();
appendInt(buffer, a.length);
int runValue = a[0];
int runLength = 1;
for (int i=1; i<a.length; ++i) {
int s = a[i];
if (s == runValue && runLength < 0xFFFF) {
++runLength;
} else {
encodeRun(buffer, runValue, runLength);
runValue = s;
runLength = 1;
}
}
encodeRun(buffer, runValue, runLength);
return buffer.toString();
}
|
function
|
java
| 782 |
class PartiallyObservable:
"""A domain must inherit this class if it is partially observable.
"Partially observable" means that the observation provided to the agent is computed from (but generally not equal
to) the internal state of the domain. Additionally, according to literature, a partially observable domain must
provide the probability distribution of the observation given a state and action.
"""
@autocastable
def get_observation_space(self) -> D.T_agent[Space[D.T_observation]]:
"""Get the (cached) observation space (finite or infinite set).
By default, #PartiallyObservable.get_observation_space() internally
calls #PartiallyObservable._get_observation_space_() the first time and automatically caches its value to make
future calls more efficient (since the observation space is assumed to be constant).
# Returns
The observation space.
"""
return self._get_observation_space()
@functools.lru_cache()
def _get_observation_space(self) -> D.T_agent[Space[D.T_observation]]:
"""Get the (cached) observation space (finite or infinite set).
By default, #PartiallyObservable._get_observation_space() internally
calls #PartiallyObservable._get_observation_space_() the first time and automatically caches its value to make
future calls more efficient (since the observation space is assumed to be constant).
# Returns
The observation space.
"""
return self._get_observation_space_()
def _get_observation_space_(self) -> D.T_agent[Space[D.T_observation]]:
"""Get the observation space (finite or infinite set).
This is a helper function called by default from #PartiallyObservable._get_observation_space(), the difference
being that the result is not cached here.
!!! tip
The underscore at the end of this function's name is a convention to remind that its result should be
constant.
# Returns
The observation space.
"""
raise NotImplementedError
@autocastable
def is_observation(self, observation: D.T_agent[D.T_observation]) -> bool:
"""Check that an observation indeed belongs to the domain observation space.
!!! tip
By default, this function is implemented using the #skdecide.core.Space.contains() function on the domain
observation space provided by #PartiallyObservable.get_observation_space(), but it can be overridden for
faster implementations.
# Parameters
observation: The observation to consider.
# Returns
True if the observation belongs to the domain observation space (False otherwise).
"""
return self._is_observation(observation)
def _is_observation(self, observation: D.T_agent[D.T_observation]) -> bool:
"""Check that an observation indeed belongs to the domain observation space.
!!! tip
By default, this function is implemented using the #skdecide.core.Space.contains() function on the domain
observation space provided by #PartiallyObservable._get_observation_space(), but it can be overridden for
faster implementations.
# Parameters
observation: The observation to consider.
# Returns
True if the observation belongs to the domain observation space (False otherwise).
"""
observation_space = self._get_observation_space()
if self.T_agent == Union:
return observation_space.contains(observation)
else: # StrDict
return all(observation_space[k].contains(v) for k, v in observation.items())
@autocastable
def get_observation_distribution(
self,
state: D.T_state,
action: Optional[D.T_agent[D.T_concurrency[D.T_event]]] = None,
) -> Distribution[D.T_agent[D.T_observation]]:
"""Get the probability distribution of the observation given a state and action.
In mathematical terms (discrete case), given an action $a$, this function represents: $P(O|s, a)$,
where $O$ is the random variable of the observation.
# Parameters
state: The state to be observed.
action: The last applied action (or None if the state is an initial state).
# Returns
The probability distribution of the observation.
"""
return self._get_observation_distribution(state, action)
def _get_observation_distribution(
self,
state: D.T_state,
action: Optional[D.T_agent[D.T_concurrency[D.T_event]]] = None,
) -> Distribution[D.T_agent[D.T_observation]]:
"""Get the probability distribution of the observation given a state and action.
In mathematical terms (discrete case), given an action $a$, this function represents: $P(O|s, a)$,
where $O$ is the random variable of the observation.
# Parameters
state: The state to be observed.
action: The last applied action (or None if the state is an initial state).
# Returns
The probability distribution of the observation.
"""
raise NotImplementedError
|
class
|
python
| 783 |
class MikaThingRuntimeOperation:
"""
Class runs the continous operation of polling the attached Phidget devices
and submits the instruments readings to a remote logging serverself.
When the Unix environment sends a `SIGINT` or `SIGTERM` signal, this class
will gracefully shutdown by shutting down the Phidgets first before closing.
"""
app_data_interval = 0
humidity_dao = None
temperature_dao = None
storage_dao = None
is_running = False
def __init__(self):
# Setup all our instrument's sensor(s).
self.humidity_dao = HumiditySensorAccessObject.getInstance()
self.humidity_dao.setOnHumidityChangeHandlerFunc(None)
self.humidity_dao.beginOperation()
self.temperature_dao = TemperatureSensorAccessObject.getInstance()
self.temperature_dao.setOnTemperatureChangeHandlerFunc(None)
self.temperature_dao.beginOperation()
self.storage_dao = PersistentStorageDataAccessObject.getInstance()
self.storage_dao.beginOperation()
# Variable controls what time the application will start on, for example if
# this value will be 5 then the acceptable times could be: 1:00 AM, 1:05 AM,
# 1:10 AM, etc.
self.app_data_interval = int(os.getenv("APPLICATION_DATA_INTERVAL_IN_MINUTES"))
# Integrate this code with our Unix environment so when a kill command
# is sent to this application then our code will gracefully exit.
signal.signal(signal.SIGINT, self.exitGracefully)
signal.signal(signal.SIGTERM, self.exitGracefully)
def exitGracefully(self,signum, frame):
self.is_running = False
def start(self):
self.is_running = True
def shutdown(self):
# Gracefully disconnect our application with the hardware devices.
self.humidity_dao.terminateOperation()
self.temperature_dao.terminateOperation()
self.storage_dao.terminateOperation()
def runOnMainLoop(self):
# We will continue running the mainloop until our class indicates we
# should stop with the `is_running` value set to `False`. This valuse
# will be set to `False` if the class detects a `SIGINT` or `SIGTERM`
# signal from the ``Linux environment.
while self.is_running:
# The following code block will get the current UTC datetime and
# make sure the fetched datatime is in sync with our applications
# fetch interval clock. For example, if our fetch interval is "5"
# then the application will poll the sensors at time intervals of
# 1:00, 1:05, 1:10, 1:15, 1:20, etc.
now_dt = datetime.datetime.utcnow()
now_ts = now_dt.replace(tzinfo=timezone.utc).timestamp()
if now_dt.second == 0:
if now_dt.minute % self.app_data_interval == 0 or now_dt.minute == 0:
try:
humidity_value = self.humidity_dao.getRelativeHumidity()
temperature_value = self.temperature_dao.getTemperature()
print("Saving at:", now_dt)
print("Humidity", humidity_value, "%")
print("Temperature", temperature_value," degree C\n")
self.storage_dao.insertTimeSeriesData(1, humidity_value, now_ts)
self.storage_dao.insertTimeSeriesData(2, temperature_value, now_ts)
except Exception as e:
self.is_running = False
sys.stderr.write("Phidget Error -> Runtime Error: \n\t" + e)
# Block the mainloop for 1 second
time.sleep(1) # 1 second
# The following block of code will fetch all the time-series data
# we have stored in our local persistent storage and if there is
# any data stored then we will submit the data to our remote data
# storage service. Afterwords we will delete the data that was
# submitted.
tsd_records = self.storage_dao.fetchAllTimeSeriesData()
if tsd_records.count() > 0:
#TODO: IMPLEMENT SUBMITTING DATA TO MIKAPOST.COM
self.storage_dao.deleteSelectedTimeSeriesData(tsd_records)
|
class
|
python
| 784 |
def dfs(self, G):
def previsit(v):
nonlocal clock
nonlocal cc
pre[v] = clock
clock = clock + 1
ccnum[v] = cc
def postvisit(v):
nonlocal clock
post[v] = clock
clock += 1
def explore(v):
visited[v] = True
previsit(v)
for u in E[v]:
if not visited[u]:
explore(u)
postvisit(v)
V = G[0]
E = G[1]
pre = {}
post = {}
clock = 1
ccnum = {}
cc = 0
visited = {v: False for v in V}
for v in V:
if not visited[v]:
cc += 1
explore(v)
return pre, post, ccnum
|
function
|
python
| 785 |
protected override void InternalInitialize()
{
DbConnectionStringBuilder builder = new DbConnectionStringBuilder();
builder.ConnectionString = ConnectionString;
if (builder.ContainsKey("MultipleActiveResultSets"))
{
_supportsMARS = "True" == ((string)builder["MultipleActiveResultSets"]);
}
_supportsUpdatableCursor = false;
if (_shouldEnsureDatabase)
{
string databaseName = null;
if (builder.ContainsKey("Initial Catalog"))
{
databaseName = (string)builder["Initial Catalog"];
builder["Initial Catalog"] = "master";
}
else if (builder.ContainsKey("Database"))
{
databaseName = (string)builder["Database"];
builder["Database"] = "master";
}
if (!String.IsNullOrEmpty(databaseName))
{
if (!Parser.IsValidIdentifier(databaseName))
throw new ArgumentException("Database name specified in store connection string is not a valid identifier.");
try
{
#if USESQLCONNECTION
using (MSSQLConnection connection = new MSSQLConnection(builder.ConnectionString))
{
connection.Execute(String.Format("if not exists (select * from sysdatabases where name = '{0}') create database {0}", databaseName));
#else
SqlConnection connection = new SqlConnection(builder.ConnectionString);
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = String.Format("if not exists (select * from sysdatabases where name = '{0}') create database {0}", databaseName);
command.ExecuteNonQuery();
#endif
}
}
catch
{
}
}
}
}
|
function
|
c#
| 786 |
public static void handleGesture(final String gesture) {
final String singlePressAction = pref.getString("hcp_gestures_single_press",
sActionsPlayPause);
final String doublePressAction = pref.getString("hcp_gestures_double_press",
sActionsNext);
final String triplePressAction = pref.getString("hcp_gestures_triple_press",
sActionsPrevious);
if (gesture == "single") {
execAction(singlePressAction);
} else if (gesture == "double") {
execAction(doublePressAction);
} else if (gesture == "triple") {
execAction(triplePressAction);
}
}
|
function
|
java
| 787 |
protected String buildMessage()
{
StringBuilder messageFormatBuilder = new StringBuilder();
List<String> messageArgs = new ArrayList<String>();
messageFormatBuilder.append("Client App (%s) is requesting the following permissions.");
messageArgs.add(mClientName);
messageFormatBuilder.append("[Requested scopes]: %s");
messageArgs.add(extractScopeNames());
if (mBindingMessage != null)
{
messageFormatBuilder.append("[Binding message]: %s");
messageArgs.add(mBindingMessage);
}
return String.format(messageFormatBuilder.toString(), messageArgs.toArray());
}
|
function
|
java
| 788 |
HRESULT CRecoGrammar::UnloadCmd()
{
SPAUTO_OBJ_LOCK;
SPDBG_FUNC("CRecoGrammar::UnloadCmd");
HRESULT hr = S_OK;
if ( m_pCRulesWeak )
{
m_pCRulesWeak->InvalidateRules();
}
m_cpCompiler.Release();
CBaseGrammar::Clear();
if (m_fCmdLoaded)
{
ENGINETASK Task;
memset(&Task, 0, sizeof(Task));
Task.eTask = EGT_UNLOADCMD;
hr = CallEngine(&Task);
m_fProprietaryCmd = FALSE;
m_fCmdLoaded = FALSE;
}
SPDBG_REPORT_ON_FAIL( hr );
return hr;
}
|
function
|
c++
| 789 |
public static T? GetEnumNullable<T>(this object value) where T : struct
{
if (!typeof(T).IsEnum)
throw new ArgumentException(string.Format(Properties.Resources.TypeConverters_ValueIsNotEnumeration,
typeof(T).FullName));
if (value.IsNull()) return null;
int intValue = 0;
bool success = false;
try
{
intValue = value.GetInt32();
success = true;
}
catch (Exception) { }
if (success)
{
if (!Enum.IsDefined(typeof(T), intValue))
throw new FormatException(string.Format(Properties.Resources.TypeConverters_EnumNumericValueInvalid,
intValue.ToString(), typeof(T).Name));
return (T)(object)intValue;
}
if (TryReadString(value, out string stringValue) && !stringValue.IsNullOrWhiteSpace())
{
try
{
return (T)Enum.Parse(typeof(T), stringValue.Trim(), true);
}
catch (Exception)
{
throw new FormatException(string.Format(Properties.Resources.TypeConverters_EnumStringValueInvalid,
stringValue, typeof(T).Name));
}
}
throw new FormatException(string.Format(Properties.Resources.TypeConverters_InvalidFormatException,
value.GetType().Name, typeof(T).Name, value.ToString()));
}
|
function
|
c#
| 790 |
protected override void OnCreate()
{
base.OnCreate();
appWindow = Window.Instance;
appWindow.BackgroundColor = Color.White;
appWindow.KeyEvent += OnKeyEvent;
appWindow.TouchEvent += OnWindowTouched;
ImageView background = new ImageView(DirectoryInfo.Resource + "/images/bg.png");
appWindow.Add(background);
background.Size2D = new Size2D(appWindow.Size.Width, appWindow.Size.Height);
background.Position2D = new Position2D(0, 0);
menuLayer = new Layer();
appWindow.AddLayer(menuLayer);
TextLabel leftLabel = new TextLabel("Tap left side of the screen to show menu");
leftLabel.Size2D = new Size2D(appWindow.Size.Width / 2 - 40, appWindow.Size.Height);
leftLabel.Position2D = new Position2D(20, 0);
leftLabel.HorizontalAlignment = HorizontalAlignment.Center;
leftLabel.VerticalAlignment = VerticalAlignment.Center;
leftLabel.MultiLine = true;
background.Add(leftLabel);
TextLabel rightLabel = new TextLabel("Tap right side of the screen to hide menu");
rightLabel.Size2D = new Size2D(appWindow.Size.Width / 2 - 40, appWindow.Size.Height);
rightLabel.Position2D = new Position2D(appWindow.Size.Width / 2 + 20, 0);
rightLabel.HorizontalAlignment = HorizontalAlignment.Center;
rightLabel.VerticalAlignment = VerticalAlignment.Center;
rightLabel.MultiLine = true;
background.Add(rightLabel);
menu = new View();
menu.BackgroundColor = new Color(0.6f, 0.6f, 0.6f, 0.5f);
menu.Size2D = new Size2D(100, appWindow.Size.Height);
menuLayer.Add(menu);
AddIcons(menu);
}
|
function
|
c#
| 791 |
def has_edge(self, first, second):
has_connexion = False
if self.contains_vertex(first) and self.contains_vertex(second):
if self.__is_directed:
has_connexion = second in self.__data[first]
else:
has_connexion = first in self.__data[second] and second in self.__data[first]
return has_connexion
|
function
|
python
| 792 |
private void VerifyResponse(HttpResponseMessage response)
{
if (response.StatusCode == HttpStatusCode.Forbidden)
{
throw new InvalidOperationException("Received 403 Forbidden response from Lavalink node. Make sure you are using the right password.");
}
response.EnsureSuccessStatusCode();
if (!response.Headers.TryGetValues(VersionHeaderName, out var values))
{
_logger?.Log(this, string.Format("Expected header `{0}` on Lavalink HTTP response. Make sure you're using the Lavalink-Server >= 3.0", VersionHeaderName), LogLevel.Warning);
return;
}
var rawVersion = values.Single();
if (!int.TryParse(rawVersion, out var version) || version <= 2)
{
_logger?.Log(this, string.Format("Invalid version {0}, supported version >= 3. Make sure you're using the Lavalink-Server >= 3.0", version), LogLevel.Warning);
}
}
|
function
|
c#
| 793 |
pub fn increase_space_density(&mut self, id: ID) -> Result<(ID, Vec<ID>, Vec<(ID, ID)>)> {
if self.space_exists(id) {
let space = self.spaces[&id].clone();
let subs = self.dimensions + 1;
let substates = space.state().subdivide(subs);
let spaces = substates
.iter()
.map(|substate| Space::new(ID::new(), substate.clone()))
.collect::<Vec<Space<S>>>();
for s in &spaces {
let id = s.id();
self.spaces.insert(id, s.clone());
self.graph.add_node(id);
self.space_ids.insert(id);
}
for a in &spaces {
let aid = a.id();
for b in &spaces {
let bid = b.id();
if aid != bid {
self.graph.add_edge(aid, bid, ());
}
}
}
let neighbors = self.graph.neighbors(id).collect::<Vec<ID>>();
let pairs = neighbors
.iter()
.enumerate()
.map(|(i, n)| {
let t = spaces[i].id();
self.graph.remove_edge(*n, id);
self.graph.add_edge(*n, t, ());
(*n, t)
})
.collect::<Vec<(ID, ID)>>();
self.space_ids.remove(&id);
self.spaces.remove(&id);
let space_ids = spaces.iter().map(|s| s.id()).collect::<Vec<ID>>();
Ok((id, space_ids, pairs))
} else {
Err(QDFError::SpaceDoesNotExists(id))
}
}
|
function
|
rust
| 794 |
func Pattern(cfg *Config, word *syntax.Word) (string, error) {
cfg = prepareConfig(cfg)
field, err := cfg.wordField(word.Parts, quoteNone)
if err != nil {
return "", err
}
buf := cfg.strBuilder()
for _, part := range field {
if part.quote > quoteNone {
buf.WriteString(pattern.QuoteMeta(part.val, patMode))
} else {
buf.WriteString(part.val)
}
}
return buf.String(), nil
}
|
function
|
go
| 795 |
float ComputeGainDb(float input_level_dbfs) {
if (input_level_dbfs < -(kHeadroomDbfs + kMaxGainDb)) {
return kMaxGainDb;
}
if (input_level_dbfs < -kHeadroomDbfs) {
return -kHeadroomDbfs - input_level_dbfs;
}
RTC_DCHECK_LE(input_level_dbfs, 0.f);
return 0.f;
}
|
function
|
c++
| 796 |
func (im *Image) Text(x, y int, clr color.Color, fontSize float64,
font *truetype.Font, text string) (int, int, error) {
textClr := image.NewUniform(clr)
c := ftContext(font, fontSize)
c.SetClip(im.Bounds())
c.SetDst(im)
c.SetSrc(textClr)
pt := freetype.Pt(x, y+int(c.PointToFix32(fontSize)>>8))
newpt, err := c.DrawString(text, pt)
if err != nil {
return 0, 0, err
}
return int(newpt.X / 256), int(newpt.Y / 256), nil
}
|
function
|
go
| 797 |
function cancelAnimation() {
for (var k in this._active) {
var entries = this._active[k];
for (var j in entries) {
entries[j].animation.cancel();
}
}
this._active = {};
}
|
function
|
javascript
| 798 |
absl::optional<MirroringActivity::MirroringType> GetMirroringType(
const MediaRoute& route,
int target_tab_id) {
if (!route.is_local())
return absl::nullopt;
const auto source = route.media_source();
if (source.IsTabMirroringSource() || source.IsLocalFileSource())
return MirroringActivity::MirroringType::kTab;
if (source.IsDesktopMirroringSource())
return MirroringActivity::MirroringType::kDesktop;
if (source.url().is_valid()) {
if (source.IsCastPresentationUrl()) {
const auto cast_source = CastMediaSource::FromMediaSource(source);
if (cast_source && cast_source->ContainsStreamingApp()) {
DCHECK_GE(target_tab_id, 0);
return MirroringActivity::MirroringType::kTab;
} else {
NOTREACHED() << "Non-mirroring Cast app: " << source;
return absl::nullopt;
}
} else if (source.url().SchemeIsHTTPOrHTTPS()) {
return MirroringActivity::MirroringType::kOffscreenTab;
}
}
NOTREACHED() << "Invalid source: " << source;
return absl::nullopt;
}
|
function
|
c++
| 799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.