max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
10,786 | <reponame>subshine/tutorials<gh_stars>1000+
# View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
"""
Please note, this code is only for python 3+. If you are using python 2+, please modify the code accordingly.
"""
from __future__ import print_function
import pandas as pd
import numpy as np
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)), index=dates, columns=['A', 'B', 'C', 'D'])
df.iloc[0,1] = np.nan
df.iloc[1,2] = np.nan
print(df.dropna(axis=0, how='any')) # how={'any', 'all'}
print(df.fillna(value=0))
print(pd.isnull(df)) | 279 |
493 | <filename>case-server/src/main/java/com/xiaoju/framework/entity/persistent/Biz.java<gh_stars>100-1000
package com.xiaoju.framework.entity.persistent;
import lombok.Data;
import java.util.Date;
/**
* 文件夹
*
* 一个业务线有一条自己的文件夹数据,这里采用json去存储
*
* @author didi
* @date 2020/09/09
*/
@Data
public class Biz {
/**
* id
*/
private Long id;
/**
* 业务线id
*/
private Long productLineId;
/**
* channel 当前默认1
*/
private Integer channel;
private Integer isDelete;
private Date gmtModified;
private Date gmtCreated;
/**
* 存储的内容
*/
private String content;
}
| 334 |
349 | /*******************************************************************************
* Copyright 2011, 2012, 2013 fanfou.com, Xiaoke, Zhang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.fanfou.app.opensource.api.bean;
import java.util.Date;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.BaseColumns;
import com.fanfou.app.opensource.api.ApiParser;
import com.fanfou.app.opensource.db.Contents.DraftInfo;
/**
* @author mcxiaoke
* @version 1.0 2011.10.26
* @version 1.1 2011.11.04
* @version 2.0 2011.11.10
* @version 3.0 2011.12.21
*
*/
public class Draft implements Storable<Draft> {
public static final int TYPE_NONE = 0;
public static final int ID_NONE = 0;
public static final String TAG = Draft.class.getSimpleName();
public int id;
public String ownerId;
public String text;
public Date createdAt;
public static final Parcelable.Creator<Draft> CREATOR = new Parcelable.Creator<Draft>() {
@Override
public Draft createFromParcel(final Parcel source) {
return new Draft(source);
}
@Override
public Draft[] newArray(final int size) {
return new Draft[size];
}
};
public static Draft parse(final Cursor c) {
if (c == null) {
return null;
}
final Draft d = new Draft();
d.id = ApiParser.parseInt(c, BaseColumns._ID);
d.ownerId = ApiParser.parseString(c, DraftInfo.OWNER_ID);
d.text = ApiParser.parseString(c, DraftInfo.TEXT);
d.createdAt = ApiParser.parseDate(c, DraftInfo.CREATED_AT);
d.type = ApiParser.parseInt(c, DraftInfo.TYPE);
d.replyTo = ApiParser.parseString(c, DraftInfo.REPLY_TO);
d.filePath = ApiParser.parseString(c, DraftInfo.FILE_PATH);
return d;
}
public int type;
public String replyTo;
public String filePath;
public Draft() {
}
public Draft(final Parcel in) {
this.id = in.readInt();
this.type = in.readInt();
this.createdAt = new Date(in.readLong());
this.ownerId = in.readString();
this.text = in.readString();
this.replyTo = in.readString();
this.filePath = in.readString();
}
@Override
public int compareTo(final Draft another) {
return this.createdAt.compareTo(another.createdAt);
}
@Override
public int describeContents() {
return 0;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Draft other = (Draft) obj;
if (this.id != other.id) {
return false;
}
if (this.text == null) {
if (other.text != null) {
return false;
}
} else if (!this.text.equals(other.text)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + this.id;
result = (prime * result)
+ ((this.text == null) ? 0 : this.text.hashCode());
return result;
}
@Override
public ContentValues toContentValues() {
final ContentValues cv = new ContentValues();
cv.put(DraftInfo.OWNER_ID, this.ownerId);
cv.put(DraftInfo.TEXT, this.text);
cv.put(DraftInfo.CREATED_AT, new Date().getTime());
cv.put(DraftInfo.TYPE, this.type);
cv.put(DraftInfo.REPLY_TO, this.replyTo);
cv.put(DraftInfo.FILE_PATH, this.filePath);
return cv;
}
@Override
public String toString() {
return "id=" + this.id + " text= " + this.text + " filepath="
+ this.filePath;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(this.id);
dest.writeInt(this.type);
dest.writeLong(this.createdAt.getTime());
dest.writeString(this.ownerId);
dest.writeString(this.text);
dest.writeString(this.replyTo);
dest.writeString(this.filePath);
}
}
| 2,035 |
1,233 | <filename>mantis-control-plane/mantis-control-plane-server/src/main/java/io/mantisrx/master/api/akka/route/v0/JobRoute.java<gh_stars>1000+
/*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.mantisrx.master.api.akka.route.v0;
import static akka.http.javadsl.server.PathMatchers.segment;
import static akka.http.javadsl.server.directives.CachingDirectives.alwaysCache;
import static io.mantisrx.master.api.akka.route.utils.JobRouteUtils.createListJobIdsRequest;
import static io.mantisrx.master.api.akka.route.utils.JobRouteUtils.createListJobsRequest;
import static io.mantisrx.master.api.akka.route.utils.JobRouteUtils.createWorkerStatusRequest;
import static io.mantisrx.master.jobcluster.proto.JobClusterManagerProto.ListArchivedWorkersRequest.DEFAULT_LIST_ARCHIVED_WORKERS_LIMIT;
import akka.actor.ActorSystem;
import akka.http.caching.javadsl.Cache;
import akka.http.javadsl.model.HttpHeader;
import akka.http.javadsl.model.HttpMethods;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.Uri;
import akka.http.javadsl.server.ExceptionHandler;
import akka.http.javadsl.server.PathMatcher0;
import akka.http.javadsl.server.PathMatchers;
import akka.http.javadsl.server.RequestContext;
import akka.http.javadsl.server.Route;
import akka.http.javadsl.server.RouteResult;
import akka.http.javadsl.unmarshalling.StringUnmarshallers;
import akka.http.javadsl.unmarshalling.Unmarshaller;
import akka.japi.JavaPartialFunction;
import io.mantisrx.common.metrics.Counter;
import io.mantisrx.common.metrics.Metrics;
import io.mantisrx.common.metrics.MetricsRegistry;
import io.mantisrx.master.api.akka.route.Jackson;
import io.mantisrx.master.api.akka.route.handlers.JobRouteHandler;
import io.mantisrx.master.api.akka.route.proto.JobClusterProtoAdapter;
import io.mantisrx.master.jobcluster.job.MantisJobMetadataView;
import io.mantisrx.master.jobcluster.job.worker.WorkerHeartbeat;
import io.mantisrx.master.jobcluster.proto.BaseResponse;
import io.mantisrx.master.jobcluster.proto.JobClusterManagerProto;
import io.mantisrx.master.jobcluster.proto.JobClusterManagerProto.KillJobRequest;
import io.mantisrx.master.jobcluster.proto.JobClusterManagerProto.ListArchivedWorkersRequest;
import io.mantisrx.master.jobcluster.proto.JobClusterManagerProto.ResubmitWorkerRequest;
import io.mantisrx.master.jobcluster.proto.JobClusterManagerProto.ScaleStageRequest;
import io.mantisrx.server.core.PostJobStatusRequest;
import io.mantisrx.server.master.config.ConfigurationProvider;
import io.mantisrx.server.master.config.MasterConfiguration;
import io.mantisrx.server.master.domain.DataFormatAdapter;
import io.mantisrx.server.master.domain.JobId;
import io.mantisrx.server.master.scheduler.WorkerEvent;
import io.mantisrx.server.master.store.MantisWorkerMetadataWritable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JobRoute extends BaseRoute {
private static final Logger logger = LoggerFactory.getLogger(JobRoute.class);
private final JobRouteHandler jobRouteHandler;
private final Metrics metrics;
private final Counter jobListGET;
private final Counter jobListJobIdGET;
private final Counter jobListRegexGET;
private final Counter jobListLabelMatchGET;
private final Counter jobArchivedWorkersGET;
private final Counter jobArchivedWorkersGETInvalid;
private final Counter workerHeartbeatStatusPOST;
private final Counter workerHeartbeatSkipped;
private final Cache<Uri, RouteResult> cache;
private final JavaPartialFunction<RequestContext, Uri> requestUriKeyer = new JavaPartialFunction<RequestContext, Uri>() {
public Uri apply(RequestContext in, boolean isCheck) {
final HttpRequest request = in.getRequest();
final boolean isGet = request.method() == HttpMethods.GET;
if (isGet) {
return request.getUri();
} else {
throw noMatch();
}
}
};
public JobRoute(final JobRouteHandler jobRouteHandler, final ActorSystem actorSystem) {
this.jobRouteHandler = jobRouteHandler;
MasterConfiguration config = ConfigurationProvider.getConfig();
this.cache = createCache(actorSystem, config.getApiCacheMinSize(), config.getApiCacheMaxSize(),
config.getApiCacheTtlMilliseconds());
Metrics m = new Metrics.Builder()
.id("V0JobRoute")
.addCounter("jobListGET")
.addCounter("jobListJobIdGET")
.addCounter("jobListRegexGET")
.addCounter("jobListLabelMatchGET")
.addCounter("jobArchivedWorkersGET")
.addCounter("jobArchivedWorkersGETInvalid")
.addCounter("workerHeartbeatStatusPOST")
.addCounter("workerHeartbeatSkipped")
.build();
this.metrics = MetricsRegistry.getInstance().registerAndGet(m);
this.jobListGET = metrics.getCounter("jobListGET");
this.jobListJobIdGET = metrics.getCounter("jobListJobIdGET");
this.jobListRegexGET = metrics.getCounter("jobListRegexGET");
this.jobListLabelMatchGET = metrics.getCounter("jobListLabelMatchGET");
this.jobArchivedWorkersGET = metrics.getCounter("jobArchivedWorkersGET");
this.jobArchivedWorkersGETInvalid = metrics.getCounter("jobArchivedWorkersGETInvalid");
this.workerHeartbeatStatusPOST = metrics.getCounter("workerHeartbeatStatusPOST");
this.workerHeartbeatSkipped = metrics.getCounter("workerHeartbeatSkipped");
}
private static final PathMatcher0 API_JOBS = segment("api").slash("jobs");
private static final HttpHeader ACCESS_CONTROL_ALLOW_ORIGIN_HEADER =
HttpHeader.parse("Access-Control-Allow-Origin", "*");
private static final Iterable<HttpHeader> DEFAULT_RESPONSE_HEADERS = Arrays.asList(
ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
public static final String KILL_ENDPOINT = "kill";
public static final String RESUBMIT_WORKER_ENDPOINT = "resubmitWorker";
public static final String SCALE_STAGE_ENDPOINT = "scaleStage";
public static final PathMatcher0 STATUS_ENDPOINT = segment("api").slash("postjobstatus");
/**
* Route that returns
* - a list of Job Ids only if 'jobIdsOnly' query param is set
* - a list of compact Job Infos if 'compact' query param is set
* - a list of Job metadatas otherwise
* The above lists are filtered and returned based on other criteria specified in the List request
* like stageNumber, workerIndex, workerNumber, matchingLabels, regex, activeOnly, jobState, workerState, limit
*
* @param regex the regex to match against Job IDs to return in response
* @return Route job list route
*/
private Route jobListRoute(final Optional<String> regex) {
return parameterOptional(StringUnmarshallers.BOOLEAN, "jobIdsOnly", (jobIdsOnly) ->
parameterOptional(StringUnmarshallers.BOOLEAN, "compact", (isCompact) ->
parameterMultiMap(params -> {
if (jobIdsOnly.isPresent() && jobIdsOnly.get()) {
logger.debug("/api/jobs/list jobIdsOnly called");
return alwaysCache(cache, requestUriKeyer, () ->
extractUri(uri -> completeAsync(
jobRouteHandler.listJobIds(createListJobIdsRequest(params, regex, true)),
resp -> completeOK(
resp.getJobIds().stream()
.map(jobId -> jobId.getJobId())
.collect(Collectors.toList()),
Jackson.marshaller()))));
}
if (isCompact.isPresent() && isCompact.get()) {
logger.debug("/api/jobs/list compact called");
return alwaysCache(cache, requestUriKeyer, () ->
extractUri(uri -> completeAsync(
jobRouteHandler.listJobs(createListJobsRequest(params, regex, true)),
resp -> completeOK(
resp.getJobList()
.stream()
.map(jobMetadataView -> JobClusterProtoAdapter.toCompactJobInfo(jobMetadataView))
.collect(Collectors.toList()),
Jackson.marshaller()))));
} else {
logger.debug("/api/jobs/list called");
return alwaysCache(cache, requestUriKeyer, () ->
extractUri(uri -> completeAsync(
jobRouteHandler.listJobs(createListJobsRequest(params, regex, true)),
resp -> completeOK(
resp.getJobList(),
Jackson.marshaller()))));
}
})
)
);
}
private Route getJobRoutes() {
return route(
path(STATUS_ENDPOINT, () ->
post(() ->
decodeRequest(() ->
entity(Unmarshaller.entityToString(), req -> {
if (logger.isDebugEnabled()) {
logger.debug("/api/postjobstatus called {}", req);
}
try {
workerHeartbeatStatusPOST.increment();
PostJobStatusRequest postJobStatusRequest = Jackson.fromJSON(req, PostJobStatusRequest.class);
WorkerEvent workerStatusRequest = createWorkerStatusRequest(postJobStatusRequest);
if (workerStatusRequest instanceof WorkerHeartbeat) {
if (!ConfigurationProvider.getConfig().isHeartbeatProcessingEnabled()) {
// skip heartbeat processing
if (logger.isTraceEnabled()) {
logger.trace("skipped heartbeat event {}", workerStatusRequest);
}
workerHeartbeatSkipped.increment();
return complete(StatusCodes.OK);
}
}
return completeWithFuture(
jobRouteHandler.workerStatus(workerStatusRequest)
.thenApply(this::toHttpResponse));
} catch (IOException e) {
logger.warn("Error handling job status {}", req, e);
return complete(StatusCodes.BAD_REQUEST, "{\"error\": \"invalid JSON payload to post job status\"}");
}
})
))),
pathPrefix(API_JOBS, () -> route(
post(() -> route(
path(KILL_ENDPOINT, () ->
decodeRequest(() ->
entity(Unmarshaller.entityToString(), req -> {
logger.debug("/api/jobs/kill called {}", req);
try {
final KillJobRequest killJobRequest = Jackson.fromJSON(req, KillJobRequest.class);
return completeWithFuture(
jobRouteHandler.kill(killJobRequest)
.thenApply(resp -> {
if (resp.responseCode == BaseResponse.ResponseCode.SUCCESS) {
return new JobClusterManagerProto.KillJobResponse(resp.requestId, resp.responseCode,
resp.getState(), "[\""+ resp.getJobId().getId() +" Killed\"]", resp.getJobId(), resp.getUser());
} else if (resp.responseCode == BaseResponse.ResponseCode.CLIENT_ERROR) {
// for backwards compatibility with old master
return new JobClusterManagerProto.KillJobResponse(resp.requestId, BaseResponse.ResponseCode.SUCCESS,
resp.getState(), "[\""+ resp.message +" \"]", resp.getJobId(), resp.getUser());
}
return resp;
})
.thenApply(this::toHttpResponse));
} catch (IOException e) {
logger.warn("Error on job kill {}", req, e);
return complete(StatusCodes.BAD_REQUEST, "{\"error\": \"invalid json payload to kill job\"}");
}
})
)),
path(RESUBMIT_WORKER_ENDPOINT, () ->
decodeRequest(() ->
entity(Unmarshaller.entityToString(), req -> {
logger.debug("/api/jobs/resubmitWorker called {}", req);
try {
final ResubmitWorkerRequest resubmitWorkerRequest = Jackson.fromJSON(req, ResubmitWorkerRequest.class);
return completeWithFuture(
jobRouteHandler.resubmitWorker(resubmitWorkerRequest)
.thenApply(this::toHttpResponse));
} catch (IOException e) {
logger.warn("Error on worker resubmit {}", req, e);
return complete(StatusCodes.BAD_REQUEST, "{\"error\": \"invalid json payload to resubmit worker\"}");
}
})
)),
path(SCALE_STAGE_ENDPOINT, () ->
decodeRequest(() ->
entity(Unmarshaller.entityToString(), req -> {
logger.debug("/api/jobs/scaleStage called {}", req);
try {
ScaleStageRequest scaleStageRequest = Jackson.fromJSON(req, ScaleStageRequest.class);
int numWorkers = scaleStageRequest.getNumWorkers();
int maxWorkersPerStage = ConfigurationProvider.getConfig().getMaxWorkersPerStage();
if (numWorkers > maxWorkersPerStage) {
logger.warn("rejecting ScaleStageRequest {} with invalid num workers", scaleStageRequest);
return complete(StatusCodes.BAD_REQUEST, "{\"error\": \"num workers must be less than " + maxWorkersPerStage + "\"}");
}
return completeWithFuture(
jobRouteHandler.scaleStage(scaleStageRequest)
.thenApply(this::toHttpResponse));
} catch (IOException e) {
logger.warn("Error scaling stage {}", req, e);
return complete(StatusCodes.BAD_REQUEST,
"{\"error\": \"invalid json payload to scale stage " + e.getMessage() +"\"}");
}
})
))
// TODO path("updateScalingPolicy", () ->
// entity(Jackson.unmarshaller(UpdateJobClusterRequest.class), req -> {
// logger.info("/api/jobs/kill called {}", req);
// return completeWithFuture(
// jobRouteHandler.kill(req)
// .thenApply(this::toHttpResponse));
// })
// )
)),
get(() -> route(
// Context from old mantis master:
// list all jobs activeOnly = true
// optional boolean 'compact' query param to return compact job infos if set
// For compact,
// - optional 'limit' query param
// - optional 'jobState' query param
// For non compact,
// - optional boolean 'jobIdsOnly' query param to return only the job Ids if set
// - optional int 'stageNumber' query param to filter for stage number
// - optional int 'workerIndex' query param to filter for worker index
// - optional int 'workerNumber' query param to filter for worker number
// - optional int 'workerState' query param to filter for worker state
// list/all - list all jobs activeOnly=false with above query parameters
// list/matching/<regex> - if optional regex param specified, propagate regex
// else list all jobs activeOnly=false with above query parameters
// list/matchinglabels
// - optional labels query param
// - optional labels.op query param - default value is 'or' if not specified (other possible value is 'and'
path(segment("list"), () -> {
jobListGET.increment();
return jobListRoute(Optional.empty());
}),
path(segment("list").slash("matchinglabels"), () -> {
jobListLabelMatchGET.increment();
return jobListRoute(Optional.empty());
}),
path(segment("list").slash(PathMatchers.segment()), (jobId) -> {
logger.debug("/api/jobs/list/{} called", jobId);
jobListJobIdGET.increment();
return completeAsync(
jobRouteHandler.getJobDetails(new JobClusterManagerProto.GetJobDetailsRequest("masterAPI", jobId)),
resp -> {
Optional<MantisJobMetadataView> mantisJobMetadataView = resp.getJobMetadata()
.map(metaData -> new MantisJobMetadataView(metaData, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), false));
return completeOK(mantisJobMetadataView,
Jackson.marshaller());
});
}),
path(segment("list").slash("matching").slash(PathMatchers.segment()), (regex) -> {
jobListRegexGET.increment();
return jobListRoute(Optional.ofNullable(regex)
.filter(r -> !r.isEmpty()));
}),
path(segment("archived").slash(PathMatchers.segment()), (jobId) ->
parameterOptional(StringUnmarshallers.INTEGER, "limit", (limit) -> {
jobArchivedWorkersGET.increment();
Optional<JobId> jobIdO = JobId.fromId(jobId);
if (jobIdO.isPresent()) {
ListArchivedWorkersRequest req = new ListArchivedWorkersRequest(jobIdO.get(),
limit.orElse(DEFAULT_LIST_ARCHIVED_WORKERS_LIMIT));
return alwaysCache(cache, requestUriKeyer, () ->
extractUri(uri -> completeAsync(
jobRouteHandler.listArchivedWorkers(req),
resp -> {
List<MantisWorkerMetadataWritable> workers = resp.getWorkerMetadata().stream()
.map(wm -> DataFormatAdapter.convertMantisWorkerMetadataToMantisWorkerMetadataWritable(wm))
.collect(Collectors.toList());
return completeOK(workers,
Jackson.marshaller());
})));
} else {
return complete(StatusCodes.BAD_REQUEST,
"error: 'archived/<jobId>' request must include a valid jobId");
}
})
),
path(segment("archived"), () -> {
jobArchivedWorkersGETInvalid.increment();
return complete(StatusCodes.BAD_REQUEST,
"error: 'archived' Request must include jobId");
})
)))
));
}
public Route createRoute(Function<Route, Route> routeFilter) {
logger.info("creating routes");
final ExceptionHandler genericExceptionHandler = ExceptionHandler.newBuilder()
.match(Exception.class, x -> {
logger.error("got exception", x);
return complete(StatusCodes.INTERNAL_SERVER_ERROR, "{\"error\": \"" + x.getMessage() + "\"}");
})
.build();
return respondWithHeaders(DEFAULT_RESPONSE_HEADERS, () -> handleExceptions(genericExceptionHandler, () -> routeFilter.apply(getJobRoutes())));
}
}
| 11,576 |
342 | <gh_stars>100-1000
# coding=utf-8
true, false = True, False
MAIN_TOKENS = {
'SENT': {
'name': 'SENTinel',
'address': '0xa44e5137293e855b1b7bc7e2c6f8cd796ffcb037'.lower(),
'abi': [{"constant": true, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "approve",
"outputs": [{"name": "success",
"type": "bool"}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "bytes32"}], "name": "services",
"outputs": [{"name": "", "type": "address"}], "payable": false, "stateMutability": "view",
"type": "function"},
{"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"name": "", "type": "uint256"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_from", "type": "address"}, {"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}], "name": "transferFrom", "outputs": [
{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [], "name": "decimals", "outputs": [{"name": "", "type": "uint8"}],
"payable": false, "stateMutability": "view", "type": "function"},
{"constant": false, "inputs": [{"name": "_value", "type": "uint256"}], "name": "burn",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}], "name": "balanceOf",
"outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view",
"type": "function"}, {"constant": false, "inputs": [{"name": "_from", "type": "address"},
{"name": "_value", "type": "uint256"}],
"name": "burnFrom", "outputs": [{"name": "success", "type": "bool"}],
"payable": false, "stateMutability": "nonpayable", "type": "function"},
{"constant": false,
"inputs": [{"name": "_serviceName", "type": "bytes32"}, {"name": "_from", "type": "address"},
{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}],
"name": "payService", "outputs": [], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [], "name": "owner", "outputs": [{"name": "", "type": "address"}],
"payable": false, "stateMutability": "view", "type": "function"},
{"constant": true, "inputs": [], "name": "symbol", "outputs": [{"name": "", "type": "string"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "transfer",
"outputs": [], "payable": false,
"stateMutability": "nonpayable",
"type": "function"},
{"constant": false,
"inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"},
{"name": "_extraData", "type": "bytes"}], "name": "approveAndCall",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}, {"name": "", "type": "address"}],
"name": "allowance", "outputs": [{"name": "", "type": "uint256"}], "payable": false,
"stateMutability": "view", "type": "function"},
{"constant": false, "inputs": [{"name": "_owner", "type": "address"}], "name": "transferOwnership",
"outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"},
{"constant": false, "inputs": [{"name": "_serviceName", "type": "bytes32"},
{"name": "_serviceAddress", "type": "address"}], "name": "deployService",
"outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {
"inputs": [{"name": "_tokenName", "type": "string"}, {"name": "_tokenSymbol", "type": "string"},
{"name": "_decimals", "type": "uint8"}, {"name": "_totalSupply", "type": "uint256"}],
"payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false,
"inputs": [
{"indexed": true,
"name": "from",
"type": "address"},
{"indexed": true,
"name": "to",
"type": "address"},
{"indexed": false,
"name": "value",
"type": "uint256"}],
"name": "Transfer",
"type": "event"},
{"anonymous": false, "inputs": [{"indexed": true, "name": "from", "type": "address"},
{"indexed": false, "name": "value", "type": "uint256"}], "name": "Burn",
"type": "event"}]
},
'BNB': {
'name': 'Binance Coin',
'address': '0xb8c77482e45f1f44de1745f52c74426c631bdd52'.lower(),
'abi': [{"constant": true, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}],
"payable": false, "type": "function"}, {"constant": false,
"inputs": [{"name": "_spender", "type": "address"},
{"name": "_value", "type": "uint256"}],
"name": "approve",
"outputs": [{"name": "success", "type": "bool"}],
"payable": false, "type": "function"},
{"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"name": "", "type": "uint256"}],
"payable": false, "type": "function"}, {"constant": false,
"inputs": [{"name": "_from", "type": "address"},
{"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}],
"name": "transferFrom",
"outputs": [{"name": "success", "type": "bool"}],
"payable": false, "type": "function"},
{"constant": true, "inputs": [], "name": "decimals", "outputs": [{"name": "", "type": "uint8"}],
"payable": false, "type": "function"},
{"constant": false, "inputs": [{"name": "amount", "type": "uint256"}], "name": "withdrawEther",
"outputs": [], "payable": false, "type": "function"},
{"constant": false, "inputs": [{"name": "_value", "type": "uint256"}], "name": "burn",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "type": "function"},
{"constant": false, "inputs": [{"name": "_value", "type": "uint256"}], "name": "unfreeze",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}], "name": "balanceOf",
"outputs": [{"name": "", "type": "uint256"}], "payable": false, "type": "function"},
{"constant": true, "inputs": [], "name": "owner", "outputs": [{"name": "", "type": "address"}],
"payable": false, "type": "function"},
{"constant": true, "inputs": [], "name": "symbol", "outputs": [{"name": "", "type": "string"}],
"payable": false, "type": "function"}, {"constant": false,
"inputs": [{"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}],
"name": "transfer", "outputs": [], "payable": false,
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}], "name": "freezeOf",
"outputs": [{"name": "", "type": "uint256"}], "payable": false, "type": "function"},
{"constant": false, "inputs": [{"name": "_value", "type": "uint256"}], "name": "freeze",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}, {"name": "", "type": "address"}],
"name": "allowance", "outputs": [{"name": "", "type": "uint256"}], "payable": false,
"type": "function"}, {
"inputs": [{"name": "initialSupply", "type": "uint256"}, {"name": "tokenName", "type": "string"},
{"name": "decimalUnits", "type": "uint8"}, {"name": "tokenSymbol", "type": "string"}],
"payable": false, "type": "constructor"}, {"payable": true, "type": "fallback"},
{"anonymous": false, "inputs": [{"indexed": true, "name": "from", "type": "address"},
{"indexed": true, "name": "to", "type": "address"},
{"indexed": false, "name": "value", "type": "uint256"}],
"name": "Transfer", "type": "event"}, {"anonymous": false,
"inputs": [{"indexed": true, "name": "from", "type": "address"},
{"indexed": false, "name": "value",
"type": "uint256"}], "name": "Burn",
"type": "event"}, {"anonymous": false, "inputs": [
{"indexed": true, "name": "from", "type": "address"},
{"indexed": false, "name": "value", "type": "uint256"}], "name": "Freeze", "type": "event"},
{"anonymous": false, "inputs": [{"indexed": true, "name": "from", "type": "address"},
{"indexed": false, "name": "value", "type": "uint256"}],
"name": "Unfreeze", "type": "event"}]
}
}
RINKEBY_TOKENS = {
'SENT': {
'name': 'Sentinel Test Token',
'address': '0x29317B796510afC25794E511e7B10659Ca18048B'.lower(),
'abi': [{"constant": true, "inputs": [], "name": "name", "outputs": [{"name": "", "type": "string"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "approve",
"outputs": [{"name": "success",
"type": "bool"}],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "bytes32"}], "name": "services",
"outputs": [{"name": "", "type": "address"}], "payable": false, "stateMutability": "view",
"type": "function"},
{"constant": true, "inputs": [], "name": "totalSupply", "outputs": [{"name": "", "type": "uint256"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_from", "type": "address"}, {"name": "_to", "type": "address"},
{"name": "_value", "type": "uint256"}], "name": "transferFrom", "outputs": [
{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [], "name": "decimals", "outputs": [{"name": "", "type": "uint8"}],
"payable": false, "stateMutability": "view", "type": "function"},
{"constant": false, "inputs": [{"name": "_value", "type": "uint256"}], "name": "burn",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}], "name": "balanceOf",
"outputs": [{"name": "", "type": "uint256"}], "payable": false, "stateMutability": "view",
"type": "function"}, {"constant": false, "inputs": [{"name": "_from", "type": "address"},
{"name": "_value", "type": "uint256"}],
"name": "burnFrom", "outputs": [{"name": "success", "type": "bool"}],
"payable": false, "stateMutability": "nonpayable", "type": "function"},
{"constant": false,
"inputs": [{"name": "_serviceName", "type": "bytes32"}, {"name": "_from", "type": "address"},
{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}],
"name": "payService", "outputs": [], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [], "name": "owner", "outputs": [{"name": "", "type": "address"}],
"payable": false, "stateMutability": "view", "type": "function"},
{"constant": true, "inputs": [], "name": "symbol", "outputs": [{"name": "", "type": "string"}],
"payable": false, "stateMutability": "view", "type": "function"}, {"constant": false, "inputs": [
{"name": "_to", "type": "address"}, {"name": "_value", "type": "uint256"}], "name": "transfer",
"outputs": [], "payable": false,
"stateMutability": "nonpayable",
"type": "function"},
{"constant": false,
"inputs": [{"name": "_spender", "type": "address"}, {"name": "_value", "type": "uint256"},
{"name": "_extraData", "type": "bytes"}], "name": "approveAndCall",
"outputs": [{"name": "success", "type": "bool"}], "payable": false, "stateMutability": "nonpayable",
"type": "function"},
{"constant": true, "inputs": [{"name": "", "type": "address"}, {"name": "", "type": "address"}],
"name": "allowance", "outputs": [{"name": "", "type": "uint256"}], "payable": false,
"stateMutability": "view", "type": "function"},
{"constant": false, "inputs": [{"name": "_owner", "type": "address"}], "name": "transferOwnership",
"outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"},
{"constant": false, "inputs": [{"name": "_serviceName", "type": "bytes32"},
{"name": "_serviceAddress", "type": "address"}], "name": "deployService",
"outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function"}, {
"inputs": [{"name": "_tokenName", "type": "string"}, {"name": "_tokenSymbol", "type": "string"},
{"name": "_decimals", "type": "uint8"}, {"name": "_totalSupply", "type": "uint256"}],
"payable": false, "stateMutability": "nonpayable", "type": "constructor"}, {"anonymous": false,
"inputs": [
{"indexed": true,
"name": "from",
"type": "address"},
{"indexed": true,
"name": "to",
"type": "address"},
{"indexed": false,
"name": "value",
"type": "uint256"}],
"name": "Transfer",
"type": "event"},
{"anonymous": false, "inputs": [{"indexed": true, "name": "from", "type": "address"},
{"indexed": false, "name": "value", "type": "uint256"}], "name": "Burn",
"type": "event"}]
}
}
| 12,312 |
335 | <filename>src/openmpt/sounddevice/SoundDeviceASIO.hpp
/* SPDX-License-Identifier: BSD-3-Clause */
/* SPDX-FileCopyrightText: <NAME> */
/* SPDX-FileCopyrightText: OpenMPT Project Developers and Contributors */
#pragma once
#include "openmpt/all/BuildSettings.hpp"
#ifdef MPT_WITH_ASIO
#include "SoundDevice.hpp"
#include "SoundDeviceBase.hpp"
#include "mpt/string/types.hpp"
#include "openmpt/base/Types.hpp"
#include "openmpt/logging/Logger.hpp"
#include <atomic>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include <cassert>
#include <ASIOModern/ASIO.hpp>
#include <ASIOModern/ASIOSystemWindows.hpp>
#if defined(MODPLUG_TRACKER)
#if !defined(MPT_BUILD_WINESUPPORT)
#include "../mptrack/ExceptionHandler.h"
#endif // !MPT_BUILD_WINESUPPORT
#endif // MODPLUG_TRACKER
#endif // MPT_WITH_ASIO
OPENMPT_NAMESPACE_BEGIN
namespace SoundDevice
{
#ifdef MPT_WITH_ASIO
class ASIOException
: public std::runtime_error
{
public:
ASIOException(const std::string &msg)
: std::runtime_error(msg)
{
return;
}
};
class CASIODevice
: public SoundDevice::Base
, private ASIO::Driver::CallbackHandler
{
friend class TemporaryASIODriverOpener;
protected:
std::unique_ptr<ASIO::Windows::IBufferSwitchDispatcher> m_DeferredBufferSwitchDispatcher;
std::unique_ptr<ASIO::Driver> m_Driver;
#if defined(MODPLUG_TRACKER) && !defined(MPT_BUILD_WINESUPPORT)
using CrashContext = ExceptionHandler::Context;
using CrashContextGuard = ExceptionHandler::ContextSetter;
#else // !(MODPLUG_TRACKER && !MPT_BUILD_WINESUPPORT)
struct CrashContext
{
void SetDescription(mpt::ustring)
{
return;
}
};
struct CrashContextGuard
{
CrashContextGuard(CrashContext *)
{
return;
}
};
#endif // MODPLUG_TRACKER && !MPT_BUILD_WINESUPPORT
CrashContext m_Ectx;
class ASIODriverWithContext
{
private:
ASIO::Driver *m_Driver;
CrashContextGuard m_Guard;
public:
ASIODriverWithContext(ASIO::Driver *driver, CrashContext *ectx)
: m_Driver(driver)
, m_Guard(ectx)
{
assert(driver);
assert(ectx);
}
ASIODriverWithContext(const ASIODriverWithContext &) = delete;
ASIODriverWithContext &operator=(const ASIODriverWithContext &) = delete;
ASIO::Driver *operator->()
{
return m_Driver;
}
};
ASIODriverWithContext AsioDriver()
{
assert(m_Driver);
return ASIODriverWithContext{m_Driver.get(), &m_Ectx};
}
double m_BufferLatency;
ASIO::Long m_nAsioBufferLen;
std::vector<ASIO::BufferInfo> m_BufferInfo;
bool m_BuffersCreated;
std::vector<ASIO::ChannelInfo> m_ChannelInfo;
std::vector<double> m_SampleBufferDouble;
std::vector<float> m_SampleBufferFloat;
std::vector<int16> m_SampleBufferInt16;
std::vector<int24> m_SampleBufferInt24;
std::vector<int32> m_SampleBufferInt32;
std::vector<double> m_SampleInputBufferDouble;
std::vector<float> m_SampleInputBufferFloat;
std::vector<int16> m_SampleInputBufferInt16;
std::vector<int24> m_SampleInputBufferInt24;
std::vector<int32> m_SampleInputBufferInt32;
bool m_CanOutputReady;
bool m_DeviceRunning;
uint64 m_TotalFramesWritten;
bool m_DeferredProcessing;
ASIO::BufferIndex m_BufferIndex;
std::atomic<bool> m_RenderSilence;
std::atomic<bool> m_RenderingSilence;
int64 m_StreamPositionOffset;
using AsioRequests = uint8;
struct AsioRequest
{
enum AsioRequestEnum : AsioRequests
{
LatenciesChanged = 1 << 0,
};
};
std::atomic<AsioRequests> m_AsioRequest;
using AsioFeatures = uint16;
struct AsioFeature
{
enum AsioFeatureEnum : AsioFeatures
{
ResetRequest = 1 << 0,
ResyncRequest = 1 << 1,
BufferSizeChange = 1 << 2,
Overload = 1 << 3,
SampleRateChange = 1 << 4,
DeferredProcess = 1 << 5,
};
};
mutable std::atomic<AsioFeatures> m_UsedFeatures;
static mpt::ustring AsioFeaturesToString(AsioFeatures features);
mutable std::atomic<uint32> m_DebugRealtimeThreadID;
void SetRenderSilence(bool silence, bool wait = false);
public:
CASIODevice(ILogger &logger, SoundDevice::Info info, SoundDevice::SysInfo sysInfo);
~CASIODevice();
private:
void InitMembers();
bool HandleRequests(); // return true if any work has been done
void UpdateLatency();
void InternalStopImpl(bool force);
public:
bool InternalOpen();
bool InternalClose();
void InternalFillAudioBuffer();
bool InternalStart();
void InternalStop();
bool InternalIsOpen() const { return m_BuffersCreated; }
bool InternalIsPlayingSilence() const;
void InternalStopAndAvoidPlayingSilence();
void InternalEndPlayingSilence();
bool OnIdle() { return HandleRequests(); }
SoundDevice::Caps InternalGetDeviceCaps();
SoundDevice::DynamicCaps GetDeviceDynamicCaps(const std::vector<uint32> &baseSampleRates);
bool OpenDriverSettings();
bool DebugIsFragileDevice() const;
bool DebugInRealtimeCallback() const;
SoundDevice::Statistics GetStatistics() const;
public:
static std::unique_ptr<SoundDevice::BackendInitializer> BackendInitializer() { return std::make_unique<SoundDevice::BackendInitializer>(); }
static std::vector<SoundDevice::Info> EnumerateDevices(ILogger &logger, SoundDevice::SysInfo sysInfo);
protected:
void OpenDriver();
void CloseDriver();
bool IsDriverOpen() const { return (m_Driver != nullptr); }
bool InternalHasTimeInfo() const;
SoundDevice::BufferAttributes InternalGetEffectiveBufferAttributes() const;
protected:
void FillAsioBuffer(bool useSource = true);
private:
// CallbackHandler
void MessageResetRequest() noexcept override;
bool MessageBufferSizeChange(ASIO::Long newSize) noexcept override;
bool MessageResyncRequest() noexcept override;
void MessageLatenciesChanged() noexcept override;
ASIO::Long MessageMMCCommand(ASIO::Long value, const void *message, const ASIO::Double *opt) noexcept override;
void MessageOverload() noexcept override;
ASIO::Long MessageUnknown(ASIO::MessageSelector selector, ASIO::Long value, const void *message, const ASIO::Double *opt) noexcept override;
void RealtimeSampleRateDidChange(ASIO::SampleRate sRate) noexcept override;
void RealtimeRequestDeferredProcessing(bool value) noexcept override;
void RealtimeTimeInfo(ASIO::Time time) noexcept override;
void RealtimeBufferSwitch(ASIO::BufferIndex bufferIndex) noexcept override;
void RealtimeBufferSwitchImpl(ASIO::BufferIndex bufferIndex) noexcept;
private:
void ExceptionHandler(const char *func);
};
#endif // MPT_WITH_ASIO
} // namespace SoundDevice
OPENMPT_NAMESPACE_END
| 2,246 |
1,144 | <reponame>dram/metasfresh<gh_stars>1000+
package de.metas.inoutcandidate.spi;
/*
* #%L
* de.metas.swat.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import de.metas.inoutcandidate.api.IReceiptScheduleProducerFactory;
/**
* Abstract implementation of {@link IReceiptScheduleProducer} which implements common methods.
*
* @author tsa
*
*/
public abstract class AbstractReceiptScheduleProducer implements IReceiptScheduleProducer
{
private IReceiptScheduleProducerFactory factory;
@Override
public final void setReceiptScheduleProducerFactory(IReceiptScheduleProducerFactory factory)
{
this.factory = factory;
}
@Override
public final IReceiptScheduleProducerFactory getReceiptScheduleProducerFactory()
{
return factory;
}
protected final IReceiptScheduleWarehouseDestProvider getWarehouseDestProvider()
{
return getReceiptScheduleProducerFactory().getWarehouseDestProvider();
}
}
| 486 |
852 | <filename>CommonTools/BaseParticlePropagator/src/RawParticle.cc
// -----------------------------------------------------------------------------
// Prototype for a particle class
// -----------------------------------------------------------------------------
// $Date: 2007/09/07 16:46:22 $
// $Revision: 1.13 $
// -----------------------------------------------------------------------------
// Author: <NAME> - RWTH-Aachen (Email: <EMAIL>)
// -----------------------------------------------------------------------------
#include "CommonTools/BaseParticlePropagator/interface/RawParticle.h"
#include <cmath>
RawParticle::RawParticle(const XYZTLorentzVector& p) : myMomentum(p) {}
RawParticle::RawParticle(const int id, const XYZTLorentzVector& p, double mass, double charge)
: myMomentum(p), myCharge{charge}, myMass{mass}, myId{id} {}
RawParticle::RawParticle(
const int id, const XYZTLorentzVector& p, const XYZTLorentzVector& xStart, double mass, double charge)
: myMomentum(p), myVertex{xStart}, myCharge{charge}, myMass{mass}, myId{id} {}
RawParticle::RawParticle(const XYZTLorentzVector& p, const XYZTLorentzVector& xStart, double charge)
: myMomentum(p), myVertex{xStart}, myCharge{charge} {}
RawParticle::RawParticle(double px, double py, double pz, double e, double charge)
: myMomentum(px, py, pz, e), myCharge{charge} {}
void RawParticle::setStatus(int istat) { myStatus = istat; }
void RawParticle::setMass(float m) { myMass = m; }
void RawParticle::setCharge(float q) { myCharge = q; }
void RawParticle::chargeConjugate() {
myId = -myId;
myCharge = -1 * myCharge;
}
void RawParticle::setT(const double t) { myVertex.SetE(t); }
void RawParticle::rotate(double angle, const XYZVector& raxis) {
Rotation r(raxis, angle);
XYZVector v(r * myMomentum.Vect());
setMomentum(v.X(), v.Y(), v.Z(), E());
}
void RawParticle::rotateX(double rphi) {
RotationX r(rphi);
XYZVector v(r * myMomentum.Vect());
setMomentum(v.X(), v.Y(), v.Z(), E());
}
void RawParticle::rotateY(double rphi) {
RotationY r(rphi);
XYZVector v(r * myMomentum.Vect());
setMomentum(v.X(), v.Y(), v.Z(), E());
}
void RawParticle::rotateZ(double rphi) {
RotationZ r(rphi);
XYZVector v(r * myMomentum.Vect());
setMomentum(v.X(), v.Y(), v.Z(), E());
}
void RawParticle::boost(double betax, double betay, double betaz) {
Boost b(betax, betay, betaz);
XYZTLorentzVector p(b * momentum());
setMomentum(p.X(), p.Y(), p.Z(), p.T());
}
std::ostream& operator<<(std::ostream& o, const RawParticle& p) {
o.setf(std::ios::fixed, std::ios::floatfield);
o.setf(std::ios::right, std::ios::adjustfield);
o << std::setw(4) << std::setprecision(2) << p.pid() << " (";
o << std::setw(2) << std::setprecision(2) << p.status() << "): ";
o << std::setw(10) << std::setprecision(4) << p.momentum() << " ";
o << std::setw(10) << std::setprecision(4) << p.vertex();
return o;
}
double RawParticle::et() const {
double mypp, tmpEt = -1.;
mypp = std::sqrt(momentum().mag2());
if (mypp != 0) {
tmpEt = E() * pt() / mypp;
}
return tmpEt;
}
| 1,148 |
421 | <reponame>hamarb123/dotnet-api-docs
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System::Security::Permissions;
public ref class Form1: public Form
{
protected:
TextBox^ textBox1;
// <Snippet1>
public:
[PermissionSetAttribute(SecurityAction::Demand, Name="FullTrust")]
Form1()
{
// The initial constructor code goes here.
PropertyGrid^ propertyGrid1 = gcnew PropertyGrid;
propertyGrid1->CommandsVisibleIfAvailable = true;
propertyGrid1->Location = Point( 10, 20 );
propertyGrid1->Size = System::Drawing::Size( 400, 300 );
propertyGrid1->TabIndex = 1;
propertyGrid1->Text = "Property Grid";
this->Controls->Add( propertyGrid1 );
propertyGrid1->SelectedObject = textBox1;
}
// </Snippet1>
};
| 363 |
775 | <filename>micropolis/micropolis-activity/src/tclx/src/tclxid.c
/*
* tclXid.c --
*
* Tcl commands to access getuid, setuid, getgid, setgid and friends.
*---------------------------------------------------------------------------
* Copyright 1992 <NAME> and <NAME>.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted, provided
* that the above copyright notice appear in all copies. <NAME> and
* <NAME> make no representations about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*-----------------------------------------------------------------------------
* $Id: tclXid.c,v 2.0 1992/10/16 04:50:51 markd Rel $
*-----------------------------------------------------------------------------
*/
#include "tclxint.h"
/*
* Prototypes of internal functions.
*/
static int
UseridToUsernameResult _ANSI_ARGS_((Tcl_Interp *interp,
int userId));
static int
UsernameToUseridResult _ANSI_ARGS_((Tcl_Interp *interp,
char *userName));
static int
GroupidToGroupnameResult _ANSI_ARGS_((Tcl_Interp *interp,
int groupId));
static int
GroupnameToGroupidResult _ANSI_ARGS_((Tcl_Interp *interp,
char *groupName));
/*
*-----------------------------------------------------------------------------
*
* Tcl_IdCmd --
* Implements the TCL id command:
*
* id user [name]
* id convert user <name>
*
* id userid [uid]
* id convert userid <uid>
*
* id group [name]
* id convert group <name>
*
* id groupid [gid]
* id convert groupid <gid>
*
* id process
* id process parent
* id process group
* id process group set
*
* id effective user
* id effective userid
*
* id effective group
* id effective groupid
*
* Results:
* Standard TCL results, may return the UNIX system error message.
*
*-----------------------------------------------------------------------------
*/
static int
UseridToUsernameResult (interp, userId)
Tcl_Interp *interp;
int userId;
{
struct passwd *pw = getpwuid (userId);
if (pw == NULL) {
char numBuf [32];
sprintf (numBuf, "%d", userId);
Tcl_AppendResult (interp, "unknown user id: ", numBuf, (char *) NULL);
return TCL_ERROR;
}
strcpy (interp->result, pw->pw_name);
return TCL_OK;
}
static int
UsernameToUseridResult (interp, userName)
Tcl_Interp *interp;
char *userName;
{
struct passwd *pw = getpwnam (userName);
if (pw == NULL) {
Tcl_AppendResult (interp, "unknown user id: ", userName,
(char *) NULL);
return TCL_ERROR;
}
sprintf (interp->result, "%d", pw->pw_uid);
return TCL_OK;
}
static int
GroupidToGroupnameResult (interp, groupId)
Tcl_Interp *interp;
int groupId;
{
struct group *grp = getgrgid (groupId);
if (grp == NULL) {
char numBuf [32];
sprintf (numBuf, "%d", groupId);
Tcl_AppendResult (interp, "unknown group id: ", numBuf, (char *) NULL);
return TCL_ERROR;
}
strcpy (interp->result, grp->gr_name);
return TCL_OK;
}
static int
GroupnameToGroupidResult (interp, groupName)
Tcl_Interp *interp;
char *groupName;
{
struct group *grp = getgrnam (groupName);
if (grp == NULL) {
Tcl_AppendResult (interp, "unknown group id: ", groupName,
(char *) NULL);
return TCL_ERROR;
}
sprintf (interp->result, "%d", grp->gr_gid);
return TCL_OK;
}
int
Tcl_IdCmd (clientData, interp, argc, argv)
ClientData clientData;
Tcl_Interp *interp;
int argc;
char **argv;
{
struct passwd *pw;
struct group *grp;
int uid, gid;
if (argc < 2)
goto bad_args;
/*
* If the first argument is "convert", handle the conversion.
*/
if (STREQU (argv[1], "convert")) {
if (argc != 4) {
Tcl_AppendResult (interp, tclXWrongArgs, argv [0],
" convert arg arg", (char *) NULL);
return TCL_ERROR;
}
if (STREQU (argv[2], "user"))
return UsernameToUseridResult (interp, argv[3]);
if (STREQU (argv[2], "userid")) {
if (Tcl_GetInt (interp, argv[3], &uid) != TCL_OK)
return TCL_ERROR;
return UseridToUsernameResult (interp, uid);
}
if (STREQU (argv[2], "group"))
return GroupnameToGroupidResult (interp, argv[3]);
if (STREQU (argv[2], "groupid")) {
if (Tcl_GetInt (interp, argv[3], &gid) != TCL_OK) return TCL_ERROR;
return GroupidToGroupnameResult (interp, gid);
}
goto bad_three_arg;
}
/*
* If the first argument is "effective", return the effective user ID,
* name, group ID or name.
*/
if (STREQU (argv[1], "effective")) {
if (argc != 3) {
Tcl_AppendResult (interp, tclXWrongArgs, argv [0],
" effective arg", (char *) NULL);
return TCL_ERROR;
}
if (STREQU (argv[2], "user"))
return UseridToUsernameResult (interp, geteuid ());
if (STREQU (argv[2], "userid")) {
sprintf (interp->result, "%d", geteuid ());
return TCL_OK;
}
if (STREQU (argv[2], "group"))
return GroupidToGroupnameResult (interp, getegid ());
if (STREQU (argv[2], "groupid")) {
sprintf (interp->result, "%d", getegid ());
return TCL_OK;
}
goto bad_three_arg;
}
/*
* If the first argument is "process", return the process ID, parent's
* process ID, process group or set the process group depending on args.
*/
if (STREQU (argv[1], "process")) {
if (argc == 2) {
sprintf (interp->result, "%d", getpid ());
return TCL_OK;
}
if (STREQU (argv[2], "parent")) {
if (argc != 3) {
Tcl_AppendResult (interp, tclXWrongArgs, argv [0],
" process parent", (char *) NULL);
return TCL_ERROR;
}
sprintf (interp->result, "%d", getppid ());
return TCL_OK;
}
if (STREQU (argv[2], "group")) {
if (argc == 3) {
sprintf (interp->result, "%d", getpgrp ());
return TCL_OK;
}
if ((argc != 4) || !STREQU (argv[3], "set")) {
Tcl_AppendResult (interp, tclXWrongArgs, argv [0],
" process group [set]", (char *) NULL);
return TCL_ERROR;
}
setpgid(getpid(), getpid());
return TCL_OK;
}
Tcl_AppendResult (interp, tclXWrongArgs, argv [0],
" process [parent|group|group set]", (char *) NULL);
return TCL_ERROR;
}
/*
* Handle setting or returning the user ID or group ID (by name or number).
*/
if (argc > 3)
goto bad_args;
if (STREQU (argv[1], "user")) {
if (argc == 2) {
return UseridToUsernameResult (interp, getuid ());
} else {
pw = getpwnam (argv[2]);
if (pw == NULL)
goto name_doesnt_exist;
if (setuid (pw->pw_uid) < 0)
goto cannot_set_name;
return TCL_OK;
}
}
if (STREQU (argv[1], "userid")) {
if (argc == 2) {
sprintf (interp->result, "%d", getuid ());
return TCL_OK;
} else {
if (Tcl_GetInt (interp, argv[2], &uid) != TCL_OK)
return TCL_ERROR;
if (setuid (uid) < 0)
goto cannot_set_name;
return TCL_OK;
}
}
if (STREQU (argv[1], "group")) {
if (argc == 2) {
return GroupidToGroupnameResult (interp, getgid ());
} else {
grp = getgrnam (argv[2]);
if (grp == NULL)
goto name_doesnt_exist;
if (setgid (grp->gr_gid) < 0)
goto cannot_set_name;
return TCL_OK;
}
}
if (STREQU (argv[1], "groupid")) {
if (argc == 2) {
sprintf (interp->result, "%d", getgid ());
return TCL_OK;
} else {
if (Tcl_GetInt (interp, argv[2], &gid) != TCL_OK)
return TCL_ERROR;
if (setgid (gid) < 0)
goto cannot_set_name;
return TCL_OK;
}
}
Tcl_AppendResult (interp, "bad arg: ", argv [0],
" second arg must be convert, effective, process, ",
"user, userid, group or groupid", (char *) NULL);
return TCL_ERROR;
bad_three_arg:
Tcl_AppendResult (interp, "bad arg: ", argv [0], ": ", argv[1],
": third arg must be user, userid, group or groupid",
(char *) NULL);
return TCL_ERROR;
bad_args:
Tcl_AppendResult (interp, tclXWrongArgs, argv [0], " arg [arg..]",
(char *) NULL);
return TCL_ERROR;
name_doesnt_exist:
Tcl_AppendResult (interp, " \"", argv[2], "\" does not exists",
(char *) NULL);
return TCL_ERROR;
cannot_set_name:
interp->result = Tcl_UnixError (interp);
return TCL_ERROR;
}
| 4,844 |
1,444 |
package mage.target.common;
import mage.filter.common.FilterAttackingCreature;
import mage.target.TargetPermanent;
/**
*
* @author <EMAIL>
*/
public class TargetAttackingCreature extends TargetPermanent {
public TargetAttackingCreature() {
this(1, 1, new FilterAttackingCreature(), false);
}
public TargetAttackingCreature(int numTargets) {
this(numTargets, numTargets, new FilterAttackingCreature(), false);
}
public TargetAttackingCreature(int minNumTargets, int maxNumTargets, FilterAttackingCreature filter, boolean notTarget) {
super(minNumTargets, maxNumTargets, filter, notTarget);
}
public TargetAttackingCreature(final TargetAttackingCreature target) {
super(target);
}
@Override
public TargetAttackingCreature copy() {
return new TargetAttackingCreature(this);
}
}
| 311 |
14,668 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/layout/layout_video.h"
#include "third_party/blink/renderer/core/testing/core_unit_test_helper.h"
namespace blink {
using LayoutMediaTest = RenderingTest;
TEST_F(LayoutMediaTest, DisallowInlineChild) {
SetBodyInnerHTML(R"HTML(
<style>
::-webkit-media-controls { display: inline; }
</style>
<video id='video'></video>
)HTML");
EXPECT_FALSE(GetLayoutObjectByElementId("video")->SlowFirstChild());
}
TEST_F(LayoutMediaTest, DisallowBlockChild) {
SetBodyInnerHTML(R"HTML(
<style>
::-webkit-media-controls { display: block; }
</style>
<video id='video'></video>
)HTML");
EXPECT_FALSE(GetLayoutObjectByElementId("video")->SlowFirstChild());
}
TEST_F(LayoutMediaTest, DisallowOutOfFlowPositionedChild) {
SetBodyInnerHTML(R"HTML(
<style>
::-webkit-media-controls { position: absolute; }
</style>
<video id='video'></video>
)HTML");
EXPECT_FALSE(GetLayoutObjectByElementId("video")->SlowFirstChild());
}
TEST_F(LayoutMediaTest, DisallowFloatingChild) {
SetBodyInnerHTML(R"HTML(
<style>
::-webkit-media-controls { float: left; }
</style>
<video id='video'></video>
)HTML");
EXPECT_FALSE(GetLayoutObjectByElementId("video")->SlowFirstChild());
}
} // namespace blink
| 546 |
425 | {
"$schema": "https://raw.githubusercontent.com/NateScarlet/holiday-cn/master/schema.json",
"$id": "https://raw.githubusercontent.com/NateScarlet/holiday-cn/master/2022.json",
"year": 2022,
"papers": [],
"days": []
} | 96 |
549 | <filename>19_pytorch_textsnake/lib/train_complete.py
import os
import time
from datetime import datetime
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.utils.data as data
from torch.optim import lr_scheduler
from util.shedule import FixLR
from dataset.total_text import TotalText, TotalText_txt
from dataset.synth_text import SynthText
from network.loss import TextLoss
from network.textnet import TextNet
from util.augmentation import BaseTransform, Augmentation
from util.config import config as cfg, update_config, print_config
from util.misc import AverageMeter
from util.misc import mkdirs, to_device
from util.option import BaseOptions
from util.visualize import visualize_network_output
from util.summary import LogSummary
def save_model(model, epoch, lr, optimzer):
save_dir = os.path.join(cfg.save_dir, cfg.exp_name)
if not os.path.exists(save_dir):
mkdirs(save_dir)
save_path = os.path.join(save_dir, 'textsnake_{}_{}.pth'.format(model.backbone_name, epoch))
print('Saving to {}.'.format(save_path))
state_dict = {
'lr': lr,
'epoch': epoch,
'model': model.state_dict() if not cfg.mgpu else model.module.state_dict(),
'optimizer': optimzer.state_dict()
}
torch.save(state_dict, save_path)
def load_model(model, model_path):
print('Loading from {}'.format(model_path))
state_dict = torch.load(model_path)
model.load_state_dict(state_dict['model'])
lr = None
train_step = 0
def train(model, train_loader, criterion, scheduler, optimizer, epoch, logger, train_step):
losses = AverageMeter()
batch_time = AverageMeter()
data_time = AverageMeter()
end = time.time()
model.train()
scheduler.step()
print('Epoch: {} : LR = {}'.format(epoch, lr))
for i, (img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map, meta) in enumerate(train_loader):
data_time.update(time.time() - end)
train_step += 1
img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map = to_device(
img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map)
output = model(img)
tr_loss, tcl_loss, sin_loss, cos_loss, radii_loss = \
criterion(output, tr_mask, tcl_mask, sin_map, cos_map, radius_map, train_mask)
loss = tr_loss + tcl_loss + sin_loss + cos_loss + radii_loss
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
losses.update(loss.item())
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
if cfg.viz and i % cfg.viz_freq == 0:
visualize_network_output(output, tr_mask, tcl_mask, mode='train')
if i % cfg.display_freq == 0:
#print(loss.item())
#print(tr_loss.item())
#print(tcl_loss.item())
#print(sin_loss.item())
#print(cos_loss.item())
#print(radii_loss.item())
print('({:d} / {:d}) - Loss: {:.4f} - tr_loss: {:.4f} - tcl_loss: {:.4f} - sin_loss: {:.4f} - cos_loss: {:.4f} - radii_loss: {:.4f}'.format(
i, len(train_loader), loss.item(), tr_loss.item(), tcl_loss.item(), sin_loss.item(), cos_loss.item(), radii_loss.item())
)
if i % cfg.log_freq == 0:
logger.write_scalars({
'loss': loss.item(),
'tr_loss': tr_loss.item(),
'tcl_loss': tcl_loss.item(),
'sin_loss': sin_loss.item(),
'cos_loss': cos_loss.item(),
'radii_loss': radii_loss.item()
}, tag='train', n_iter=train_step)
if epoch % cfg.save_freq == 0:
save_model(model, epoch, scheduler.get_lr(), optimizer)
print('Training Loss: {}'.format(losses.avg))
return train_step
def validation(model, valid_loader, criterion, epoch, logger):
with torch.no_grad():
model.eval()
losses = AverageMeter()
tr_losses = AverageMeter()
tcl_losses = AverageMeter()
sin_losses = AverageMeter()
cos_losses = AverageMeter()
radii_losses = AverageMeter()
for i, (img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map, meta) in enumerate(valid_loader):
img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map = to_device(
img, train_mask, tr_mask, tcl_mask, radius_map, sin_map, cos_map)
output = model(img)
tr_loss, tcl_loss, sin_loss, cos_loss, radii_loss = \
criterion(output, tr_mask, tcl_mask, sin_map, cos_map, radius_map, train_mask)
loss = tr_loss + tcl_loss + sin_loss + cos_loss + radii_loss
# update losses
losses.update(loss.item())
tr_losses.update(tr_loss.item())
tcl_losses.update(tcl_loss.item())
sin_losses.update(sin_loss.item())
cos_losses.update(cos_loss.item())
radii_losses.update(radii_loss.item())
if cfg.viz and i % cfg.viz_freq == 0:
visualize_network_output(output, tr_mask, tcl_mask, mode='val')
if i % cfg.display_freq == 0:
print(
'Validation: - Loss: {:.4f} - tr_loss: {:.4f} - tcl_loss: {:.4f} - sin_loss: {:.4f} - cos_loss: {:.4f} - radii_loss: {:.4f}'.format(
loss.item(), tr_loss.item(), tcl_loss.item(), sin_loss.item(),
cos_loss.item(), radii_loss.item())
)
logger.write_scalars({
'loss': losses.avg,
'tr_loss': tr_losses.avg,
'tcl_loss': tcl_losses.avg,
'sin_loss': sin_losses.avg,
'cos_loss': cos_losses.avg,
'radii_loss': radii_losses.avg
}, tag='val', n_iter=epoch)
print('Validation Loss: {}'.format(losses.avg))
cfg.max_epoch = 50
cfg.means = (0.485, 0.456, 0.406)
cfg.stds = (0.229, 0.224, 0.225)
cfg.log_dir = "log_dir"
cfg.exp_name = "try1"
cfg.net = "vgg"; #vgg, #resnet (does not work)
cfg.resume = "textsnake_vgg_180.pth";
cfg.cuda = True;
cfg.mgpu = False;
cfg.save_dir = "save/";
cfg.vis_dir = "vis/";
cfg.loss = "CrossEntropyLoss";
cfg.input_channel = 1;
cfg.pretrain = False;
cfg.verbose = True;
cfg.viz = True;
cfg.start_iter = 0;
cfg.lr = 0.001;
cfg.lr_adjust = "fix" #fix, step
cfg.stepvalues = [];
cfg.step_size = cfg.max_epoch//3;
cfg.weight_decay = 0;
cfg.gamma = 0.1;
cfg.momentum = 0.9;
cfg.optim = "SGD"; #SGD, Adam
cfg.display_freq = 50;
cfg.viz_freq = 50;
cfg.save_freq = 20;
cfg.log_freq = 100;
cfg.val_freq = 1000;
cfg.batch_size = 8;
cfg.rescale = 255.0;
cfg.checkepoch = -1;
if cfg.cuda and torch.cuda.is_available():
torch.set_default_tensor_type('torch.cuda.FloatTensor')
cudnn.benchmark = True
cfg.device = torch.device("cuda")
else:
torch.set_default_tensor_type('torch.FloatTensor')
cfg.device = torch.device("cpu")
# Create weights saving directory
if not os.path.exists(cfg.save_dir):
os.mkdir(cfg.save_dir)
# Create weights saving directory of target model
model_save_path = os.path.join(cfg.save_dir, cfg.exp_name)
if not os.path.exists(model_save_path):
os.mkdir(model_save_path)
if not os.path.exists(cfg.vis_dir):
os.mkdir(cfg.vis_dir)
trainset = TotalText_txt(
"data/total-text/Images/Train/",
"gt/Train/",
ignore_list=None,
is_training=True,
transform=Augmentation(size=cfg.input_size, mean=cfg.means, std=cfg.stds)
)
valset = TotalText_txt(
"data/total-text/Images/Test/",
"gt/Test/",
ignore_list=None,
is_training=False,
transform=BaseTransform(size=cfg.input_size, mean=cfg.means, std=cfg.stds)
)
train_loader = data.DataLoader(trainset, batch_size=cfg.batch_size, shuffle=True, num_workers=cfg.num_workers)
if valset:
val_loader = data.DataLoader(valset, batch_size=cfg.batch_size, shuffle=False, num_workers=cfg.num_workers)
else:
valset = None
log_dir = os.path.join(cfg.log_dir, datetime.now().strftime('%b%d_%H-%M-%S_') + cfg.exp_name)
logger = LogSummary(log_dir)
model = TextNet(is_training=True, backbone=cfg.net)
if cfg.mgpu:
model = nn.DataParallel(model)
model = model.to(cfg.device)
if cfg.cuda:
cudnn.benchmark = True
if cfg.resume:
load_model(model, cfg.resume)
criterion = TextLoss()
lr = cfg.lr
optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr)
scheduler = lr_scheduler.StepLR(optimizer, step_size=cfg.step_size, gamma=cfg.gamma)
print('Start training TextSnake.')
for epoch in range(cfg.start_epoch, cfg.max_epoch):
train_step = train(model, train_loader, criterion, scheduler, optimizer, epoch, logger, train_step)
if valset:
validation(model, val_loader, criterion, epoch, logger)
save_model(model, "final", scheduler.get_lr(), optimizer)
| 4,097 |
2,061 | from macropy.core.test.macros.line_number_macro import macros, expand
def run(x, throw):
with expand:
x = x + 1
if throw:
raise Exception("lol")
return x
| 77 |
739 | /**
* @file
* @brief Forward header for <tt>coveo/linq/linq.h</tt>.
*
* @copyright 2016-2019, Coveo Solutions Inc.
* Distributed under the Apache License, Version 2.0 (see <a href="https://github.com/coveo/linq/blob/master/LICENSE">LICENSE</a>).
*/
#ifndef COVEO_LINQ_FWD_H
#define COVEO_LINQ_FWD_H
#include <coveo/linq/linq.h>
#endif // COVEO_LINQ_FWD_H
| 172 |
921 | <reponame>narumiruna/alembic
//-*****************************************************************************
//
// Copyright (c) 2009-2011,
// <NAME>, Inc. and
// Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Sony Pictures Imageworks, nor
// Industrial Light & Magic nor the names of their contributors may be used
// to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//-*****************************************************************************
#ifndef AbcClients_WFObjConvert_Reader_h
#define AbcClients_WFObjConvert_Reader_h
#include <AbcClients/WFObjConvert/Export.h>
#include <AbcClients/WFObjConvert/Foundation.h>
namespace AbcClients {
namespace WFObjConvert {
//-*****************************************************************************
// This class definition is taken from Gto/WFObj.
//-*****************************************************************************
//-*****************************************************************************
//! The Reader class is an abstract base class which represents the
//! actions which may occur in the parsing of a Wavefront OBJ file.
//! As the file or stream is parsed, each of these actions will be called
//! as their corresponding actions are encountered in the file. The
//! default behavior is to ignore everything.
//! Because the files being read are ascii, they can actually represent
//! arbitrary precision. Therefore, the Reader is implemented in double
//! precision for maximum accuracy.
class ABC_WFOBJ_CONVERT_EXPORT Reader
{
public:
typedef std::vector<index_t> IndexVec;
typedef std::vector<std::string> StringVec;
//! In current ilm-base, there is no Vec4.
//! By default, we will treat 4-dimensional
//! points as homogenous and dehomogenize them, subsequently
//! calling the V3d version of 'v'
//! Default constructor does nothing
//! ...
Reader() {}
//! Virtual destructor as support for derived classes.
//! ...
virtual ~Reader() {}
//! This function is called by the parser
//! when parsing begins.
//! The argument passed is a name for the stream - in the
//! case of a file, it will be the file name; otherwise it
//! will be an identifier of some kind.
virtual void parsingBegin( const std::string &iStreamName ) {}
//! This function is called by the parser
//! if an error has occurred, causing parsing to stop.
//! An error description and a line number are given.
virtual void parsingError( const std::string &iStreamName,
const std::string &iErrorDesc,
size_t iErrorLine ) {}
//! This function is called by the parser
//! when parsing ends. The name passed in will match
//! the name passed to the begin function.
virtual void parsingEnd( const std::string &iStreamName,
size_t iNumLinesParsed ) {}
//-*************************************************************************
//! POINT DECLARATION
//! Points may be of type:
//! "v", which are 3 or 4-dimensional points,
//! "vt", which are 1, 2, or 3 dimensional texture coordinates,
//! "vn", which are 3-dimensional normals,
//! "vp", which are 'parameter coordinates'. Unclear what these are for.
//! These functions will each also be passed the integer index that
//! they correspond to, for synchronization and checking.
//! OBJ files begin with the first vertex at index '1', allowing for
//! vertex "0" to be used as a special location.
//-*************************************************************************
//! Set a three-dimensional vertex.
//! ...
virtual void v( index_t iIndex, const V3d &iVal ) {}
//! Set a 4-dimensional vertex, interpreted as homogenous.
//! The default behavior is to dehomogenize and call the 3-dim version.
//! It will not divide by zero - it will leave the point alone in that
//! case.
virtual void v( index_t iIndex, const V3d &iVal, double iW );
//! Set a 1-dimensional texture vertex.
//! ...
virtual void vt( index_t iIndex, double iVal ) {}
//! Set a 2-dimensional texture vertex.
//! ...
virtual void vt( index_t iIndex, const V2d &iVal ) {}
//! Set a 3-dimensional texture vertex.
//! ...
virtual void vt( index_t iIndex, const V3d &iVal ) {}
//! Set a 3-dimensional normal.
//! Using V3d instead of N3f/N3T
virtual void vn( index_t iIndex, const V3d &iVal ) {}
//! Set a 1-dimensional parameter vertex.
//! ...
virtual void vp( index_t iIndex, double iVal ) {}
//! Set a 2-dimensional parameter vertex.
//! ...
virtual void vp( index_t iIndex, const V2d &iVal ) {}
//-*************************************************************************
//! ELEMENT DECLARATION
//! In this Parser/Reader, we have three types of elements.
//! They are "faces", "lines", and "points".
//! points can actually have multiple points.
//! An element consists of vectors of Vertex, Normal, and Texture
//! indices. If these indices were unspecified, the vectors will be empty.
//! The vertex indices will always be non-empty
//-*************************************************************************
//! Declare a face.
//! ...
virtual void f( const IndexVec &iVertexIndices,
const IndexVec &iTextureIndices,
const IndexVec &iNormalIndices ) {}
//! Declare a polyline.
//! ...
virtual void l( const IndexVec &iVertexIndices,
const IndexVec &iTextureIndices,
const IndexVec &iNormalIndices ) {}
//! Declare a point-set.
//! ...
virtual void p( const IndexVec &iVertexIndices,
const IndexVec &iTextureIndices,
const IndexVec &iNormalIndices ) {}
//-*************************************************************************
//! GROUPS AND OBJECT DECLARATION
//! OBJ files have the ability to assign objects to groups, multiple
//! groups at a time, and also to declare elements as belonging to
//! a particular named object.
//-*************************************************************************
//! Called when an as-yet unseen group name is encountered.
//! ...
virtual void newGroup( const std::string &iGroupName ) {}
//! Called when active groups change
//! The set of groups may be more than 1.
virtual void activeGroups( const StringVec &iGroupNames ) {}
//! Called when an "o" line is encountered.
//! ...
virtual void activeObject( const std::string &iObjectName ) {}
//! Called when smoothing group changes -- note that Id == 0 means
//! no smoothing -- this is equivalent to the "s off" statement.
//! the "s on" statement will set smoothing group to 1.
virtual void smoothingGroup( int iSmoothingGroup ) {}
//-*************************************************************************
// Bevel/cinterp/dinterp
//-*************************************************************************
virtual void bevel( bool ) {}
virtual void cinterp( bool ) {}
virtual void dinterp( bool ) {}
//-*************************************************************************
// Material and map
//-*************************************************************************
virtual void mtllib( const std::string &iName ) {}
virtual void maplib( const std::string &iName ) {}
virtual void usemap( const std::string &iName ) {}
virtual void usemtl( const std::string &iName ) {}
//-*************************************************************************
// Trace/Shadow objects
//-*************************************************************************
virtual void trace_obj( const std::string &iName ) {}
virtual void shadow_obj( const std::string& iName ) {}
//-*************************************************************************
// Level of detail number
//-*************************************************************************
virtual void lod( int ) {}
};
} // End namespace WFObjConvert
} // End namespace AbcClients
#endif
| 2,915 |
1,144 | package org.adempiere.ui.editor;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import javax.swing.Action;
import javax.swing.KeyStroke;
public final class NullCopyPasteSupportEditor implements ICopyPasteSupportEditor
{
public static final transient NullCopyPasteSupportEditor instance = new NullCopyPasteSupportEditor();
public static final boolean isNull(final ICopyPasteSupportEditor copyPasteSupport)
{
return copyPasteSupport == null || copyPasteSupport == instance;
}
private NullCopyPasteSupportEditor()
{
super();
}
@Override
public void executeCopyPasteAction(CopyPasteActionType actionType)
{
// nothing
}
@Override
public Action getCopyPasteAction(final CopyPasteActionType actionType)
{
return null;
}
/**
* @throws IllegalStateException always
*/
@Override
public void putCopyPasteAction(final CopyPasteActionType actionType, final Action action, final KeyStroke keyStroke)
{
throw new IllegalStateException("Setting copy/paste action not supported");
}
/**
* @return false
*/
@Override
public boolean isCopyPasteActionAllowed(CopyPasteActionType actionType)
{
return false;
}
}
| 560 |
4,857 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.backup;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.backup.impl.BackupAdminImpl;
import org.apache.hadoop.hbase.backup.impl.BackupSystemTable;
import org.apache.hadoop.hbase.backup.util.BackupUtils;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.tool.TestBulkLoadHFiles;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Pair;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hbase.thirdparty.com.google.common.collect.Lists;
/**
* 1. Create table t1
* 2. Load data to t1
* 3 Full backup t1
* 4 Load data to t1
* 5 bulk load into t1
* 6 Incremental backup t1
*/
@Category(LargeTests.class)
public class TestIncrementalBackupWithBulkLoad extends TestBackupBase {
@ClassRule
public static final HBaseClassTestRule CLASS_RULE =
HBaseClassTestRule.forClass(TestIncrementalBackupWithBulkLoad.class);
private static final Logger LOG = LoggerFactory.getLogger(TestIncrementalBackupDeleteTable.class);
// implement all test cases in 1 test since incremental backup/restore has dependencies
@Test
public void TestIncBackupDeleteTable() throws Exception {
String testName = "TestIncBackupDeleteTable";
// #1 - create full backup for all tables
LOG.info("create full backup image for all tables");
List<TableName> tables = Lists.newArrayList(table1);
Connection conn = ConnectionFactory.createConnection(conf1);
Admin admin = conn.getAdmin();
BackupAdminImpl client = new BackupAdminImpl(conn);
BackupRequest request = createBackupRequest(BackupType.FULL, tables, BACKUP_ROOT_DIR);
String backupIdFull = client.backupTables(request);
assertTrue(checkSucceeded(backupIdFull));
// #2 - insert some data to table table1
Table t1 = conn.getTable(table1);
Put p1;
for (int i = 0; i < NB_ROWS_IN_BATCH; i++) {
p1 = new Put(Bytes.toBytes("row-t1" + i));
p1.addColumn(famName, qualName, Bytes.toBytes("val" + i));
t1.put(p1);
}
Assert.assertEquals(TEST_UTIL.countRows(t1), NB_ROWS_IN_BATCH * 2);
t1.close();
int NB_ROWS2 = 20;
LOG.debug("bulk loading into " + testName);
int actual = TestBulkLoadHFiles.loadHFiles(testName, table1Desc, TEST_UTIL, famName,
qualName, false, null, new byte[][][] {
new byte[][]{ Bytes.toBytes("aaaa"), Bytes.toBytes("cccc") },
new byte[][]{ Bytes.toBytes("ddd"), Bytes.toBytes("ooo") },
}, true, false, true, NB_ROWS_IN_BATCH*2, NB_ROWS2);
// #3 - incremental backup for table1
tables = Lists.newArrayList(table1);
request = createBackupRequest(BackupType.INCREMENTAL, tables, BACKUP_ROOT_DIR);
String backupIdIncMultiple = client.backupTables(request);
assertTrue(checkSucceeded(backupIdIncMultiple));
// #4 bulk load again
LOG.debug("bulk loading into " + testName);
int actual1 = TestBulkLoadHFiles.loadHFiles(testName, table1Desc, TEST_UTIL, famName,
qualName, false, null,
new byte[][][] { new byte[][] { Bytes.toBytes("ppp"), Bytes.toBytes("qqq") },
new byte[][] { Bytes.toBytes("rrr"), Bytes.toBytes("sss") }, },
true, false, true, NB_ROWS_IN_BATCH * 2 + actual, NB_ROWS2);
// #5 - incremental backup for table1
tables = Lists.newArrayList(table1);
request = createBackupRequest(BackupType.INCREMENTAL, tables, BACKUP_ROOT_DIR);
String backupIdIncMultiple1 = client.backupTables(request);
assertTrue(checkSucceeded(backupIdIncMultiple1));
// Delete all data in table1
TEST_UTIL.deleteTableData(table1);
// #5.1 - check tables for full restore */
Admin hAdmin = TEST_UTIL.getAdmin();
// #6 - restore incremental backup for table1
TableName[] tablesRestoreIncMultiple = new TableName[] { table1 };
//TableName[] tablesMapIncMultiple = new TableName[] { table1_restore };
client.restore(BackupUtils.createRestoreRequest(BACKUP_ROOT_DIR, backupIdIncMultiple1,
false, tablesRestoreIncMultiple, tablesRestoreIncMultiple, true));
Table hTable = conn.getTable(table1);
Assert.assertEquals(TEST_UTIL.countRows(hTable), NB_ROWS_IN_BATCH * 2 + actual + actual1);
request = createBackupRequest(BackupType.FULL, tables, BACKUP_ROOT_DIR);
backupIdFull = client.backupTables(request);
try (final BackupSystemTable table = new BackupSystemTable(conn)) {
Pair<Map<TableName, Map<String, Map<String, List<Pair<String, Boolean>>>>>, List<byte[]>> pair
= table.readBulkloadRows(tables);
assertTrue("map still has " + pair.getSecond().size() + " entries",
pair.getSecond().isEmpty());
}
assertTrue(checkSucceeded(backupIdFull));
hTable.close();
admin.close();
conn.close();
}
}
| 2,161 |
305 | <filename>books/kestrel/java/aij/java/src/edu/kestrel/acl2/aij/Acl2Ratio.java
/*
* Copyright (C) 2020 Kestrel Institute (http://www.kestrel.edu)
* License: A 3-clause BSD license. See the LICENSE file distributed with ACL2.
* Author: <NAME> (<EMAIL>)
*/
package edu.kestrel.acl2.aij;
/**
* Representation of ACL2 ratios.
* These are the values that satisfy {@code rationalp} but not {@code integerp},
* i.e. ratios in Common Lisp.
* <p>
* This class is not public because code outside this package
* must use the public methods in the {@link Acl2Rational} class
* to create rational numbers (which may be integers or ratios).
*/
final class Acl2Ratio extends Acl2Rational {
//////////////////////////////////////// private members:
/**
* Numerator of the ratio.
* Invariant: not null, coprime with the denominator.
*/
private final Acl2Integer numerator;
/**
* Denominator of the ratio.
* Invariant: not null, greater than 1, coprime with the numerator.
*/
private final Acl2Integer denominator;
/**
* Constructs a ratio with the given numerator and denominator.
*
* @param numerator The numerator of the ratio.
* Invariants: not null,
* coprime with {@code denominator}.
* @param denominator The denominator of the ratio.
* Invariants: not null,
* greater than 1,
* coprime with {@code numerator}.
*/
private Acl2Ratio(Acl2Integer numerator, Acl2Integer denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
//////////////////////////////////////// package-private members:
/**
* Returns a ratio with the given numerator and denominator.
*
* @param numerator The numerator of the ratio.
* Invariants: not null,
* coprime with {@code denominator}.
* @param denominator The denominator of the ratio.
* Invariants: not null,
* greater than 1,
* coprime with {@code numerator}.
* @return The ratio.
*/
static Acl2Ratio makeInternal(Acl2Integer numerator,
Acl2Integer denominator) {
return new Acl2Ratio(numerator, denominator);
}
//////////////////////////////////////// public members:
/**
* Compares this ratio with the argument object for equality.
* This is consistent with the {@code equal} ACL2 function.
*
* @param o The object to compare this ratio with.
* @return {@code true} if the object is equal to this ratio,
* otherwise {@code false}.
*/
@Override
public boolean equals(Object o) {
/* Since the denominator is positive and coprime with the numerator,
two ratios are equal iff their numerator and denominator are. */
if (this == o) return true;
if (!(o instanceof Acl2Ratio)) return false;
Acl2Ratio that = (Acl2Ratio) o;
if (!numerator.equals(that.numerator)) return false;
return denominator.equals(that.denominator);
}
/**
* Returns a hash code for this ratio.
*
* @return A hash code for this ratio.
*/
@Override
public int hashCode() {
int result = numerator.hashCode();
result = 31 * result + denominator.hashCode();
return result;
}
/**
* Returns a printable representation of this ratio.
* We return a Java string that
* conforms to ACL2's notation for ratios.
*
* @return A printable representation of this ratio.
*/
@Override
public String toString() {
return this.numerator + "/" + this.denominator;
}
/**
* Returns the numerator of this ratio.
* The numerator is in reduced form,
* i.e. it is coprime with the denominator,
* and its sign is consistent with a positive denominator.
*
* @return The numerator of this ratio.
*/
@Override
public Acl2Integer getNumerator() {
return numerator;
}
/**
* Returns the denominator of this ACL2 ratio.
* The denominator is in reduced form,
* i.e. it is positive and coprime with the numerator.
*
* @return The denominator of this ratio.
*/
@Override
public Acl2Integer getDenominator() {
return denominator;
}
}
| 1,801 |
653 | <filename>itstack-naive-chat-server/itstack-naive-chat-server-ddd/src/main/java/org/itstack/naive/chat/Application.java
package org.itstack.naive.chat;
import io.netty.channel.Channel;
import org.itstack.naive.chat.application.UserService;
import org.itstack.naive.chat.socket.NettyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* 博 客:http://bugstack.cn
* 公众号:bugstack虫洞栈 | 沉淀、分享、成长,让自己和他人都能有所收获!
* create by 小傅哥 on @2020
*/
@SpringBootApplication
@Configuration
@ImportResource(locations = {"classpath:spring-config.xml"})
public class Application extends SpringBootServletInitializer implements CommandLineRunner {
private Logger logger = LoggerFactory.getLogger(Application.class);
@Resource
private NettyServer nettyServer;
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
logger.info("NettyServer启动服务开始 port:7397");
Future<Channel> future = Executors.newFixedThreadPool(2).submit(nettyServer);
Channel channel = future.get();
if (null == channel) throw new RuntimeException("netty server start error channel is null");
while (!channel.isActive()) {
logger.info("NettyServer启动服务 ...");
Thread.sleep(500);
}
logger.info("NettyServer启动服务完成 {}", channel.localAddress());
}
}
| 819 |
1,444 | package mage.view;
import mage.counters.Counter;
import java.io.Serializable;
/**
* @author <EMAIL>
*/
public class CounterView implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int count;
public CounterView(Counter counter) {
this.name = counter.getName();
this.count = counter.getCount();
}
public CounterView(final CounterView view) {
this.name = view.name;
this.count = view.count;
}
public String getName() {
return name;
}
public int getCount() {
return count;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
if (!(other instanceof CounterView)) {
return false;
}
CounterView oth = (CounterView) other;
return
(count == oth.count) &&
(name.equals(oth.name));
}
}
| 465 |
66,985 | <filename>spring-boot-tests/spring-boot-smoke-tests/spring-boot-smoke-test-bootstrap-registry/src/main/java/smoketest/bootstrapregistry/app/SampleBootstrapRegistryApplication.java
/*
* Copyright 2012-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package smoketest.bootstrapregistry.app;
import smoketest.bootstrapregistry.external.svn.SubversionBootstrap;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SampleBootstrapRegistryApplication {
public static void main(String[] args) {
// This example shows how a Bootstrapper can be used to register a custom
// SubversionClient that still has access to data provided in the
// application.properties file
SpringApplication application = new SpringApplication(SampleBootstrapRegistryApplication.class);
application.addBootstrapRegistryInitializer(SubversionBootstrap.withCustomClient(MySubversionClient::new));
application.run(args);
}
}
| 423 |
2,082 | <reponame>alairice/doccano<gh_stars>1000+
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_mommy import mommy
from projects.models import SEQUENCE_LABELING
from projects.tests.utils import prepare_project
class TestRelationLabeling(TestCase):
@classmethod
def setUpTestData(cls):
cls.project = prepare_project(SEQUENCE_LABELING)
cls.example = mommy.make("Example", project=cls.project.item)
cls.label_type = mommy.make("RelationType", project=cls.project.item)
cls.user = cls.project.admin
def test_can_annotate_relation(self):
from_id = mommy.make("Span", example=self.example, start_offset=0, end_offset=1)
to_id = mommy.make("Span", example=self.example, start_offset=1, end_offset=2)
mommy.make("Relation", example=self.example, from_id=from_id, to_id=to_id)
def test_cannot_annotate_relation_if_span_example_is_different(self):
from_id = mommy.make("Span", example=self.example, start_offset=0, end_offset=1)
to_id = mommy.make("Span", start_offset=1, end_offset=2)
with self.assertRaises(ValidationError):
mommy.make("Relation", example=self.example, from_id=from_id, to_id=to_id)
def test_cannot_annotate_relation_if_relation_example_is_different_from_span_example(self):
from_id = mommy.make("Span", example=self.example, start_offset=0, end_offset=1)
to_id = mommy.make("Span", example=self.example, start_offset=1, end_offset=2)
with self.assertRaises(ValidationError):
mommy.make("Relation", from_id=from_id, to_id=to_id)
| 665 |
2,150 | <reponame>cihuang123/pyrobot
from pyrobot import Robot
import os
import open3d
# Please change this to match your habitat_sim repo's path
path_to_habitat_scene = os.path.dirname(os.path.realpath(__file__))
relative_path = "scenes/skokloster-castle.glb"
common_config = dict(scene_path=os.path.join(path_to_habitat_scene, relative_path))
bot = Robot("habitat", common_config=common_config)
# fetch the point
pts, colors = bot.camera.get_current_pcd(in_cam=False)
# convert points to open3d point cloud object
pcd = open3d.PointCloud()
pcd.points = open3d.Vector3dVector(pts)
pcd.colors = open3d.Vector3dVector(colors / 255.0)
# for visualizing the origin
coord = open3d.create_mesh_coordinate_frame(1, [0, 0, 0])
# visualize point cloud
open3d.visualization.draw_geometries([pcd, coord])
| 293 |
1,056 | <reponame>timfel/netbeans
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.profiler.v2.features;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import org.netbeans.lib.profiler.ProfilerClient;
import org.netbeans.lib.profiler.client.ClientUtils;
import org.netbeans.lib.profiler.common.Profiler;
import org.netbeans.lib.profiler.common.ProfilingSettings;
import org.netbeans.lib.profiler.ui.components.ProfilerToolbar;
import org.netbeans.lib.profiler.ui.swing.PopupButton;
import org.netbeans.lib.profiler.ui.swing.SmallButton;
import org.netbeans.lib.profiler.utils.Wildcards;
import org.netbeans.modules.profiler.ResultsListener;
import org.netbeans.modules.profiler.ResultsManager;
import org.netbeans.modules.profiler.api.ProjectUtilities;
import org.netbeans.modules.profiler.api.icons.Icons;
import org.netbeans.modules.profiler.api.icons.ProfilerIcons;
import org.netbeans.modules.profiler.v2.ProfilerFeature;
import org.netbeans.modules.profiler.v2.ProfilerSession;
import org.netbeans.modules.profiler.v2.impl.WeakProcessor;
import org.netbeans.modules.profiler.v2.ui.SettingsPanel;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.lookup.Lookups;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author <NAME>
*/
@NbBundle.Messages({
"SQLFeature_name=SQL Queries",
"SQLFeature_description=Display executed SQL queries, their duration and invocation paths",
"SQLFeature_profileMethod=Profile Method",
"SQLFeature_profileClass=Profile Class"
})
final class SQLFeature extends ProfilerFeature.Basic {
private final WeakProcessor processor;
private FeatureMode currentMode;
private FeatureMode appliedMode;
private SQLFeatureModes.AllQueriesMode allQueriesMode;
private SQLFeatureModes.FilteredQueriesMode filteredQueriesMode;
private SQLFeature(ProfilerSession session) {
super(Icons.getIcon(ProfilerIcons.WINDOW_SQL), Bundle.SQLFeature_name(),
Bundle.SQLFeature_description(), 20, session);
Lookup.Provider project = session.getProject();
String projectName = project == null ? "External Process" : // NOI18N
ProjectUtilities.getDisplayName(project);
processor = new WeakProcessor("SQLFeature Processor for " + projectName); // NOI18N
initModes();
}
// --- Mode ----------------------------------------------------------------
private static final String MODE_FLAG = "MODE_FLAG"; // NOI18N
private void initModes() {
allQueriesMode = new SQLFeatureModes.AllQueriesMode() {
String readFlag(String flag, String defaultValue) {
return SQLFeature.this.readFlag(getID() + "_" + flag, defaultValue); // NOI18N
}
void storeFlag(String flag, String value) {
SQLFeature.this.storeFlag(getID() + "_" + flag, value); // NOI18N
}
void settingsChanged() {
SQLFeature.this.settingsChanged();
}
};
filteredQueriesMode = new SQLFeatureModes.FilteredQueriesMode() {
String readFlag(String flag, String defaultValue) {
return SQLFeature.this.readFlag(getID() + "_" + flag, defaultValue); // NOI18N
}
void storeFlag(String flag, String value) {
SQLFeature.this.storeFlag(getID() + "_" + flag, value); // NOI18N
}
void settingsChanged() {
SQLFeature.this.settingsChanged();
}
};
String _currentMode = readFlag(MODE_FLAG, allQueriesMode.getID());
if (_currentMode.equals(filteredQueriesMode.getID())) currentMode = filteredQueriesMode;
else currentMode = allQueriesMode;
appliedMode = currentMode;
}
private void saveMode() {
storeFlag(MODE_FLAG, currentMode.getID());
}
private void setMode(FeatureMode newMode) {
if (currentMode == newMode) return;
currentMode = newMode;
modeChanged();
}
private void confirmMode() {
appliedMode = currentMode;
}
private void modeChanged() {
updateModeName();
updateModeUI();
configurationChanged();
saveMode();
}
// --- Settings ------------------------------------------------------------
public boolean supportsSettings(ProfilingSettings psettings) {
return !ProfilingSettings.isCPUSettings(psettings) &&
!ProfilingSettings.isMemorySettings(psettings);
}
public void configureSettings(ProfilingSettings psettings) {
currentMode.configureSettings(psettings);
}
public boolean currentSettingsValid() {
return currentMode.currentSettingsValid();
}
private void submitChanges() {
confirmMode();
confirmSettings();
fireChange();
}
// Changes to current settings are pending
private boolean pendingChanges() {
if (appliedMode != currentMode) return true;
return currentMode.pendingChanges();
}
// Profiling settings defined by this feature have changed
private void configurationChanged() {
assert isActivated();
ProfilerSession session = getSession();
if (!session.inProgress()) submitChanges();
else updateApplyButton(session.getState());
}
private void confirmSettings() {
currentMode.confirmSettings();
}
private void confirmAllSettings() {
if (allQueriesMode != null) allQueriesMode.confirmSettings();
if (filteredQueriesMode != null) filteredQueriesMode.confirmSettings();
}
private void settingsChanged() {
configurationChanged();
}
private void selectionChanged() {
configurationChanged();
}
// --- Settings UI ---------------------------------------------------------
private static final String SETTINGS_FLAG = "SETTINGS_FLAG"; // NOI18N
private JPanel settingsUI;
private JButton modeButton;
private JPanel settingsContainer;
private JButton applyButton;
public JPanel getSettingsUI() {
if (settingsUI == null) {
settingsUI = new JPanel(new GridBagLayout()) {
public void setVisible(boolean visible) {
if (visible && getComponentCount() == 0) populateSettingsUI();
super.setVisible(visible);
storeFlag(SETTINGS_FLAG, visible ? Boolean.TRUE.toString() : null);
}
public Dimension getPreferredSize() {
if (getComponentCount() == 0) return new Dimension();
else return super.getPreferredSize();
}
};
String _vis = readFlag(SETTINGS_FLAG, null);
boolean vis = _vis == null ? false : Boolean.parseBoolean(_vis);
settingsUI.setVisible(vis || currentMode != allQueriesMode);
}
return settingsUI;
}
private void populateSettingsUI() {
settingsUI.setOpaque(false);
settingsUI.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
GridBagConstraints c;
JPanel profilePanel = new SettingsPanel();
profilePanel.add(new JLabel(Bundle.ObjectsFeature_profileMode()));
profilePanel.add(Box.createHorizontalStrut(5));
// Mode button
modeButton = new PopupButton(currentMode.getName()) {
protected void populatePopup(JPopupMenu popup) {
popup.add(new JRadioButtonMenuItem(allQueriesMode.getName(), currentMode == allQueriesMode) {
protected void fireActionPerformed(ActionEvent e) { setMode(allQueriesMode); }
});
popup.add(new JRadioButtonMenuItem(filteredQueriesMode.getName(), currentMode == filteredQueriesMode) {
protected void fireActionPerformed(ActionEvent e) { setMode(filteredQueriesMode); }
});
}
};
profilePanel.add(modeButton);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(0, 0, 0, 0);
c.anchor = GridBagConstraints.NORTHWEST;
settingsUI.add(profilePanel, c);
// Settings container
settingsContainer = new JPanel(new BorderLayout());
settingsContainer.setOpaque(false);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.VERTICAL;
c.insets = new Insets(0, 10, 0, 0);
c.anchor = GridBagConstraints.NORTHWEST;
settingsUI.add(settingsContainer, c);
JPanel buttonsPanel = new SettingsPanel();
final Component space = Box.createHorizontalStrut(10);
buttonsPanel.add(space);
// Apply button
applyButton = new SmallButton(Bundle.ObjectsFeature_applyButton()) {
protected void fireActionPerformed(ActionEvent e) {
stopResults();
resetResults();
submitChanges();
unpauseResults();
}
public void setVisible(boolean visible) {
super.setVisible(visible);
space.setVisible(visible);
}
};
buttonsPanel.add(applyButton);
c = new GridBagConstraints();
c.gridx = 2;
c.gridy = 0;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(0, 0, 0, 0);
c.anchor = GridBagConstraints.NORTHEAST;
settingsUI.add(buttonsPanel, c);
updateModeUI();
updateApplyButton(getSession().getState());
}
private void updateModeName() {
if (modeButton != null) modeButton.setText(currentMode.getName());
}
private void updateModeUI() {
if (settingsContainer != null) {
settingsContainer.removeAll();
JComponent modeUI = currentMode.getUI();
if (modeUI != null) settingsContainer.add(modeUI);
settingsContainer.doLayout();
settingsContainer.repaint();
}
}
private void updateApplyButton(int state) {
if (applyButton != null) {
boolean visible = state != Profiler.PROFILING_INACTIVE;
applyButton.setVisible(visible);
if (visible) applyButton.setEnabled(currentSettingsValid() && pendingChanges());
}
}
// --- Toolbar & Results UI ------------------------------------------------
private SQLFeatureUI ui;
public JPanel getResultsUI() {
return getUI().getResultsUI();
}
public ProfilerToolbar getToolbar() {
return getUI().getToolbar();
}
private SQLFeatureUI getUI() {
if (ui == null) ui = new SQLFeatureUI() {
void selectForProfiling(final ClientUtils.SourceCodeSelection value) {
RequestProcessor.getDefault().post(new Runnable() {
public void run() {
String name = Wildcards.ALLWILDCARD.equals(value.getMethodName()) ?
Bundle.SQLFeature_profileClass() :
Bundle.SQLFeature_profileMethod();
ProfilerSession.findAndConfigure(Lookups.fixed(value), getProject(), name);
}
});
}
Lookup.Provider getProject() {
return SQLFeature.this.getSession().getProject();
}
ProfilerClient getProfilerClient() {
Profiler profiler = SQLFeature.this.getSession().getProfiler();
return profiler.getTargetAppRunner().getProfilerClient();
}
int getSessionState() {
return SQLFeature.this.getSessionState();
}
void refreshResults() {
SQLFeature.this.refreshResults();
}
};
return ui;
}
// --- Live results --------------------------------------------------------
private Runnable refresher;
private volatile boolean running;
private void startResults() {
if (running) return;
running = true;
refresher = new Runnable() {
public void run() {
if (running) {
refreshView();
refreshResults(1500);
}
}
};
refreshResults(1000);
}
private void refreshView() {
if (ui != null && ResultsManager.getDefault().resultsAvailable()) {
try {
ui.refreshData();
} catch (ClientUtils.TargetAppOrVMTerminated ex) {
stopResults();
}
}
}
private void refreshResults() {
if (running) processor.post(new Runnable() {
public void run() {
if (ui != null) ui.setForceRefresh();
refreshView();
}
});
}
private void refreshResults(int delay) {
if (running && refresher != null) processor.post(refresher, delay);
}
private void resetResults() {
if (ui != null) ui.resetData();
}
private void stopResults() {
if (refresher != null) {
running = false;
refresher = null;
}
}
private void unpauseResults() {
if (ui != null) ui.resetPause();
}
// --- Session lifecycle ---------------------------------------------------
private SQLResetter resetter;
public void notifyActivated() {
resetResults();
resetter = Lookup.getDefault().lookup(SQLResetter.class);
resetter.controller = this;
}
public void notifyDeactivated() {
resetResults();
if (resetter != null) {
resetter.controller = null;
resetter = null;
}
if (ui != null) {
ui.cleanup();
ui = null;
}
}
protected void profilingStateChanged(int oldState, int newState) {
if (newState == Profiler.PROFILING_INACTIVE || newState == Profiler.PROFILING_IN_TRANSITION) {
stopResults();
confirmAllSettings();
} else if (isActivated() && newState == Profiler.PROFILING_RUNNING) {
startResults();
} else if (newState == Profiler.PROFILING_STARTED) {
resetResults();
unpauseResults();
}
if (ui != null) ui.sessionStateChanged(getSessionState());
updateApplyButton(newState);
}
@ServiceProvider(service=ResultsListener.class)
public static final class SQLResetter implements ResultsListener {
private SQLFeature controller;
public void resultsAvailable() { /*if (controller != null) controller.refreshView();*/ }
public void resultsReset() { if (controller != null && controller.ui != null) controller.ui.resetData(); }
}
// --- Provider ------------------------------------------------------------
@ServiceProvider(service=ProfilerFeature.Provider.class)
public static final class Provider extends ProfilerFeature.Provider {
public ProfilerFeature getFeature(ProfilerSession session) {
//return Boolean.getBoolean("org.netbeans.modules.profiler.features.enableSQL") ? new SQLFeature(session) : null; // NOI18N
return new SQLFeature(session);
}
}
}
| 7,307 |
695 | <filename>src/test/pythonFiles/typeFormatFiles/elseBlocksFirstLine2.py
if True == True:
a = 2
b = 3
else: | 41 |
778 | package org.aion.zero.impl.precompiled.contracts.ATB;
import static com.google.common.truth.Truth.assertThat;
import static org.aion.zero.impl.precompiled.contracts.ATB.BridgeTestUtils.dummyContext;
import java.util.List;
import org.aion.crypto.HashUtil;
import org.aion.precompiled.contracts.ATB.BridgeController;
import org.aion.precompiled.contracts.ATB.BridgeStorageConnector;
import org.aion.precompiled.contracts.ATB.ErrCode;
import org.aion.precompiled.type.CapabilitiesProvider;
import org.aion.precompiled.type.IExternalStateForPrecompiled;
import org.aion.precompiled.type.PrecompiledTransactionContext;
import org.aion.types.AionAddress;
import org.aion.types.Log;
import org.aion.util.bytes.ByteUtil;
import org.aion.zero.impl.precompiled.ExternalStateForTests;
import org.aion.zero.impl.vm.precompiled.ExternalCapabilitiesForPrecompiled;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class BridgeControllerOwnerTest {
private BridgeStorageConnector connector;
private BridgeController controller;
private List<Log> logs;
private static final AionAddress CONTRACT_ADDR =
new AionAddress(HashUtil.h256("contractAddress".getBytes()));
private static final AionAddress OWNER_ADDR =
new AionAddress(HashUtil.h256("ownerAddress".getBytes()));
@BeforeClass
public static void setupCapabilities() {
CapabilitiesProvider.installExternalCapabilities(new ExternalCapabilitiesForPrecompiled());
}
@AfterClass
public static void teardownCapabilities() {
CapabilitiesProvider.removeExternalCapabilities();
}
@Before
public void beforeEach() {
IExternalStateForPrecompiled worldState = ExternalStateForTests.usingDefaultRepository();
this.connector = new BridgeStorageConnector(worldState, CONTRACT_ADDR);
PrecompiledTransactionContext context = dummyContext();
this.logs = context.getLogs();
this.controller = new BridgeController(connector, this.logs, CONTRACT_ADDR, OWNER_ADDR);
}
@Test
public void testInitialize() {
this.controller.initialize();
assertThat(this.connector.getOwner()).isEqualTo(OWNER_ADDR.toByteArray());
}
@Test
public void testTransferOwnership() {
byte[] transferOwnership = HashUtil.keccak256("ChangedOwner(address)".getBytes());
byte[] newOwner = HashUtil.h256("newOwner".getBytes());
this.controller.initialize();
this.controller.setNewOwner(OWNER_ADDR.toByteArray(), newOwner);
// sanity check
assertThat(this.connector.getNewOwner()).isEqualTo(newOwner);
ErrCode err = this.controller.acceptOwnership(newOwner);
assertThat(err).isEqualTo(ErrCode.NO_ERROR);
assertThat(this.connector.getOwner()).isEqualTo(newOwner);
// check that an event was properly generated
assertThat(this.logs.size()).isEqualTo(1);
Log changedOwnerLog = this.logs.get(0);
assertThat(changedOwnerLog.copyOfData()).isEqualTo(ByteUtil.EMPTY_BYTE_ARRAY);
assertThat(changedOwnerLog.copyOfTopics().get(0)).isEqualTo(transferOwnership);
assertThat(changedOwnerLog.copyOfTopics().get(1)).isEqualTo(newOwner);
}
@Test
public void testInvalidOwnerTransferOwnership() {
byte[] notOwner = HashUtil.h256("not owner".getBytes());
byte[] newOwner = HashUtil.h256("newOwner".getBytes());
this.controller.initialize();
ErrCode err = this.controller.setNewOwner(notOwner, newOwner);
assertThat(err).isEqualTo(ErrCode.NOT_OWNER);
}
}
| 1,336 |
1,602 | //==-- llvm/Support/CheckedArithmetic.h - Safe arithmetical operations *- C++ //
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains generic functions for operating on integers which
// give the indication on whether the operation has overflown.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_SUPPORT_CHECKEDARITHMETIC_H
#define LLVM_SUPPORT_CHECKEDARITHMETIC_H
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Optional.h"
#include <type_traits>
namespace {
/// Utility function to apply a given method of \c APInt \p F to \p LHS and
/// \p RHS.
/// \return Empty optional if the operation overflows, or result otherwise.
template <typename T, typename F>
std::enable_if_t<std::is_integral<T>::value && sizeof(T) * 8 <= 64,
llvm::Optional<T>>
checkedOp(T LHS, T RHS, F Op, bool Signed = true) {
llvm::APInt ALHS(/*BitSize=*/sizeof(T) * 8, LHS, Signed);
llvm::APInt ARHS(/*BitSize=*/sizeof(T) * 8, RHS, Signed);
bool Overflow;
llvm::APInt Out = (ALHS.*Op)(ARHS, Overflow);
if (Overflow)
return llvm::None;
return Signed ? Out.getSExtValue() : Out.getZExtValue();
}
}
namespace llvm {
/// Add two signed integers \p LHS and \p RHS.
/// \return Optional of sum if no signed overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_signed<T>::value, llvm::Optional<T>>
checkedAdd(T LHS, T RHS) {
return checkedOp(LHS, RHS, &llvm::APInt::sadd_ov);
}
/// Subtract two signed integers \p LHS and \p RHS.
/// \return Optional of sum if no signed overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_signed<T>::value, llvm::Optional<T>>
checkedSub(T LHS, T RHS) {
return checkedOp(LHS, RHS, &llvm::APInt::ssub_ov);
}
/// Multiply two signed integers \p LHS and \p RHS.
/// \return Optional of product if no signed overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_signed<T>::value, llvm::Optional<T>>
checkedMul(T LHS, T RHS) {
return checkedOp(LHS, RHS, &llvm::APInt::smul_ov);
}
/// Multiply A and B, and add C to the resulting product.
/// \return Optional of result if no signed overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_signed<T>::value, llvm::Optional<T>>
checkedMulAdd(T A, T B, T C) {
if (auto Product = checkedMul(A, B))
return checkedAdd(*Product, C);
return llvm::None;
}
/// Add two unsigned integers \p LHS and \p RHS.
/// \return Optional of sum if no unsigned overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_unsigned<T>::value, llvm::Optional<T>>
checkedAddUnsigned(T LHS, T RHS) {
return checkedOp(LHS, RHS, &llvm::APInt::uadd_ov, /*Signed=*/false);
}
/// Multiply two unsigned integers \p LHS and \p RHS.
/// \return Optional of product if no unsigned overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_unsigned<T>::value, llvm::Optional<T>>
checkedMulUnsigned(T LHS, T RHS) {
return checkedOp(LHS, RHS, &llvm::APInt::umul_ov, /*Signed=*/false);
}
/// Multiply unsigned integers A and B, and add C to the resulting product.
/// \return Optional of result if no unsigned overflow occurred,
/// \c None otherwise.
template <typename T>
std::enable_if_t<std::is_unsigned<T>::value, llvm::Optional<T>>
checkedMulAddUnsigned(T A, T B, T C) {
if (auto Product = checkedMulUnsigned(A, B))
return checkedAddUnsigned(*Product, C);
return llvm::None;
}
} // End llvm namespace
#endif
| 1,337 |
345 | <filename>test/programytest/storage/entities/test_duplicates.py
import unittest
import unittest.mock
from programy.storage.entities.duplicates import DuplicatesStore
class DuplicatesStoreTests(unittest.TestCase):
def test_save_duplicates(self):
store = DuplicatesStore()
with self.assertRaises(NotImplementedError):
duplicates = unittest.mock.Mock()
store.save_duplicates(duplicates)
| 168 |
5,133 | <reponame>Saljack/mapstruct
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.mapstruct.util.Experimental;
/**
* Configuration of builders, e.g. the name of the final build method.
*
* <p>
* <strong>Example:</strong> Using builder
* </p>
* <pre><code class='java'>
* // Mapper
* @Mapper
* public interface SimpleBuilderMapper {
* @Mapping(target = "name", source = "fullName"),
* @Mapping(target = "job", constant = "programmer"),
* SimpleImmutablePerson toImmutable(SimpleMutablePerson source);
* }
* </code></pre>
* <pre><code class='java'>
* // generates
* @Override
* public SimpleImmutablePerson toImmutable(SimpleMutablePerson source) {
* // name method can be changed with parameter {@link #buildMethod()}
* Builder simpleImmutablePerson = SimpleImmutablePerson.builder();
* simpleImmutablePerson.name( source.getFullName() );
* simpleImmutablePerson.age( source.getAge() );
* simpleImmutablePerson.address( source.getAddress() );
* simpleImmutablePerson.job( "programmer" );
* // ...
* }
* </code></pre>
*
* @author <NAME>
*
* @since 1.3
*/
@Retention(RetentionPolicy.CLASS)
@Target({})
@Experimental
public @interface Builder {
/**
* The name of the build method that needs to be invoked on the builder to create the type to be build
*
* @return the method that needs to tbe invoked on the builder
*/
String buildMethod() default "build";
/**
* Toggling builders on / off. Builders are sometimes used solely for unit testing (fluent testdata)
* MapStruct will need to use the regular getters /setters in that case.
*
* @return when true, no builder patterns will be applied
*/
boolean disableBuilder() default false;
}
| 672 |
2,831 | #pragma once
#include "../common/config.h"
namespace co {
struct StackTraits
{
static stack_malloc_fn_t& MallocFunc();
static stack_free_fn_t& FreeFunc();
static int & GetProtectStackPageSize();
static bool ProtectStack(void* stack, std::size_t size, int pageSize);
static void UnprotectStack(void* stack, int pageSize);
};
} // namespace co
//#include "../../third_party/boost.context/boost/context/fcontext.hpp"
//using boost::context::fcontext_t;
//using boost::context::jump_fcontext;
//using boost::context::make_fcontext;
extern "C"
{
typedef void* fcontext_t;
typedef void (FCONTEXT_CALL *fn_t)(intptr_t);
intptr_t libgo_jump_fcontext(fcontext_t * ofc, fcontext_t nfc,
intptr_t vp, bool preserve_fpu = false);
fcontext_t libgo_make_fcontext(void* stack, std::size_t size, fn_t fn);
} // extern "C"
| 326 |
2,453 | <gh_stars>1000+
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 30 2020 21:18:12).
//
// Copyright (C) 1997-2019 <NAME>.
//
#import <objc/NSObject.h>
@class MISSING_TYPE;
@protocol IDETestReport_Device;
@interface _TtC6IDEKit26IDETestReportDeviceSummary : NSObject
{
MISSING_TYPE *device;
MISSING_TYPE *testFailureCount;
}
+ (id)deviceSummariesForTestGroups:(id)arg1;
- (void).cxx_destruct;
- (id)init;
- (id)initWithDevice:(id)arg1 testFailureCount:(long long)arg2;
@property(nonatomic) long long testFailureCount; // @synthesize testFailureCount;
@property(nonatomic, readonly) id <IDETestReport_Device> device; // @synthesize device;
@end
| 257 |
310 | {
"name": "Ai",
"description": "A media server.",
"url": "http://www.avolites.com/ai-features"
} | 42 |
1,738 | <gh_stars>1000+
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_EDITOR_MANNEQUIN_MANNCONTEXTEDITORDIALOG_H
#define CRYINCLUDE_EDITOR_MANNEQUIN_MANNCONTEXTEDITORDIALOG_H
#pragma once
#include "MannequinBase.h"
#include <QDialog>
#include <QScopedPointer>
class CXTPMannContextRecord;
class CMannContextTableModel;
namespace Ui {
class MannContextEditorDialog;
}
class CMannContextEditorDialog
: public QDialog
{
public:
CMannContextEditorDialog(QWidget* pParent = nullptr);
virtual ~CMannContextEditorDialog();
private:
void OnReportItemDblClick(const QModelIndex& index);
void OnReportSelChanged();
void OnNewContext();
void OnEditContext();
void OnCloneAndEditContext();
void OnDeleteContext();
void OnMoveUp();
void OnMoveDown();
void OnImportBackground();
void OnInitDialog();
void PopulateReport();
void EnableControls();
CXTPMannContextRecord* GetFocusedRecord();
QModelIndex GetFocusedRecordIndex() const;
void SetFocusedRecord(const uint32 dataID);
void OnColumnHeaderClicked(int column);
CMannContextTableModel* m_contextModel;
QScopedPointer<Ui::MannContextEditorDialog> ui;
};
#endif // CRYINCLUDE_EDITOR_MANNEQUIN_MANNCONTEXTEDITORDIALOG_H
| 600 |
642 | <gh_stars>100-1000
import netCDF4
# OPeNDAP.
url = 'http://geoport-dev.whoi.edu/thredds/dodsC/estofs/atlantic'
with netCDF4.Dataset(url) as nc:
# Compiled with cython.
assert nc.filepath() == url
url = 'http://geoport.whoi.edu/thredds/dodsC/usgs/vault0/models/tides/vdatum_gulf_of_maine/adcirc54_38_orig.nc'
with netCDF4.Dataset(url) as nc:
nc['tidenames'][:]
| 185 |
1,428 | package kik;
public class May {
public static void main(String[] args) {
int []arrayku = {2,4,5,21,4,6,1,88};
int i,j,k,psskecil,numkecil;
for(i=0 ; i < arrayku.length ; i++) {
numkecil = arrayku[i];
psskecil = i;
for(j=i ; j<arrayku.length ; j++) {
if(arrayku[j] < numkecil) {
numkecil = arrayku[j];
psskecil = j;
}
}
int gelasC;
gelasC = arrayku[i];
arrayku[i] = arrayku[psskecil];
arrayku[psskecil] = gelasC;
}
for(k=0 ; k<arrayku.length ; k++) {
System.out.print(" "+arrayku[k]);
}
}
} | 292 |
2,268 | <reponame>joshmartel/source-sdk-2013
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "server_class.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ServerClass *g_pServerClassHead=0;
| 115 |
341 | package dev.morphia.aggregation.experimental.codecs;
import dev.morphia.aggregation.experimental.codecs.stages.AddFieldsCodec;
import dev.morphia.aggregation.experimental.codecs.stages.AutoBucketCodec;
import dev.morphia.aggregation.experimental.codecs.stages.BucketCodec;
import dev.morphia.aggregation.experimental.codecs.stages.CollectionStatsCodec;
import dev.morphia.aggregation.experimental.codecs.stages.CountCodec;
import dev.morphia.aggregation.experimental.codecs.stages.CurrentOpCodec;
import dev.morphia.aggregation.experimental.codecs.stages.FacetCodec;
import dev.morphia.aggregation.experimental.codecs.stages.GeoNearCodec;
import dev.morphia.aggregation.experimental.codecs.stages.GraphLookupCodec;
import dev.morphia.aggregation.experimental.codecs.stages.GroupCodec;
import dev.morphia.aggregation.experimental.codecs.stages.IndexStatsCodec;
import dev.morphia.aggregation.experimental.codecs.stages.LimitCodec;
import dev.morphia.aggregation.experimental.codecs.stages.LookupCodec;
import dev.morphia.aggregation.experimental.codecs.stages.MatchCodec;
import dev.morphia.aggregation.experimental.codecs.stages.MergeCodec;
import dev.morphia.aggregation.experimental.codecs.stages.OutCodec;
import dev.morphia.aggregation.experimental.codecs.stages.PlanCacheStatsCodec;
import dev.morphia.aggregation.experimental.codecs.stages.ProjectionCodec;
import dev.morphia.aggregation.experimental.codecs.stages.RedactCodec;
import dev.morphia.aggregation.experimental.codecs.stages.ReplaceRootCodec;
import dev.morphia.aggregation.experimental.codecs.stages.ReplaceWithCodec;
import dev.morphia.aggregation.experimental.codecs.stages.SampleCodec;
import dev.morphia.aggregation.experimental.codecs.stages.SkipCodec;
import dev.morphia.aggregation.experimental.codecs.stages.SortByCountCodec;
import dev.morphia.aggregation.experimental.codecs.stages.SortCodec;
import dev.morphia.aggregation.experimental.codecs.stages.StageCodec;
import dev.morphia.aggregation.experimental.codecs.stages.UnionWithCodec;
import dev.morphia.aggregation.experimental.codecs.stages.UnsetCodec;
import dev.morphia.aggregation.experimental.codecs.stages.UnwindCodec;
import dev.morphia.aggregation.experimental.expressions.impls.Expression;
import dev.morphia.aggregation.experimental.stages.AddFields;
import dev.morphia.aggregation.experimental.stages.AutoBucket;
import dev.morphia.aggregation.experimental.stages.Bucket;
import dev.morphia.aggregation.experimental.stages.CollectionStats;
import dev.morphia.aggregation.experimental.stages.Count;
import dev.morphia.aggregation.experimental.stages.CurrentOp;
import dev.morphia.aggregation.experimental.stages.Facet;
import dev.morphia.aggregation.experimental.stages.GeoNear;
import dev.morphia.aggregation.experimental.stages.GraphLookup;
import dev.morphia.aggregation.experimental.stages.Group;
import dev.morphia.aggregation.experimental.stages.IndexStats;
import dev.morphia.aggregation.experimental.stages.Limit;
import dev.morphia.aggregation.experimental.stages.Lookup;
import dev.morphia.aggregation.experimental.stages.Match;
import dev.morphia.aggregation.experimental.stages.Merge;
import dev.morphia.aggregation.experimental.stages.Out;
import dev.morphia.aggregation.experimental.stages.PlanCacheStats;
import dev.morphia.aggregation.experimental.stages.Projection;
import dev.morphia.aggregation.experimental.stages.Redact;
import dev.morphia.aggregation.experimental.stages.ReplaceRoot;
import dev.morphia.aggregation.experimental.stages.ReplaceWith;
import dev.morphia.aggregation.experimental.stages.Sample;
import dev.morphia.aggregation.experimental.stages.Skip;
import dev.morphia.aggregation.experimental.stages.Sort;
import dev.morphia.aggregation.experimental.stages.SortByCount;
import dev.morphia.aggregation.experimental.stages.UnionWith;
import dev.morphia.aggregation.experimental.stages.Unset;
import dev.morphia.aggregation.experimental.stages.Unwind;
import dev.morphia.mapping.Mapper;
import org.bson.codecs.Codec;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings({"rawtypes", "unchecked"})
public class AggregationCodecProvider implements CodecProvider {
private final Codec expressionCodec;
private final Mapper mapper;
private Map<Class, StageCodec> codecs;
public AggregationCodecProvider(Mapper mapper) {
this.mapper = mapper;
expressionCodec = new ExpressionCodec(this.mapper);
}
@Override
public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
Codec<T> codec = getCodecs().get(clazz);
if (codec == null) {
if (Expression.class.isAssignableFrom(clazz)) {
codec = expressionCodec;
}
}
return codec;
}
private Map<Class, StageCodec> getCodecs() {
if (codecs == null) {
codecs = new HashMap<>();
// Stages
codecs.put(AddFields.class, new AddFieldsCodec(mapper));
codecs.put(AutoBucket.class, new AutoBucketCodec(mapper));
codecs.put(Bucket.class, new BucketCodec(mapper));
codecs.put(CollectionStats.class, new CollectionStatsCodec(mapper));
codecs.put(Count.class, new CountCodec(mapper));
codecs.put(CurrentOp.class, new CurrentOpCodec(mapper));
codecs.put(Facet.class, new FacetCodec(mapper));
codecs.put(GeoNear.class, new GeoNearCodec(mapper));
codecs.put(GraphLookup.class, new GraphLookupCodec(mapper));
codecs.put(Group.class, new GroupCodec(mapper));
codecs.put(IndexStats.class, new IndexStatsCodec(mapper));
codecs.put(Merge.class, new MergeCodec(mapper));
codecs.put(PlanCacheStats.class, new PlanCacheStatsCodec(mapper));
codecs.put(Limit.class, new LimitCodec(mapper));
codecs.put(Lookup.class, new LookupCodec(mapper));
codecs.put(Match.class, new MatchCodec(mapper));
codecs.put(Out.class, new OutCodec(mapper));
codecs.put(Projection.class, new ProjectionCodec(mapper));
codecs.put(Redact.class, new RedactCodec(mapper));
codecs.put(ReplaceRoot.class, new ReplaceRootCodec(mapper));
codecs.put(ReplaceWith.class, new ReplaceWithCodec(mapper));
codecs.put(Sample.class, new SampleCodec(mapper));
codecs.put(Skip.class, new SkipCodec(mapper));
codecs.put(Sort.class, new SortCodec(mapper));
codecs.put(SortByCount.class, new SortByCountCodec(mapper));
codecs.put(UnionWith.class, new UnionWithCodec(mapper));
codecs.put(Unset.class, new UnsetCodec(mapper));
codecs.put(Unwind.class, new UnwindCodec(mapper));
}
return codecs;
}
}
| 2,631 |
360 | import abc
from typing import Tuple
domain_context_registry = {}
class DomainContext(abc.ABC):
class __metaclass__(type):
def __init__(cls, name, b, d):
type.__init__(cls, name, b, d)
domain_context_registry[name] = cls
_known_fluid_fields: Tuple[Tuple[str, str], ...]
_known_particle_fields: Tuple[Tuple[str, str], ...]
def __init__(self, ds):
self.ds = ds
| 192 |
1,016 | /**
*
*/
package com.thinkbiganalytics.metadata.sla.spi.core;
/*-
* #%L
* thinkbig-sla-core
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.google.common.collect.ComparisonChain;
import com.thinkbiganalytics.metadata.sla.api.AssessmentResult;
import com.thinkbiganalytics.metadata.sla.api.MetricAssessment;
import com.thinkbiganalytics.metadata.sla.api.Obligation;
import com.thinkbiganalytics.metadata.sla.api.ObligationAssessment;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
*/
public class SimpleObligationAssessment implements ObligationAssessment {
public static final Comparator<ObligationAssessment> DEF_COMPARATOR = new DefaultComparator();
private static final long serialVersionUID = -6209570471757886664L;
private Obligation obligation;
private String message = "";
private AssessmentResult result = AssessmentResult.SUCCESS;
private Set<MetricAssessment> metricAssessments;
private Comparator<ObligationAssessment> comparator = DEF_COMPARATOR;
private List<Comparable<? extends Serializable>> comparables = Collections.emptyList();
/**
*
*/
protected SimpleObligationAssessment() {
this.metricAssessments = new HashSet<MetricAssessment>();
}
public SimpleObligationAssessment(Obligation obligation) {
this();
this.obligation = obligation;
}
public SimpleObligationAssessment(Obligation obligation, String message, AssessmentResult result) {
this();
this.obligation = obligation;
this.message = message;
this.result = result;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.sla.api.ObligationAssessment#getObligation()
*/
@Override
public Obligation getObligation() {
return this.obligation;
}
protected void setObligation(Obligation obligation) {
this.obligation = obligation;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.sla.api.ObligationAssessment#getMessage()
*/
@Override
public String getMessage() {
return this.message;
}
protected void setMessage(String message) {
this.message = message;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.sla.api.ObligationAssessment#getResult()
*/
@Override
public AssessmentResult getResult() {
return this.result;
}
protected void setResult(AssessmentResult result) {
this.result = result;
}
/* (non-Javadoc)
* @see com.thinkbiganalytics.metadata.sla.api.ObligationAssessment#getMetricAssessments()
*/
@Override
public Set<MetricAssessment> getMetricAssessments() {
return new HashSet<MetricAssessment>(this.metricAssessments);
}
protected void setMetricAssessments(Set<MetricAssessment> metricAssessments) {
this.metricAssessments = metricAssessments;
}
@Override
public int compareTo(ObligationAssessment obAssessment) {
return this.comparator.compare(this, obAssessment);
}
protected boolean add(MetricAssessment assessment) {
return this.metricAssessments.add(assessment);
}
protected boolean addAll(Collection<? extends MetricAssessment> assessments) {
return this.metricAssessments.addAll(assessments);
}
protected void setComparator(Comparator<ObligationAssessment> comparator) {
this.comparator = comparator;
}
protected void setComparables(List<Comparable<? extends Serializable>> comparables) {
this.comparables = comparables;
}
protected static class DefaultComparator implements Comparator<ObligationAssessment> {
@Override
public int compare(ObligationAssessment o1, ObligationAssessment o2) {
ComparisonChain chain = ComparisonChain
.start()
.compare(o1.getResult(), o2.getResult());
if (o1 instanceof SimpleObligationAssessment && o2 instanceof SimpleObligationAssessment) {
SimpleObligationAssessment s1 = (SimpleObligationAssessment) o1;
SimpleObligationAssessment s2 = (SimpleObligationAssessment) o2;
for (int idx = 0; idx < s1.comparables.size(); idx++) {
chain = chain.compare(s1.comparables.get(idx), s2.comparables.get(idx));
}
}
if (chain.result() != 0) {
return chain.result();
}
List<MetricAssessment<Serializable>> list1 = new ArrayList<>(o1.getMetricAssessments());
List<MetricAssessment<Serializable>> list2 = new ArrayList<>(o2.getMetricAssessments());
chain = chain.compare(list1.size(), list2.size());
Collections.sort(list1);
Collections.sort(list2);
for (int idx = 0; idx < list1.size(); idx++) {
chain = chain.compare(list1.get(idx), list2.get(idx));
}
return chain.result();
}
}
}
| 2,194 |
17,318 | /*
* Copyright (c) 2011-2018, <NAME>. All Rights Reserved.
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dianping.cat.report.service;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.unidal.lookup.ContainerHolder;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import com.dianping.cat.message.internal.DefaultEvent;
import com.dianping.cat.message.internal.DefaultMessageProducer;
public abstract class ModelServiceWithCalSupport extends ContainerHolder {
private Transaction m_current;
protected void logError(Throwable cause) {
StringWriter writer = new StringWriter(2048);
cause.printStackTrace(new PrintWriter(writer));
if (cause instanceof Error) {
logEvent("Error", cause.getClass().getName(), "ERROR", writer.toString());
} else if (cause instanceof RuntimeException) {
logEvent("RuntimeException", cause.getClass().getName(), "ERROR", writer.toString());
} else {
logEvent("Exception", cause.getClass().getName(), "ERROR", writer.toString());
}
}
protected void logEvent(String type, String name, String status, String nameValuePairs) {
DefaultEvent event = new DefaultEvent(type, name);
m_current.addChild(event);
if (nameValuePairs != null && nameValuePairs.length() > 0) {
event.addData(nameValuePairs);
}
event.setStatus(status);
event.complete();
}
protected Transaction newTransaction(String type, String name) {
DefaultMessageProducer cat = (DefaultMessageProducer) Cat.getProducer();
return cat.newTransaction(m_current, type, name);
}
protected void setParentTransaction(Transaction current) {
m_current = current;
}
}
| 690 |
420 | <reponame>RetroFlix/retroflix.repo<gh_stars>100-1000
# -*- coding: UTF-8 -*-
#
# Copyright (C) 2020, <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# pylint: disable=missing-docstring
"""Functions to interact with Trakt API."""
from __future__ import absolute_import, unicode_literals
from . import api_utils
from . import get_imdb_id
try:
from typing import Optional, Text, Dict, List, Any # pylint: disable=unused-import
InfoType = Dict[Text, Any] # pylint: disable=invalid-name
except ImportError:
pass
HEADERS = (
('User-Agent', 'Kodi Movie scraper by Team Kodi'),
('Accept', 'application/json'),
('trakt-api-key', '<KEY>'),
('trakt-api-version', '2'),
('Content-Type', 'application/json'),
)
api_utils.set_headers(dict(HEADERS))
MOVIE_URL = 'https://api.trakt.tv/movies/{}'
def get_trakt_ratinginfo(uniqueids):
imdb_id = get_imdb_id(uniqueids)
result = {}
url = MOVIE_URL.format(imdb_id)
params = {'extended': 'full'}
movie_info = api_utils.load_info(url, params=params, default={})
if(movie_info):
if 'votes' in movie_info and 'rating' in movie_info:
result['ratings'] = {'trakt': {'votes': int(movie_info['votes']), 'rating': float(movie_info['rating'])}}
elif 'rating' in movie_info:
result['ratings'] = {'trakt': {'rating': float(movie_info['rating'])}}
return result
| 707 |
1,418 | package aima.core.logic.planning;
import aima.core.logic.fol.kb.data.Literal;
import java.util.*;
/**
* Artificial Intelligence A Modern Approach (3rd Edition): Figure 10.9 page
* 383.<br>
* <br>
*
* <pre>
*
* function GRAPHPLAN(problem) returns solution or failure
*
* graph ← INITIAL-PLANNING-GRAPH(problem)
* goals ← CONJUNCTS(problem.GOAL)
* nogoods ← an empty hash table
* for tl = 0 to ∞ do
* if goals all non-mutex in St of graph then
* solution ← EXTRACT-SOLUTION(graph, goals, NUMLEVELS(graph), nogoods)
* if solution ≠ failure then return solution
* if graph and nogoods have both leveled off then return failure
* graph ← EXPAND-GRAPH(graph, problem)
* </pre>
* <p>
* Figure 10.9 The GRAPHPLAN algorithm. GRAPHPLAN calls EXPAND-GRAPH to add a
* level until either a solution is found by EXTRACT-SOLUTION, or no solution
* is possible.
*
* @author samagra
*/
public class GraphPlanAlgorithm {
/**
* function GRAPHPLAN(problem) returns solution or failure
*
* @param problem the planning problem for which the plan is to be created
* @return a solution or null
*/
public List<List<ActionSchema>> graphPlan(Problem problem) {
//graph ← INITIAL-PLANNING-GRAPH(problem)
Graph graph = initialPlanningGraph(problem);
// goals ← CONJUNCTS(problem.GOAL)
List<Literal> goals = conjuncts(problem.getGoalState());
// nogoods ← an empty hash table
Hashtable<Integer, List<Literal>> nogoods = new Hashtable<>();
Level state;
// for tl = 0 to ∞ do
for (int tl = 0; ; tl++) {
//St
state = graph.getLevels().get(2 * tl);
// if goals all non-mutex in St of graph then
if (checkAllGoalsNonMutex(state, goals)) {
// solution ← EXTRACT-SOLUTION(graph, goals, NUMLEVELS(graph), nogoods)
List<List<ActionSchema>> solution = extractSolution(graph, goals, graph.numLevels(), nogoods);
//if solution ≠ failure then return solution
if (solution != null && solution.size() != 0)
return solution;
}
// if graph and nogoods have both leveled off then return failure
if (levelledOff(graph) && leveledOff(nogoods)) {
return null;
}
// graph ← EXPAND-GRAPH(graph, problem)
graph = expandGraph(graph);
}
}
/**
* This method extracts a solution from the planning graph.
* <p>
* Artificial Intelligence A Modern Approach (3rd Edition): page 384.<br>
* <p>
* We can define EXTRACT -SOLUTION as a backward search problem, where
* each state in the search contains a pointer to a level in the planning graph and a set of unsat-
* isfied goals. We define this search problem as follows:
* • The initial state is the last level of the planning graph, S n , along with the set of goals
* from the planning problem.
* • The actions available in a state at level S i are to select any conflict-free subset of the
* actions in A i−1 whose effects cover the goals in the state. The resulting state has level
* S i−1 and has as its set of goals the preconditions for the selected set of actions. By
* “conflict free,” we mean a set of actions such that no two of them are mutex and no two
* of their preconditions are mutex.
* • The goal is to reach a state at level S 0 such that all the goals are satisfied.
* • The cost of each action is 1.
*
* @param graph The planning graph.
* @param goals Goals of the planning problem.
* @param numLevel Number of levels in the graph.
* @param nogoods A hash table to store previously calculated results.
* @return a solution if found else null
*/
private List<List<ActionSchema>> extractSolution(Graph graph, List<Literal> goals, int numLevel,
Hashtable<Integer, List<Literal>> nogoods) {
if (nogoods.contains(numLevel))
return null;
int level = (graph.numLevels() - 1) / 2;
List<Literal> goalsCurr = goals;
List<List<ActionSchema>> solution = new ArrayList<>();
Level currLevel = graph.getLevels().get(2 * level);
while (level > 0) {
List<List<ActionSchema>> setOfPossibleActions = new ArrayList<>();
HashMap<Object, List<Object>> mutexLinks = currLevel.getPrevLevel().getMutexLinks();
for (Literal literal :
goalsCurr) {
List<ActionSchema> possiBleActionsPerLiteral = new ArrayList<>();
for (Object action :
currLevel.getPrevLinks().get(literal)) {
possiBleActionsPerLiteral.add((ActionSchema) action);
}
setOfPossibleActions.add(possiBleActionsPerLiteral);
}
List<List<ActionSchema>> allPossibleSubSets = generateCombinations(setOfPossibleActions);
boolean validSet;
List<ActionSchema> setToBeTaken = null;
for (List<ActionSchema> possibleSet :
allPossibleSubSets) {
validSet = true;
ActionSchema firstAction, secondAction;
for (int i = 0; i < possibleSet.size(); i++) {
firstAction = possibleSet.get(i);
for (int j = i + 1; j < possibleSet.size(); j++) {
secondAction = possibleSet.get(j);
if (mutexLinks.containsKey(firstAction) && mutexLinks.get(firstAction).contains(secondAction))
validSet = false;
}
}
if (validSet) {
setToBeTaken = possibleSet;
break;
}
}
if (setToBeTaken == null) {
nogoods.put(level, goalsCurr);
return null;
}
level--;
currLevel = graph.getLevels().get(2 * level);
goalsCurr.clear();
solution.add(setToBeTaken);
for (ActionSchema action :
setToBeTaken) {
for (Literal literal :
action.getPrecondition()) {
if (!goalsCurr.contains(literal)) {
goalsCurr.add(literal);
}
}
}
}
return solution;
}
/**
* This method is used to check if all goals are present in a particular state
* and none of them has a mutex link.
*
* @param level The current level in which to check for the goals.
* @param goals List of goals to be checked
* @return Boolean representing if goals all non mutex in St
*/
private boolean checkAllGoalsNonMutex(Level level, List<Literal> goals) {
if (!level.getLevelObjects().containsAll(goals)) {
return false;
}
boolean mutexCheck = false;
for (Object literal :
goals) {
List<Object> mutexOfGoal = level.getMutexLinks().get(literal);
if (mutexOfGoal != null) {
for (Object object :
mutexOfGoal) {
if (goals.contains((Literal) object)) {
mutexCheck = true;
break;
}
}
}
}
return (!mutexCheck);
}
/**
* This method adds a new state (a state level and an action level both) to the planning graph.
*
* @param graph The planning graph.
* @return The expanded graph.
*/
private Graph expandGraph(Graph graph) {
return graph.addLevel().addLevel();
}
/**
* A graph is said to be levelled off if two consecutive levels are identical.
*
* @param nogoods
* @return Boolean stating if the hashtable is levelled off.
*/
private boolean leveledOff(Hashtable<Integer, List<Literal>> nogoods) {
if (nogoods.size() < 2)
return false;
return nogoods.get(nogoods.size() - 1).equals(nogoods.get(nogoods.size() - 2));
}
/**
* A graph is said to be levelled off if two consecutive levels are identical.
*
* @param graph
* @return Boolean stating if the graph is levelled off.
*/
private boolean levelledOff(Graph graph) {
if (graph.numLevels() < 2)
return false;
return graph.levels.get(graph.numLevels() - 1).equals(graph.levels.get(graph.numLevels() - 2));
}
/**
* Returns a list of literals in a state.
*
* @param goalState
* @return List of literals.
*/
private List<Literal> conjuncts(State goalState) {
return goalState.getFluents();
}
/**
* This method initialises the planning graph for a particular problem.
*
* @param problem The planning problem.
* @return Graph for the planning problem.
*/
private Graph initialPlanningGraph(Problem problem) {
Level initialLevel = new Level(null, problem);
return new Graph(problem, initialLevel);
}
// Helper methods for combinations and permutations.
public List<List<ActionSchema>> combineTwoLists(List<ActionSchema> firstList, List<ActionSchema> secondList) {
List<List<ActionSchema>> result = new ArrayList<>();
for (ActionSchema firstAction :
firstList) {
for (ActionSchema secondAction :
secondList) {
result.add(Arrays.asList(firstAction, secondAction));
}
}
return result;
}
public List<List<ActionSchema>> combineExtraList(List<List<ActionSchema>> combinedList, List<ActionSchema> newList) {
List<List<ActionSchema>> result = new ArrayList<>();
for (List<ActionSchema> combined :
combinedList) {
for (ActionSchema action :
newList) {
List<ActionSchema> tempList = new ArrayList<>(combined);
tempList.add(action);
result.add(tempList);
}
}
return result;
}
public List<List<ActionSchema>> generateCombinations(List<List<ActionSchema>> actionLists) {
List<List<ActionSchema>> result = new ArrayList<>();
if (actionLists.size() == 1) {
result.add(actionLists.get(0));
return result;
}
if (actionLists.size() == 2) {
return combineTwoLists(actionLists.get(0), actionLists.get(1));
} else {
result = combineTwoLists(actionLists.get(0), actionLists.get(1));
for (int i = 2; i < actionLists.size(); i++) {
result = combineExtraList(result, actionLists.get(i));
}
return result;
}
}
}
| 5,015 |
3,083 | // Copyright 2011-2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef BASECONNECTION_HPP
#define BASECONNECTION_HPP
#include <string>
#include "defs.hpp"
#include "errors.hpp"
#include "commands.hpp"
#undef htonl
#undef ntohl
// Some forward declarations
class InformationProvider;
/**
* Base class for connections between BinNavi and the debug client.
*
* All connection policies must inherit from this class.
**/
class BaseConnection {
private:
// Creates a packet header
RDBG_PROTO_HDR createPacketHeader(const commandtype_t command,
unsigned int id,
unsigned int argnr) const;
// Creates an integer argument header that can be used in packets
DBG_PROTO_ARG createIntegerArgumentHeader() const;
// Creates an address argument header that can be used in packets
DBG_PROTO_ARG createAddressArgumentHeader() const;
// Creates a string argument header that can be used in packets
DBG_PROTO_ARG createStringArgumentHeader(unsigned int size) const;
// Creates an address argument that can be used in packets
DBG_PROTO_ARG_ADDRESS createAddressArgument(CPUADDRESS address) const;
// Adds an integer argument header and an integer argument to a packet
void addIntegerArgument(PacketBuffer& buffer, unsigned int value) const;
// Adds an address argument header and an address argument to a packet
void addAddressArgument(PacketBuffer& buffer, CPUADDRESS address) const;
/**
* Adds a string argument header and a string argument to a packet.
*
* @param buffer The packet to add to.
* @param str The string to add to the packet.
**/
template <typename T>
void addStringArgument(PacketBuffer& buffer, const T& str) const {
// This function needs to be templatized because T can be either
// std::string or std::vector<char>
// String argument header
buffer.add(createStringArgumentHeader(str.size()));
// String argument
buffer.add(&str[0], str.size());
}
// Sends a packet with a single integer value to BinNavi
NaviError sendIntegerReply(const commandtype_t command, unsigned int id,
unsigned int value) const;
// Sends a packet with two integer values to BinNavi
NaviError sendIntegerIntegerReply(const commandtype_t command,
unsigned int id, unsigned int value1,
unsigned int value2) const;
// Sends a packet with three integer values to BinNavi
NaviError sendIntegerIntegerIntegerReply(const commandtype_t command,
unsigned int id,
unsigned int value1,
unsigned int value2,
unsigned int value3) const;
// Sends a packet with a variable number of integer values to BinNavi
NaviError sendIntegersReply(const commandtype_t, unsigned int id,
unsigned int* values,
unsigned int nrvalues) const;
// Sends a packet with one address to BinNavi
NaviError sendAddressReply(const commandtype_t command, unsigned int id,
CPUADDRESS address) const;
// Sends a packet with two addresses to BinNavi
NaviError sendDoubleAddressReply(const commandtype_t command,
unsigned int id,
CPUADDRESS address1,
CPUADDRESS address2) const;
// Sends a packet with information about multiple addresses to BinNavi
NaviError sendAddressesReply(const commandtype_t command, unsigned int id,
const CPUADDRESS* addresses,
unsigned int nraddresses) const;
NaviError sendBreakpointsReply(
const commandtype_t command,
unsigned int id,
const std::vector<std::pair<CPUADDRESS, unsigned int> >& results) const;
// Sends a packet with an integer value and an address to BinNavi
NaviError sendIntegerAddressReply(const commandtype_t command,
unsigned int id, unsigned int value,
CPUADDRESS address) const;
// Sends a packet with an integer value and two addresses to BinNavi
NaviError sendIntegerAddressAddressReply(const commandtype_t command,
unsigned int id,
unsigned int value,
CPUADDRESS address1,
CPUADDRESS address2) const;
// Sends a packet with two integer values and an address to BinNavi
NaviError sendIntegerIntegerAddressReply(const commandtype_t command,
unsigned int id,
unsigned int value1,
unsigned int value2,
CPUADDRESS value3) const;
// Sends a packet with string information to BinNavi
NaviError sendString(const commandtype_t type, unsigned int id,
const std::string& str) const;
// Sends a packet with register values to BinNavi
NaviError sendRegistersReply(commandtype_t type, unsigned int id,
const std::string& regString) const;
// Sends a packet with information about a breakpoint event to BinNavi
NaviError sendEventReply(commandtype_t type, unsigned int id,
unsigned int tid,
const std::string& regString) const;
// Sends a packet with the process information of the running processes to
//BinNavi.
NaviError sendListProcessesReply(
commandtype_t type, unsigned int id,
const std::string& processListString) const;
// Sends a packet with file system information to BinNavi
NaviError sendListFilesReply(commandtype_t type, unsigned int id,
const std::string& str) const;
// Sends a packet with memory data to BinNavi
NaviError sendMemoryReply(unsigned int id, CPUADDRESS address,
const MemoryContainer& memrange) const;
// Sends a packet that contains information about a suspended process to
//BinNavi
NaviError sendSuspendedReply(const commandtype_t command, unsigned int id,
const InformationProvider& provider) const;
// Reads a packet header from BinNavi
NaviError readHeader(RDBG_PROTO_HDR& hdr) const;
// Reads a packet argument header from BinNavi
NaviError readArgumentHeader(DBG_PROTO_ARG& arg) const;
// Reads a single integer argument from BinNavi
NaviError readIntegerArgument(unsigned int& arg) const;
// Reads a single address argument from BinNavi
NaviError readAddressArgument(DBG_PROTO_ARG_ADDRESS& arg) const;
// Reads a packet without additional information from BinNavi
NaviError readSimplePacket(Packet* p) const;
// Reads a packet with a single integer argument from BinNavi
NaviError readIntegerPacket(Packet* p) const;
// Reads a packet with a single address argument from BinNavi
NaviError readAddressPacket(Packet* p) const;
// Reads a packet with a single address argument and without an address
//header from BinNavi
NaviError readAddressPacketRaw(Packet* p) const;
// Reads a single data argument from BinNavi
NaviError readDataPacket(Packet* p) const;
// Reads a packet that contains an address and binary data
NaviError readAddressDataPacket(Packet* p) const;
// Reads a packet with memory range information from BinNavi
NaviError readMemoryPacket(Packet* p) const;
// Reads a packet with information about setting a register value from
//BinNavi
NaviError readSetRegisterPacket(Packet* p) const;
// Reads a packet with memory search information from BinNavi
NaviError readSearchPacket(Packet* p) const;
// Reads a packet that contains a bunch of addresses
NaviError readAddressesPacket(Packet* p) const;
NaviError readLongPacketRaw(Packet* p) const;
NaviError readExceptionSettingsPacket(Packet* p) const;
NaviError readSetDebuggerEventSettingsPacket(Packet* p) const;
protected:
/**
* Sends a specified number of bytes from a given buffer to BinNavi.
*
* @param buffer The source buffer.
* @param size The size of the buffer.
*
* @return A NaviError code that describes whether the operation was
* successful or not.
**/
virtual NaviError send(const char* buffer, unsigned int size) const = 0;
/**
* Reads a specified number of incoming bytes from BinNavi.
*
* Note that the buffer is guaranteed to be large enough to hold the
* specified number of bytes.
*
* @param buffer The destination buffer.
* @param size Number of bytes to read.
*
* @return A NaviError code that describes whether the operation was
* successful or not.
**/
virtual NaviError read(char* buffer, unsigned int size) const = 0;
#ifndef NAVI_GDB_OSX
/**
* Converts values between host and network byte order.
*
* TODO: Investigate potential problems when passing unsigned ints.
*
* @param value The value in host byte order.
*
* @return The value in network byte order.
**/
virtual int htonl(int value) const = 0;
/**
* Converts values between network and host byte order.
*
* TODO: Investigate potential problems when passing unsigned ints.
*
* @param value The value in network byte order.
*
* @return The value in host byte order.
**/
virtual int ntohl(int value) const = 0;
#endif
public:
/**
* Initializes the connection to BinNavi.
*
* @return A NaviError code that describes whether the operation was
* successful or not.
**/
virtual NaviError initializeConnection() = 0;
/**
* Closes the connection to BinNavi.
*
* @return A NaviError code that describes whether the operation was
* successful or not.
**/
virtual NaviError closeConnection() = 0;
/**
* Indicates whether data from BinNavi is incoming.
*
* @return True, if incoming data is ready to be read. False, otherwise.
**/
virtual bool hasData() const = 0;
/**
* Opens a connection and waits for BinNavi to connect.
*
* @return A NaviError code that describes whether the operation was
* successful or not.
**/
virtual NaviError waitForConnection() = 0;
virtual ~BaseConnection() {}
// Reads an incoming debug command packet from BinNavi
NaviError readPacket(Packet* p) const;
// Sends a debug reply without any additional arguments to BinNavi
NaviError sendSimpleReply(const commandtype_t command, unsigned int id) const;
// Sends a debug reply that signals that an earlier received debug command
// was successfully executed.
NaviError sendSuccessReply(const Packet* p,
const InformationProvider& info) const;
// Sends a debug reply that signals that an earlier received debug command
// failed.
NaviError sendErrorReply(const Packet* p, NaviError error) const;
// Sends information about a breakpoint event to BinNavi.
NaviError sendBreakpointEvent(const DBGEVT* dbg) const;
// Sends information that the target process closed to BinNavi.
NaviError sendProcessClosedEvent(const DBGEVT* dbg) const;
// Sends a debug reply that is not the result of an earlier debug command.
NaviError sendDebugEvent(const DBGEVT* event) const;
// Sends the initial debugger information string to BinNavi
NaviError sendInfoString(const std::string& infoString) const;
// Sends the initial authentication string to BinNavi
NaviError sendAuthentication() const;
// Prints information about connection (e.g. IP)
virtual void printConnectionInfo() = 0;
};
#endif
| 4,414 |
11,356 | // (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 <NAME>
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.)
// See http://www.boost.org/libs/iostreams for documentation.
#include <algorithm> // equal.
#include <fstream>
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/detail/adapter/direct_adapter.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "detail/sequence.hpp"
#include "detail/temp_file.hpp"
#include "detail/verification.hpp"
using namespace std;
using namespace boost::iostreams;
using namespace boost::iostreams::test;
using boost::unit_test::test_suite;
void direct_adapter_test()
{
typedef boost::iostreams::detail::direct_adapter<array_source>
indirect_array_source;
typedef boost::iostreams::detail::direct_adapter<array_sink>
indirect_array_sink;
typedef boost::iostreams::detail::direct_adapter<boost::iostreams::array>
indirect_array;
typedef stream<indirect_array_source>
indirect_array_istream;
typedef stream<indirect_array_sink>
indirect_array_ostream;
typedef stream<indirect_array>
indirect_array_stream;
test_file test;
test_sequence<> seq;
//--------------indirect_array_istream------------------------------------//
{
indirect_array_istream first(&seq[0], &seq[0] + seq.size());
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chars(first, second),
"failed reading from indirect_array_istream in chars"
);
}
{
indirect_array_istream first(&seq[0], &seq[0] + seq.size());
ifstream second(test.name().c_str());
BOOST_CHECK_MESSAGE(
compare_streams_in_chunks(first, second),
"failed reading from indirect_array_istream in chunks"
);
}
//--------------indirect_array_ostream------------------------------------//
{
vector<char> dest(data_reps * data_length(), '?');
indirect_array_ostream out(&dest[0], &dest[0] + dest.size());
write_data_in_chars(out);
BOOST_CHECK_MESSAGE(
std::equal(seq.begin(), seq.end(), dest.begin()),
"failed writing to indirect_array_ostream in chunks"
);
}
{
vector<char> dest(data_reps * data_length(), '?');
indirect_array_ostream out(&dest[0], &dest[0] + dest.size());
write_data_in_chunks(out);
BOOST_CHECK_MESSAGE(
std::equal(seq.begin(), seq.end(), dest.begin()),
"failed writing to indirect_array_ostream in chunks"
);
}
//--------------indirect_array_stream-------------------------------------//
{
vector<char> test(data_reps * data_length(), '?');
indirect_array_stream io(&test[0], &test[0] + test.size());
BOOST_CHECK_MESSAGE(
test_seekable_in_chars(io),
"failed seeking within indirect_array_stream, in chars"
);
}
{
vector<char> test(data_reps * data_length(), '?');
indirect_array_stream io(&test[0], &test[0] + test.size());
BOOST_CHECK_MESSAGE(
test_seekable_in_chunks(io),
"failed seeking within indirect_array_stream, in chunks"
);
}
}
test_suite* init_unit_test_suite(int, char* [])
{
test_suite* test = BOOST_TEST_SUITE("direct_adapter test");
test->add(BOOST_TEST_CASE(&direct_adapter_test));
return test;
}
| 1,647 |
348 | {"nom":"Crossac","circ":"7ème circonscription","dpt":"Loire-Atlantique","inscrits":2118,"abs":1288,"votants":830,"blancs":58,"nuls":55,"exp":717,"res":[{"nuance":"REM","nom":"<NAME>","voix":491},{"nuance":"LR","nom":"<NAME>","voix":226}]} | 94 |
485 | <reponame>lupyuen/evm<gh_stars>100-1000
#ifdef CONFIG_EVM_MODULE_HTTP
#include "evm_module.h"
#include <rtthread.h>
#include "webclient.h"
#define HTTP_HEADER_SIZE (1024)
#define HTTP_RECV_MAX_SIZE (10 * 1024)
//request.abort()
static evm_val_t evm_module_http_request_abort(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
struct webclient_session *session = evm_object_get_ext_data(p);
if (!session)
return EVM_VAL_UNDEFINED;
webclient_close(session);
}
//request.end([data][, callback])
static evm_val_t evm_module_http_request_end(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
evm_module_http_request_write(e, p, argc, v);
if (webclient_get(session, url) != 200)
{
return EVM_VAL_UNDEFINED
}
int flag = 0;
if (argc > 1 && evm_is_script(v + 1))
flag = 1;
int bytes_read = 0, content_pos = 0;
int content_length = webclient_content_length_get(session);
do
{
bytes_read = webclient_read(session, buffer, 1024);
if (bytes_read <= 0)
{
break;
}
if (flag)
evm_run_callback(e, v + 1, &e->scope, NULL, 0);
content_pos += bytes_read;
} while (content_pos < content_length);
return EVM_VAL_UNDEFINED;
}
//request.setTimeout(ms[, callback])
static evm_val_t evm_module_http_request_setTimeout(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
//ms秒之后,销毁socket,并执行回调函数
if (argc < 0 || !evm_is_integer(v))
return EVM_VAL_UNDEFINED;
uint32_t timeout = evm_2_integer(v);
if (timeout < 0)
return EVM_VAL_UNDEFINED;
struct webclient_session *session = evm_object_get_ext_data(p);
if (!session)
return EVM_VAL_UNDEFINED;
webclient_set_timeout(session, timeout);
return EVM_VAL_NULL;
}
//request.write(data[, callback])
static evm_val_t evm_module_http_request_write(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 1 || !evm_is_string(v) || !evm_is_buffer(v))
return EVM_VAL_UNDEFINED;
struct webclient_session *session = evm_object_get_ext_data(p);
if (!session)
return EVM_VAL_UNDEFINED;
evm_val_t *buf = v;
int result = 0;
if (evm_is_string(v))
{
result = webclient_write(session, evm_2_string(v), evm_string_len(v));
}
else
{
result = webclient_write(session, evm_buffer_addr(buf), evm_buffer_len(buf))
}
if (argc > 1 && evm_is_script(v + 1))
{
evm_run_callback(e, v + 1, &e->scope, NULL, 0);
}
if (result > 0)
return EVM_VAL_TRUE;
return EVM_VAL_FALSE;
}
static evm_val_t evm_module_http_client_new(e)
{
evm_val_t *obj = evm_object_create(e, GC_DICT, 9, 0);
if (obj)
{
evm_prop_append(e, obj, "abort", evm_mk_native((intptr_t)evm_module_http_request_abort));
evm_prop_append(e, obj, "end", evm_mk_native((intptr_t)evm_module_http_request_end));
evm_prop_append(e, obj, "setTimeout", evm_mk_native((intptr_t)evm_module_http_request_setTimeout));
evm_prop_append(e, obj, "write", evm_mk_native((intptr_t)evm_module_http_request_write));
struct webclient_session *session = evm_malloc(sizeof(struct webclient_session));
if (session)
{
evm_object_set_ext_data(obj, (intptr_t)session);
}
return *obj;
}
return EVM_VAL_UNDEFINED;
}
//http.request(options[, callback])
static evm_val_t evm_module_http_request(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 1 || !evm_is_object(v))
{
return EVM_VAL_UNDEFINED;
}
evm_val_t *host = evm_prop_get(e, v, "host", 0);
if (host)
return EVM_VAL_UNDEFINED;
uint8_t port = 80;
evm_val_t *p = evm_prop_get(e, v, "port", 0);
if (evm_is_number(p))
port = evm_2_integer(p);
char *method = "GET";
evm_val_t *m = evm_prop_get(e, v, "method", 0);
if (evm_is_string(m))
method = evm_2_string(m);
char *path = "/";
evm_val_t *p = evm_prop_get(e, v, "path", 0);
if (evm_is_string(p))
path = evm_2_string(p);
evm_val_t *result = evm_module_http_client_new(e);
if (!result)
return EVM_VAL_UNDEFINED;
struct webclient_session *session = evm_object_get_ext_data(result);
evm_val_t *url = evm_heap_string_create(strlen(host) + strlen(itoa(port)) + strlen(path));
sprintf(evm_heap_string_addr(url), "%s:%d%s", host, port, path);
evm_val_t *opts = evm_prop_get(e, v, "headers", 0);
if (evm_is_undefined(opts))
return EVM_VAL_UNDEFINED;
if (evm_is_object(opts))
{
uint32_t length = evm_prop_len(opts);
for (uint_32_t index = 0; index < length; index++)
{
evm_hash_t key = evm_prop_get_key_by_index(e, opts, index);
if (key == EVM_INVALID_HASH)
{
break;
}
evm_val_t *v = evm_prop_get_by_key(e, opts, key, index);
const char *name = evm_string_get(e, key);
if (evm_is_string(v)) webclient_header_fields_add(session, "%s: %s\r\n", name);
else webclient_header_fields_add(session, "%s: %d\r\n", name);
}
}
return *result;
}
//http.get(options[, callback])
static evm_val_t evm_module_http_request_get(evm_t *e, evm_val_t *p, int argc, evm_val_t *v)
{
if (argc < 1 || !evm_is_object(v))
return EVM_VAL_UNDEFINED;
evm_prop_set_value(e, p, "method", evm_mk_heap_string((intptr_t) "GET"));
evm_val_t *client = evm_module_http_request(e, p, argc, v);
return evm_module_http_request_end(e, client, argc, v);
}
evm_err_t evm_module_http(evm_t *e) {
evm_builtin_t builtin[] = {
{"request", evm_mk_native((intptr_t)evm_module_http_request)},
{"get", evm_mk_native((intptr_t)evm_module_http_request_get)},
{NULL, NULL}};
evm_module_create(e, "http", builtin);
return e->err;
}
#endif
| 2,982 |
435 | <reponame>amaajemyfren/data
{
"alias": "video/1964/sunpy-python-for-solar-physicists-0",
"category": "SciPy 2013",
"copyright_text": "https://www.youtube.com/t/terms",
"description": "Authors: Mumford, Stuart, University of Sheffield / SunPy\n\nTrack: Astronomy and Astrophysics\n\nModern solar physicists have, at their disposal, an abundance of space\nand ground based instruments providing a large amount of data to analyse\nthe complex Sun every day. The NASA Solar Dynamics Observatory\nsatellite, for example, collects around 1.2 TB of data every 24 hours\nwhich requires extensive reconstruction before it is ready for\nscientific use. Currently most data processing and analysis for all\nsolar data is done using IDL and the 'SolarSoft' library. SunPy is a\nproject designed to provide a free, open and easy-to-use Python\nalternative to IDL and SolarSoft.\n\nSunPy provides unified, coordinate-aware data objects for many common\nsolar data types and integrates into these plotting and analysis tools.\nProviding this base will give the global solar physics community the\nopportunity to use Python for future data processing and analysis\nroutines. The astronomy and astrophysics community, through the\nimplementation and adoption of AstroPy and pyRAF, have already\ndemonstrated that Python is well suited for the analysis and processing\nof space science data.\n\nIn this presentation, we give key examples of SunPy's structure and\nscope, as well as the major improvements that have taken place to\nprovide a stable base for future expansion. We discuss recent\nimprovements to file I/O and visualisation, as well as improvements to\nthe structure and interface of the map objects.\n\nWe discuss the many challenges which SunPy faces if it is to achieve its\ngoal of becoming a key package for solar physics. The SunPy developers\nhope to increase the the visibility and uptake of SunPy, and encourage\npeople to contribute to the project, while maintaining a high quality\ncode base, which is facilitated by the use of a social version control\nsystem (git and GitHub).\n",
"duration": null,
"id": 1964,
"language": "eng",
"quality_notes": "",
"recorded": "2013-07-01",
"slug": "sunpy-python-for-solar-physicists-0",
"speakers": [
"<NAME>"
],
"summary": "SunPy is a project designed to provide a free, open and easy-to-use\nPython alternative to IDL and SolarSoft. SunPy provides unified,\ncoordinate-aware data objects for many common solar data types and\nintegrates into these plotting and analysis tools.\n",
"tags": [
"astronomy",
"astrophysics",
"SunPy"
],
"thumbnail_url": "https://i1.ytimg.com/vi/bXPPTCkaVu8/hqdefault.jpg",
"title": "SunPy - Python for Solar Physicists",
"videos": [
{
"length": 0,
"type": "youtube",
"url": "https://www.youtube.com/watch?v=bXPPTCkaVu8"
}
]
}
| 836 |
373 | <reponame>PegasusEpsilon/Barony
/*-------------------------------------------------------------------------------
BARONY
File: paths.hpp
Desc: paths.cpp header file
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#pragma once
extern int* pathMapFlying;
extern int* pathMapGrounded;
extern int pathMapZone;
// function prototypes
Uint32 heuristic(int x1, int y1, int x2, int y2);
list_t* generatePath(int x1, int y1, int x2, int y2, Entity* my, Entity* target, bool lavaIsPassable = false);
void generatePathMaps();
// return true if an entity is blocks pathing
bool isPathObstacle(Entity* entity);
| 203 |
562 | <reponame>Diastro/azure-resource-manager-schemas
{
"id": "https://schema.management.azure.com/schemas/2015-06-15/Microsoft.Storage.json#",
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Microsoft.Storage",
"description": "Microsoft Storage Resource Types",
"resourceDefinitions": {
"storageAccounts": {
"type": "object",
"properties": {
"apiVersion": {
"type": "string",
"enum": [
"2015-06-15"
]
},
"location": {
"type": "string",
"description": "The location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update, the request will succeed."
},
"name": {
"type": "string",
"minLength": 3,
"maxLength": 24,
"description": "The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only."
},
"properties": {
"oneOf": [
{
"$ref": "#/definitions/StorageAccountPropertiesCreateParameters"
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "The parameters used to create the storage account."
},
"tags": {
"oneOf": [
{
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {}
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "A list of key value pairs that describe the resource. These tags can be used for viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key with a length no greater than 128 characters and a value with a length no greater than 256 characters."
},
"type": {
"type": "string",
"enum": [
"Microsoft.Storage/storageAccounts"
]
}
},
"required": [
"apiVersion",
"location",
"name",
"type"
],
"description": "Microsoft.Storage/storageAccounts"
}
},
"definitions": {
"StorageAccountPropertiesCreateParameters": {
"type": "object",
"properties": {
"accountType": {
"oneOf": [
{
"type": "string",
"enum": [
"Standard_LRS",
"Standard_ZRS",
"Standard_GRS",
"Standard_RAGRS",
"Premium_LRS"
]
},
{
"$ref": "https://schema.management.azure.com/schemas/common/definitions.json#/definitions/expression"
}
],
"description": "The sku name. Required for account creation; optional for update. Note that in older versions, sku name was called accountType."
}
},
"required": [
"accountType"
],
"description": "The parameters used to create the storage account."
}
}
} | 1,612 |
2,151 | <filename>api/audio_codecs/audio_encoder.cc<gh_stars>1000+
/*
* Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/audio_codecs/audio_encoder.h"
#include "rtc_base/checks.h"
#include "rtc_base/trace_event.h"
namespace webrtc {
ANAStats::ANAStats() = default;
ANAStats::~ANAStats() = default;
ANAStats::ANAStats(const ANAStats&) = default;
AudioEncoder::EncodedInfo::EncodedInfo() = default;
AudioEncoder::EncodedInfo::EncodedInfo(const EncodedInfo&) = default;
AudioEncoder::EncodedInfo::EncodedInfo(EncodedInfo&&) = default;
AudioEncoder::EncodedInfo::~EncodedInfo() = default;
AudioEncoder::EncodedInfo& AudioEncoder::EncodedInfo::operator=(
const EncodedInfo&) = default;
AudioEncoder::EncodedInfo& AudioEncoder::EncodedInfo::operator=(EncodedInfo&&) =
default;
int AudioEncoder::RtpTimestampRateHz() const {
return SampleRateHz();
}
AudioEncoder::EncodedInfo AudioEncoder::Encode(
uint32_t rtp_timestamp,
rtc::ArrayView<const int16_t> audio,
rtc::Buffer* encoded) {
TRACE_EVENT0("webrtc", "AudioEncoder::Encode");
RTC_CHECK_EQ(audio.size(),
static_cast<size_t>(NumChannels() * SampleRateHz() / 100));
const size_t old_size = encoded->size();
EncodedInfo info = EncodeImpl(rtp_timestamp, audio, encoded);
RTC_CHECK_EQ(encoded->size() - old_size, info.encoded_bytes);
return info;
}
bool AudioEncoder::SetFec(bool enable) {
return !enable;
}
bool AudioEncoder::SetDtx(bool enable) {
return !enable;
}
bool AudioEncoder::GetDtx() const {
return false;
}
bool AudioEncoder::SetApplication(Application application) {
return false;
}
void AudioEncoder::SetMaxPlaybackRate(int frequency_hz) {}
void AudioEncoder::SetTargetBitrate(int target_bps) {}
rtc::ArrayView<std::unique_ptr<AudioEncoder>>
AudioEncoder::ReclaimContainedEncoders() {
return nullptr;
}
bool AudioEncoder::EnableAudioNetworkAdaptor(const std::string& config_string,
RtcEventLog* event_log) {
return false;
}
void AudioEncoder::DisableAudioNetworkAdaptor() {}
void AudioEncoder::OnReceivedUplinkPacketLossFraction(
float uplink_packet_loss_fraction) {}
void AudioEncoder::OnReceivedUplinkRecoverablePacketLossFraction(
float uplink_recoverable_packet_loss_fraction) {}
void AudioEncoder::OnReceivedTargetAudioBitrate(int target_audio_bitrate_bps) {
OnReceivedUplinkBandwidth(target_audio_bitrate_bps, rtc::nullopt);
}
void AudioEncoder::OnReceivedUplinkBandwidth(
int target_audio_bitrate_bps,
rtc::Optional<int64_t> bwe_period_ms) {}
void AudioEncoder::OnReceivedRtt(int rtt_ms) {}
void AudioEncoder::OnReceivedOverhead(size_t overhead_bytes_per_packet) {}
void AudioEncoder::SetReceiverFrameLengthRange(int min_frame_length_ms,
int max_frame_length_ms) {}
ANAStats AudioEncoder::GetANAStats() const {
return ANAStats();
}
} // namespace webrtc
| 1,198 |
3,673 |
#include <os.hpp>
#include <util/bitops.hpp>
#include <util/units.hpp>
#include <kernel.hpp>
using namespace util::literals;
size_t brk_bytes_used();
size_t mmap_bytes_used();
size_t mmap_allocation_end();
size_t kernel::heap_usage() noexcept
{
return brk_bytes_used() + mmap_bytes_used();
}
size_t kernel::heap_avail() noexcept
{
return (heap_max() - heap_begin()) - heap_usage();
}
uintptr_t kernel::heap_end() noexcept
{
return mmap_allocation_end();
}
size_t os::total_memuse() noexcept {
return kernel::heap_usage() + kernel::state().liveupdate_size + kernel::heap_begin();
}
constexpr size_t heap_alignment = 4096;
__attribute__((weak)) ssize_t __brk_max = 0x100000;
static bool __heap_ready = false;
extern void init_mmap(uintptr_t mmap_begin);
uintptr_t __init_brk(uintptr_t begin, size_t size);
uintptr_t __init_mmap(uintptr_t begin, size_t size);
bool kernel::heap_ready() { return __heap_ready; }
bool os::mem::heap_ready() { return kernel::heap_ready(); }
void kernel::init_heap(uintptr_t free_mem_begin, uintptr_t memory_end) noexcept {
// NOTE: Initialize the heap before exceptions
// cache-align heap, because its not aligned
kernel::state().memory_end = memory_end;
kernel::state().heap_max = memory_end - 1;
kernel::state().heap_begin = util::bits::roundto<heap_alignment>(free_mem_begin);
auto brk_end = __init_brk(kernel::heap_begin(), __brk_max);
Expects(brk_end <= memory_end);
__init_mmap(brk_end, memory_end);
__heap_ready = true;
}
| 575 |
823 | //
// CommunityCommentListAPI.h
// MierMilitaryNews
//
// Created by 李响 on 2016/11/1.
// Copyright © 2016年 miercn. All rights reserved.
//
#import "BaseBlockAPI.h"
#import "CommunityCommentModel.h"
@interface CommunityCommentListAPI : BaseBlockAPI
//加载列表
- (void)loadCommentListDataWithID:(NSString *)postId CircleId:(NSString *)circleId Page:(NSInteger)page ResultBlock:(APIRequestResultBlock)resultBlock;
/**
解析数据
@param resultBlock 结果回调Block
*/
- (void)analyticalCommentListDataWithData:(id)data ResultBlock:(void(^)(NSDictionary *))resultBlock;
@end
| 216 |
427 | #!/usr/bin/python
import cmd
import dict_utils
import file_extract
import optparse
import re
import struct
import string
import StringIO
import sys
import uuid
# Mach header "magic" constants
MH_MAGIC = 0xfeedface
MH_CIGAM = 0xcefaedfe
MH_MAGIC_64 = 0xfeedfacf
MH_CIGAM_64 = 0xcffaedfe
FAT_MAGIC = 0xcafebabe
FAT_CIGAM = 0xbebafeca
# Mach haeder "filetype" constants
MH_OBJECT = 0x00000001
MH_EXECUTE = 0x00000002
MH_FVMLIB = 0x00000003
MH_CORE = 0x00000004
MH_PRELOAD = 0x00000005
MH_DYLIB = 0x00000006
MH_DYLINKER = 0x00000007
MH_BUNDLE = 0x00000008
MH_DYLIB_STUB = 0x00000009
MH_DSYM = 0x0000000a
MH_KEXT_BUNDLE = 0x0000000b
# Mach haeder "flag" constant bits
MH_NOUNDEFS = 0x00000001
MH_INCRLINK = 0x00000002
MH_DYLDLINK = 0x00000004
MH_BINDATLOAD = 0x00000008
MH_PREBOUND = 0x00000010
MH_SPLIT_SEGS = 0x00000020
MH_LAZY_INIT = 0x00000040
MH_TWOLEVEL = 0x00000080
MH_FORCE_FLAT = 0x00000100
MH_NOMULTIDEFS = 0x00000200
MH_NOFIXPREBINDING = 0x00000400
MH_PREBINDABLE = 0x00000800
MH_ALLMODSBOUND = 0x00001000
MH_SUBSECTIONS_VIA_SYMBOLS = 0x00002000
MH_CANONICAL = 0x00004000
MH_WEAK_DEFINES = 0x00008000
MH_BINDS_TO_WEAK = 0x00010000
MH_ALLOW_STACK_EXECUTION = 0x00020000
MH_ROOT_SAFE = 0x00040000
MH_SETUID_SAFE = 0x00080000
MH_NO_REEXPORTED_DYLIBS = 0x00100000
MH_PIE = 0x00200000
MH_DEAD_STRIPPABLE_DYLIB = 0x00400000
MH_HAS_TLV_DESCRIPTORS = 0x00800000
MH_NO_HEAP_EXECUTION = 0x01000000
# Mach load command constants
LC_REQ_DYLD = 0x80000000
LC_SEGMENT = 0x00000001
LC_SYMTAB = 0x00000002
LC_SYMSEG = 0x00000003
LC_THREAD = 0x00000004
LC_UNIXTHREAD = 0x00000005
LC_LOADFVMLIB = 0x00000006
LC_IDFVMLIB = 0x00000007
LC_IDENT = 0x00000008
LC_FVMFILE = 0x00000009
LC_PREPAGE = 0x0000000a
LC_DYSYMTAB = 0x0000000b
LC_LOAD_DYLIB = 0x0000000c
LC_ID_DYLIB = 0x0000000d
LC_LOAD_DYLINKER = 0x0000000e
LC_ID_DYLINKER = 0x0000000f
LC_PREBOUND_DYLIB = 0x00000010
LC_ROUTINES = 0x00000011
LC_SUB_FRAMEWORK = 0x00000012
LC_SUB_UMBRELLA = 0x00000013
LC_SUB_CLIENT = 0x00000014
LC_SUB_LIBRARY = 0x00000015
LC_TWOLEVEL_HINTS = 0x00000016
LC_PREBIND_CKSUM = 0x00000017
LC_LOAD_WEAK_DYLIB = 0x00000018 | LC_REQ_DYLD
LC_SEGMENT_64 = 0x00000019
LC_ROUTINES_64 = 0x0000001a
LC_UUID = 0x0000001b
LC_RPATH = 0x0000001c | LC_REQ_DYLD
LC_CODE_SIGNATURE = 0x0000001d
LC_SEGMENT_SPLIT_INFO = 0x0000001e
LC_REEXPORT_DYLIB = 0x0000001f | LC_REQ_DYLD
LC_LAZY_LOAD_DYLIB = 0x00000020
LC_ENCRYPTION_INFO = 0x00000021
LC_DYLD_INFO = 0x00000022
LC_DYLD_INFO_ONLY = 0x00000022 | LC_REQ_DYLD
LC_LOAD_UPWARD_DYLIB = 0x00000023 | LC_REQ_DYLD
LC_VERSION_MIN_MACOSX = 0x00000024
LC_VERSION_MIN_IPHONEOS = 0x00000025
LC_FUNCTION_STARTS = 0x00000026
LC_DYLD_ENVIRONMENT = 0x00000027
# Mach CPU constants
CPU_ARCH_MASK = 0xff000000
CPU_ARCH_ABI64 = 0x01000000
CPU_TYPE_ANY = 0xffffffff
CPU_TYPE_VAX = 1
CPU_TYPE_MC680x0 = 6
CPU_TYPE_I386 = 7
CPU_TYPE_X86_64 = CPU_TYPE_I386 | CPU_ARCH_ABI64
CPU_TYPE_MIPS = 8
CPU_TYPE_MC98000 = 10
CPU_TYPE_HPPA = 11
CPU_TYPE_ARM = 12
CPU_TYPE_MC88000 = 13
CPU_TYPE_SPARC = 14
CPU_TYPE_I860 = 15
CPU_TYPE_ALPHA = 16
CPU_TYPE_POWERPC = 18
CPU_TYPE_POWERPC64 = CPU_TYPE_POWERPC | CPU_ARCH_ABI64
# VM protection constants
VM_PROT_READ = 1
VM_PROT_WRITE = 2
VM_PROT_EXECUTE = 4
# VM protection constants
N_STAB = 0xe0
N_PEXT = 0x10
N_TYPE = 0x0e
N_EXT = 0x01
# Values for nlist N_TYPE bits of the "Mach.NList.type" field.
N_UNDF = 0x0
N_ABS = 0x2
N_SECT = 0xe
N_PBUD = 0xc
N_INDR = 0xa
# Section indexes for the "Mach.NList.sect_idx" fields
NO_SECT = 0
MAX_SECT = 255
# Stab defines
N_GSYM = 0x20
N_FNAME = 0x22
N_FUN = 0x24
N_STSYM = 0x26
N_LCSYM = 0x28
N_BNSYM = 0x2e
N_OPT = 0x3c
N_RSYM = 0x40
N_SLINE = 0x44
N_ENSYM = 0x4e
N_SSYM = 0x60
N_SO = 0x64
N_OSO = 0x66
N_LSYM = 0x80
N_BINCL = 0x82
N_SOL = 0x84
N_PARAMS = 0x86
N_VERSION = 0x88
N_OLEVEL = 0x8A
N_PSYM = 0xa0
N_EINCL = 0xa2
N_ENTRY = 0xa4
N_LBRAC = 0xc0
N_EXCL = 0xc2
N_RBRAC = 0xe0
N_BCOMM = 0xe2
N_ECOMM = 0xe4
N_ECOML = 0xe8
N_LENG = 0xfe
vm_prot_names = ['---', 'r--', '-w-', 'rw-', '--x', 'r-x', '-wx', 'rwx']
def dump_memory(base_addr, data, hex_bytes_len, num_per_line):
hex_bytes = data.encode('hex')
if hex_bytes_len == -1:
hex_bytes_len = len(hex_bytes)
addr = base_addr
ascii_str = ''
i = 0
while i < hex_bytes_len:
if ((i / 2) % num_per_line) == 0:
if i > 0:
print ' %s' % (ascii_str)
ascii_str = ''
print '0x%8.8x:' % (addr + i),
hex_byte = hex_bytes[i:i + 2]
print hex_byte,
int_byte = int(hex_byte, 16)
ascii_char = '%c' % (int_byte)
if int_byte >= 32 and int_byte < 127:
ascii_str += ascii_char
else:
ascii_str += '.'
i = i + 2
if ascii_str:
if (i / 2) % num_per_line:
padding = num_per_line - ((i / 2) % num_per_line)
else:
padding = 0
print '%*s%s' % (padding * 3 + 1, '', ascii_str)
print
class TerminalColors:
'''Simple terminal colors class'''
def __init__(self, enabled=True):
# TODO: discover terminal type from "file" and disable if
# it can't handle the color codes
self.enabled = enabled
def reset(self):
'''Reset all terminal colors and formatting.'''
if self.enabled:
return "\x1b[0m"
return ''
def bold(self, on=True):
'''Enable or disable bold depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[1m"
else:
return "\x1b[22m"
return ''
def italics(self, on=True):
'''Enable or disable italics depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[3m"
else:
return "\x1b[23m"
return ''
def underline(self, on=True):
'''Enable or disable underline depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[4m"
else:
return "\x1b[24m"
return ''
def inverse(self, on=True):
'''Enable or disable inverse depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[7m"
else:
return "\x1b[27m"
return ''
def strike(self, on=True):
'''Enable or disable strike through depending on the "on" parameter.'''
if self.enabled:
if on:
return "\x1b[9m"
else:
return "\x1b[29m"
return ''
def black(self, fg=True):
'''Set the foreground or background color to black.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[30m"
else:
return "\x1b[40m"
return ''
def red(self, fg=True):
'''Set the foreground or background color to red.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[31m"
else:
return "\x1b[41m"
return ''
def green(self, fg=True):
'''Set the foreground or background color to green.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[32m"
else:
return "\x1b[42m"
return ''
def yellow(self, fg=True):
'''Set the foreground or background color to yellow.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[43m"
else:
return "\x1b[33m"
return ''
def blue(self, fg=True):
'''Set the foreground or background color to blue.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[34m"
else:
return "\x1b[44m"
return ''
def magenta(self, fg=True):
'''Set the foreground or background color to magenta.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[35m"
else:
return "\x1b[45m"
return ''
def cyan(self, fg=True):
'''Set the foreground or background color to cyan.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[36m"
else:
return "\x1b[46m"
return ''
def white(self, fg=True):
'''Set the foreground or background color to white.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[37m"
else:
return "\x1b[47m"
return ''
def default(self, fg=True):
'''Set the foreground or background color to the default.
The foreground color will be set if "fg" tests True. The background color will be set if "fg" tests False.'''
if self.enabled:
if fg:
return "\x1b[39m"
else:
return "\x1b[49m"
return ''
def swap_unpack_char():
"""Returns the unpack prefix that will for non-native endian-ness."""
if struct.pack('H', 1).startswith("\x00"):
return '<'
return '>'
def dump_hex_bytes(addr, s, bytes_per_line=16):
i = 0
line = ''
for ch in s:
if (i % bytes_per_line) == 0:
if line:
print line
line = '%#8.8x: ' % (addr + i)
line += "%02X " % ord(ch)
i += 1
print line
def dump_hex_byte_string_diff(addr, a, b, bytes_per_line=16):
i = 0
line = ''
a_len = len(a)
b_len = len(b)
if a_len < b_len:
max_len = b_len
else:
max_len = a_len
tty_colors = TerminalColors(True)
for i in range(max_len):
ch = None
if i < a_len:
ch_a = a[i]
ch = ch_a
else:
ch_a = None
if i < b_len:
ch_b = b[i]
if not ch:
ch = ch_b
else:
ch_b = None
mismatch = ch_a != ch_b
if (i % bytes_per_line) == 0:
if line:
print line
line = '%#8.8x: ' % (addr + i)
if mismatch:
line += tty_colors.red()
line += "%02X " % ord(ch)
if mismatch:
line += tty_colors.default()
i += 1
print line
class Mach:
"""Class that does everything mach-o related"""
class Arch:
"""Class that implements mach-o architectures"""
def __init__(self, c=0, s=0):
self.cpu = c
self.sub = s
def set_cpu_type(self, c):
self.cpu = c
def set_cpu_subtype(self, s):
self.sub = s
def set_arch(self, c, s):
self.cpu = c
self.sub = s
def is_64_bit(self):
return (self.cpu & CPU_ARCH_ABI64) != 0
cpu_infos = [
["arm", CPU_TYPE_ARM, CPU_TYPE_ANY],
["arm", CPU_TYPE_ARM, 0],
["armv4", CPU_TYPE_ARM, 5],
["armv6", CPU_TYPE_ARM, 6],
["armv5", CPU_TYPE_ARM, 7],
["xscale", CPU_TYPE_ARM, 8],
["armv7", CPU_TYPE_ARM, 9],
["armv7f", CPU_TYPE_ARM, 10],
["armv7s", CPU_TYPE_ARM, 11],
["armv7k", CPU_TYPE_ARM, 12],
["armv7m", CPU_TYPE_ARM, 15],
["armv7em", CPU_TYPE_ARM, 16],
["ppc", CPU_TYPE_POWERPC, CPU_TYPE_ANY],
["ppc", CPU_TYPE_POWERPC, 0],
["ppc601", CPU_TYPE_POWERPC, 1],
["ppc602", CPU_TYPE_POWERPC, 2],
["ppc603", CPU_TYPE_POWERPC, 3],
["ppc603e", CPU_TYPE_POWERPC, 4],
["ppc603ev", CPU_TYPE_POWERPC, 5],
["ppc604", CPU_TYPE_POWERPC, 6],
["ppc604e", CPU_TYPE_POWERPC, 7],
["ppc620", CPU_TYPE_POWERPC, 8],
["ppc750", CPU_TYPE_POWERPC, 9],
["ppc7400", CPU_TYPE_POWERPC, 10],
["ppc7450", CPU_TYPE_POWERPC, 11],
["ppc970", CPU_TYPE_POWERPC, 100],
["ppc64", CPU_TYPE_POWERPC64, 0],
["ppc970-64", CPU_TYPE_POWERPC64, 100],
["i386", CPU_TYPE_I386, 3],
["i486", CPU_TYPE_I386, 4],
["i486sx", CPU_TYPE_I386, 0x84],
["i386", CPU_TYPE_I386, CPU_TYPE_ANY],
["x86_64", CPU_TYPE_X86_64, 3],
["x86_64", CPU_TYPE_X86_64, CPU_TYPE_ANY],
]
def __str__(self):
for info in self.cpu_infos:
if self.cpu == info[1] and (self.sub & 0x00ffffff) == info[2]:
return info[0]
return "{0}.{1}".format(self.cpu, self.sub)
class Magic(dict_utils.Enum):
enum = {
'MH_MAGIC': MH_MAGIC,
'MH_CIGAM': MH_CIGAM,
'MH_MAGIC_64': MH_MAGIC_64,
'MH_CIGAM_64': MH_CIGAM_64,
'FAT_MAGIC': FAT_MAGIC,
'FAT_CIGAM': FAT_CIGAM
}
def __init__(self, initial_value=0):
dict_utils.Enum.__init__(self, initial_value, self.enum)
def is_skinny_mach_file(self):
return self.value == MH_MAGIC or self.value == MH_CIGAM or self.value == MH_MAGIC_64 or self.value == MH_CIGAM_64
def is_universal_mach_file(self):
return self.value == FAT_MAGIC or self.value == FAT_CIGAM
def unpack(self, data):
data.set_byte_order('native')
self.value = data.get_uint32()
def get_byte_order(self):
if self.value == MH_CIGAM or self.value == MH_CIGAM_64 or self.value == FAT_CIGAM:
return swap_unpack_char()
else:
return '='
def is_64_bit(self):
return self.value == MH_MAGIC_64 or self.value == MH_CIGAM_64
def __init__(self):
self.magic = Mach.Magic()
self.content = None
self.path = None
def extract(self, path, extractor):
self.path = path
self.unpack(extractor)
def parse(self, path):
self.path = path
try:
f = open(self.path)
file_extractor = file_extract.FileExtract(f, '=')
self.unpack(file_extractor)
# f.close()
except IOError as xxx_todo_changeme:
(errno, strerror) = xxx_todo_changeme.args
print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
def compare(self, rhs):
self.content.compare(rhs.content)
def dump(self, options=None):
self.content.dump(options)
def dump_header(self, dump_description=True, options=None):
self.content.dump_header(dump_description, options)
def dump_load_commands(self, dump_description=True, options=None):
self.content.dump_load_commands(dump_description, options)
def dump_sections(self, dump_description=True, options=None):
self.content.dump_sections(dump_description, options)
def dump_section_contents(self, options):
self.content.dump_section_contents(options)
def dump_symtab(self, dump_description=True, options=None):
self.content.dump_symtab(dump_description, options)
def dump_symbol_names_matching_regex(self, regex, file=None):
self.content.dump_symbol_names_matching_regex(regex, file)
def description(self):
return self.content.description()
def unpack(self, data):
self.magic.unpack(data)
if self.magic.is_skinny_mach_file():
self.content = Mach.Skinny(self.path)
elif self.magic.is_universal_mach_file():
self.content = Mach.Universal(self.path)
else:
self.content = None
if self.content is not None:
self.content.unpack(data, self.magic)
def is_valid(self):
return self.content is not None
class Universal:
def __init__(self, path):
self.path = path
self.type = 'universal'
self.file_off = 0
self.magic = None
self.nfat_arch = 0
self.archs = list()
def description(self):
s = '%#8.8x: %s (' % (self.file_off, self.path)
archs_string = ''
for arch in self.archs:
if len(archs_string):
archs_string += ', '
archs_string += '%s' % arch.arch
s += archs_string
s += ')'
return s
def unpack(self, data, magic=None):
self.file_off = data.tell()
if magic is None:
self.magic = Mach.Magic()
self.magic.unpack(data)
else:
self.magic = magic
self.file_off = self.file_off - 4
# Universal headers are always in big endian
data.set_byte_order('big')
self.nfat_arch = data.get_uint32()
for i in range(self.nfat_arch):
self.archs.append(Mach.Universal.ArchInfo())
self.archs[i].unpack(data)
for i in range(self.nfat_arch):
self.archs[i].mach = Mach.Skinny(self.path)
data.seek(self.archs[i].offset, 0)
skinny_magic = Mach.Magic()
skinny_magic.unpack(data)
self.archs[i].mach.unpack(data, skinny_magic)
def compare(self, rhs):
print 'error: comparing two universal files is not supported yet'
return False
def dump(self, options):
if options.dump_header:
print
print "Universal Mach File: magic = %s, nfat_arch = %u" % (self.magic, self.nfat_arch)
print
if self.nfat_arch > 0:
if options.dump_header:
self.archs[0].dump_header(True, options)
for i in range(self.nfat_arch):
self.archs[i].dump_flat(options)
if options.dump_header:
print
for i in range(self.nfat_arch):
self.archs[i].mach.dump(options)
def dump_header(self, dump_description=True, options=None):
if dump_description:
print self.description()
for i in range(self.nfat_arch):
self.archs[i].mach.dump_header(True, options)
print
def dump_load_commands(self, dump_description=True, options=None):
if dump_description:
print self.description()
for i in range(self.nfat_arch):
self.archs[i].mach.dump_load_commands(True, options)
print
def dump_sections(self, dump_description=True, options=None):
if dump_description:
print self.description()
for i in range(self.nfat_arch):
self.archs[i].mach.dump_sections(True, options)
print
def dump_section_contents(self, options):
for i in range(self.nfat_arch):
self.archs[i].mach.dump_section_contents(options)
print
def dump_symtab(self, dump_description=True, options=None):
if dump_description:
print self.description()
for i in range(self.nfat_arch):
self.archs[i].mach.dump_symtab(True, options)
print
def dump_symbol_names_matching_regex(self, regex, file=None):
for i in range(self.nfat_arch):
self.archs[i].mach.dump_symbol_names_matching_regex(
regex, file)
class ArchInfo:
def __init__(self):
self.arch = Mach.Arch(0, 0)
self.offset = 0
self.size = 0
self.align = 0
self.mach = None
def unpack(self, data):
# Universal headers are always in big endian
data.set_byte_order('big')
self.arch.cpu, self.arch.sub, self.offset, self.size, self.align = data.get_n_uint32(
5)
def dump_header(self, dump_description=True, options=None):
if options.verbose:
print "CPU SUBTYPE OFFSET SIZE ALIGN"
print "---------- ---------- ---------- ---------- ----------"
else:
print "ARCH FILEOFFSET FILESIZE ALIGN"
print "---------- ---------- ---------- ----------"
def dump_flat(self, options):
if options.verbose:
print "%#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (self.arch.cpu, self.arch.sub, self.offset, self.size, self.align)
else:
print "%-10s %#8.8x %#8.8x %#8.8x" % (self.arch, self.offset, self.size, self.align)
def dump(self):
print " cputype: %#8.8x" % self.arch.cpu
print "cpusubtype: %#8.8x" % self.arch.sub
print " offset: %#8.8x" % self.offset
print " size: %#8.8x" % self.size
print " align: %#8.8x" % self.align
def __str__(self):
return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (
self.arch.cpu, self.arch.sub, self.offset, self.size, self.align)
def __repr__(self):
return "Mach.Universal.ArchInfo: %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x" % (
self.arch.cpu, self.arch.sub, self.offset, self.size, self.align)
class Flags:
def __init__(self, b):
self.bits = b
def __str__(self):
s = ''
if self.bits & MH_NOUNDEFS:
s += 'MH_NOUNDEFS | '
if self.bits & MH_INCRLINK:
s += 'MH_INCRLINK | '
if self.bits & MH_DYLDLINK:
s += 'MH_DYLDLINK | '
if self.bits & MH_BINDATLOAD:
s += 'MH_BINDATLOAD | '
if self.bits & MH_PREBOUND:
s += 'MH_PREBOUND | '
if self.bits & MH_SPLIT_SEGS:
s += 'MH_SPLIT_SEGS | '
if self.bits & MH_LAZY_INIT:
s += 'MH_LAZY_INIT | '
if self.bits & MH_TWOLEVEL:
s += 'MH_TWOLEVEL | '
if self.bits & MH_FORCE_FLAT:
s += 'MH_FORCE_FLAT | '
if self.bits & MH_NOMULTIDEFS:
s += 'MH_NOMULTIDEFS | '
if self.bits & MH_NOFIXPREBINDING:
s += 'MH_NOFIXPREBINDING | '
if self.bits & MH_PREBINDABLE:
s += 'MH_PREBINDABLE | '
if self.bits & MH_ALLMODSBOUND:
s += 'MH_ALLMODSBOUND | '
if self.bits & MH_SUBSECTIONS_VIA_SYMBOLS:
s += 'MH_SUBSECTIONS_VIA_SYMBOLS | '
if self.bits & MH_CANONICAL:
s += 'MH_CANONICAL | '
if self.bits & MH_WEAK_DEFINES:
s += 'MH_WEAK_DEFINES | '
if self.bits & MH_BINDS_TO_WEAK:
s += 'MH_BINDS_TO_WEAK | '
if self.bits & MH_ALLOW_STACK_EXECUTION:
s += 'MH_ALLOW_STACK_EXECUTION | '
if self.bits & MH_ROOT_SAFE:
s += 'MH_ROOT_SAFE | '
if self.bits & MH_SETUID_SAFE:
s += 'MH_SETUID_SAFE | '
if self.bits & MH_NO_REEXPORTED_DYLIBS:
s += 'MH_NO_REEXPORTED_DYLIBS | '
if self.bits & MH_PIE:
s += 'MH_PIE | '
if self.bits & MH_DEAD_STRIPPABLE_DYLIB:
s += 'MH_DEAD_STRIPPABLE_DYLIB | '
if self.bits & MH_HAS_TLV_DESCRIPTORS:
s += 'MH_HAS_TLV_DESCRIPTORS | '
if self.bits & MH_NO_HEAP_EXECUTION:
s += 'MH_NO_HEAP_EXECUTION | '
# Strip the trailing " |" if we have any flags
if len(s) > 0:
s = s[0:-2]
return s
class FileType(dict_utils.Enum):
enum = {
'MH_OBJECT': MH_OBJECT,
'MH_EXECUTE': MH_EXECUTE,
'MH_FVMLIB': MH_FVMLIB,
'MH_CORE': MH_CORE,
'MH_PRELOAD': MH_PRELOAD,
'MH_DYLIB': MH_DYLIB,
'MH_DYLINKER': MH_DYLINKER,
'MH_BUNDLE': MH_BUNDLE,
'MH_DYLIB_STUB': MH_DYLIB_STUB,
'MH_DSYM': MH_DSYM,
'MH_KEXT_BUNDLE': MH_KEXT_BUNDLE
}
def __init__(self, initial_value=0):
dict_utils.Enum.__init__(self, initial_value, self.enum)
class Skinny:
def __init__(self, path):
self.path = path
self.type = 'skinny'
self.data = None
self.file_off = 0
self.magic = 0
self.arch = Mach.Arch(0, 0)
self.filetype = Mach.FileType(0)
self.ncmds = 0
self.sizeofcmds = 0
self.flags = Mach.Flags(0)
self.uuid = None
self.commands = list()
self.segments = list()
self.sections = list()
self.symbols = list()
self.sections.append(Mach.Section())
def description(self):
return '%#8.8x: %s (%s)' % (self.file_off, self.path, self.arch)
def unpack(self, data, magic=None):
self.data = data
self.file_off = data.tell()
if magic is None:
self.magic = Mach.Magic()
self.magic.unpack(data)
else:
self.magic = magic
self.file_off = self.file_off - 4
data.set_byte_order(self.magic.get_byte_order())
self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, bits = data.get_n_uint32(
6)
self.flags.bits = bits
if self.is_64_bit():
data.get_uint32() # Skip reserved word in mach_header_64
for i in range(0, self.ncmds):
lc = self.unpack_load_command(data)
self.commands.append(lc)
def get_data(self):
if self.data:
self.data.set_byte_order(self.magic.get_byte_order())
return self.data
return None
def unpack_load_command(self, data):
lc = Mach.LoadCommand()
lc.unpack(self, data)
lc_command = lc.command.get_enum_value()
if (lc_command == LC_SEGMENT or
lc_command == LC_SEGMENT_64):
lc = Mach.SegmentLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_LOAD_DYLIB or
lc_command == LC_ID_DYLIB or
lc_command == LC_LOAD_WEAK_DYLIB or
lc_command == LC_REEXPORT_DYLIB):
lc = Mach.DylibLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_LOAD_DYLINKER or
lc_command == LC_SUB_FRAMEWORK or
lc_command == LC_SUB_CLIENT or
lc_command == LC_SUB_UMBRELLA or
lc_command == LC_SUB_LIBRARY or
lc_command == LC_ID_DYLINKER or
lc_command == LC_RPATH):
lc = Mach.LoadDYLDLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_DYLD_INFO_ONLY):
lc = Mach.DYLDInfoOnlyLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_SYMTAB):
lc = Mach.SymtabLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_DYSYMTAB):
lc = Mach.DYLDSymtabLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_UUID):
lc = Mach.UUIDLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_CODE_SIGNATURE or
lc_command == LC_SEGMENT_SPLIT_INFO or
lc_command == LC_FUNCTION_STARTS):
lc = Mach.DataBlobLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_UNIXTHREAD):
lc = Mach.UnixThreadLoadCommand(lc)
lc.unpack(self, data)
elif (lc_command == LC_ENCRYPTION_INFO):
lc = Mach.EncryptionInfoLoadCommand(lc)
lc.unpack(self, data)
lc.skip(data)
return lc
def compare(self, rhs):
print "\nComparing:"
print "a) %s %s" % (self.arch, self.path)
print "b) %s %s" % (rhs.arch, rhs.path)
result = True
if self.type == rhs.type:
for lhs_section in self.sections[1:]:
rhs_section = rhs.get_section_by_section(lhs_section)
if rhs_section:
print 'comparing %s.%s...' % (lhs_section.segname, lhs_section.sectname),
sys.stdout.flush()
lhs_data = lhs_section.get_contents(self)
rhs_data = rhs_section.get_contents(rhs)
if lhs_data and rhs_data:
if lhs_data == rhs_data:
print 'ok'
else:
lhs_data_len = len(lhs_data)
rhs_data_len = len(rhs_data)
# if lhs_data_len < rhs_data_len:
# if lhs_data == rhs_data[0:lhs_data_len]:
# print 'section data for %s matches the first %u bytes' % (lhs_section.sectname, lhs_data_len)
# else:
# # TODO: check padding
# result = False
# elif lhs_data_len > rhs_data_len:
# if lhs_data[0:rhs_data_len] == rhs_data:
# print 'section data for %s matches the first %u bytes' % (lhs_section.sectname, lhs_data_len)
# else:
# # TODO: check padding
# result = False
# else:
result = False
print 'error: sections differ'
# print 'a) %s' % (lhs_section)
# dump_hex_byte_string_diff(0, lhs_data, rhs_data)
# print 'b) %s' % (rhs_section)
# dump_hex_byte_string_diff(0, rhs_data, lhs_data)
elif lhs_data and not rhs_data:
print 'error: section data missing from b:'
print 'a) %s' % (lhs_section)
print 'b) %s' % (rhs_section)
result = False
elif not lhs_data and rhs_data:
print 'error: section data missing from a:'
print 'a) %s' % (lhs_section)
print 'b) %s' % (rhs_section)
result = False
elif lhs_section.offset or rhs_section.offset:
print 'error: section data missing for both a and b:'
print 'a) %s' % (lhs_section)
print 'b) %s' % (rhs_section)
result = False
else:
print 'ok'
else:
result = False
print 'error: section %s is missing in %s' % (lhs_section.sectname, rhs.path)
else:
print 'error: comaparing a %s mach-o file with a %s mach-o file is not supported' % (self.type, rhs.type)
result = False
if not result:
print 'error: mach files differ'
return result
def dump_header(self, dump_description=True, options=None):
if options.verbose:
print "MAGIC CPU SUBTYPE FILETYPE NUM CMDS SIZE CMDS FLAGS"
print "---------- ---------- ---------- ---------- -------- ---------- ----------"
else:
print "MAGIC ARCH FILETYPE NUM CMDS SIZE CMDS FLAGS"
print "------------ ---------- -------------- -------- ---------- ----------"
def dump_flat(self, options):
if options.verbose:
print "%#8.8x %#8.8x %#8.8x %#8.8x %#8u %#8.8x %#8.8x" % (self.magic, self.arch.cpu, self.arch.sub, self.filetype.value, self.ncmds, self.sizeofcmds, self.flags.bits)
else:
print "%-12s %-10s %-14s %#8u %#8.8x %s" % (self.magic, self.arch, self.filetype, self.ncmds, self.sizeofcmds, self.flags)
def dump(self, options):
if options.dump_header:
self.dump_header(True, options)
if options.dump_load_commands:
self.dump_load_commands(False, options)
if options.dump_sections:
self.dump_sections(False, options)
if options.section_names:
self.dump_section_contents(options)
if options.dump_symtab:
self.get_symtab()
if len(self.symbols):
self.dump_sections(False, options)
else:
print "No symbols"
if options.find_mangled:
self.dump_symbol_names_matching_regex(re.compile('^_?_Z'))
def dump_header(self, dump_description=True, options=None):
if dump_description:
print self.description()
print "Mach Header"
print " magic: %#8.8x %s" % (self.magic.value, self.magic)
print " cputype: %#8.8x %s" % (self.arch.cpu, self.arch)
print " cpusubtype: %#8.8x" % self.arch.sub
print " filetype: %#8.8x %s" % (self.filetype.get_enum_value(), self.filetype.get_enum_name())
print " ncmds: %#8.8x %u" % (self.ncmds, self.ncmds)
print " sizeofcmds: %#8.8x" % self.sizeofcmds
print " flags: %#8.8x %s" % (self.flags.bits, self.flags)
def dump_load_commands(self, dump_description=True, options=None):
if dump_description:
print self.description()
for lc in self.commands:
print lc
def get_section_by_name(self, name):
for section in self.sections:
if section.sectname and section.sectname == name:
return section
return None
def get_section_by_section(self, other_section):
for section in self.sections:
if section.sectname == other_section.sectname and section.segname == other_section.segname:
return section
return None
def dump_sections(self, dump_description=True, options=None):
if dump_description:
print self.description()
num_sections = len(self.sections)
if num_sections > 1:
self.sections[1].dump_header()
for sect_idx in range(1, num_sections):
print "%s" % self.sections[sect_idx]
def dump_section_contents(self, options):
saved_section_to_disk = False
for sectname in options.section_names:
section = self.get_section_by_name(sectname)
if section:
sect_bytes = section.get_contents(self)
if options.outfile:
if not saved_section_to_disk:
outfile = open(options.outfile, 'w')
if options.extract_modules:
# print "Extracting modules from mach file..."
data = file_extract.FileExtract(
StringIO.StringIO(sect_bytes), self.data.byte_order)
version = data.get_uint32()
num_modules = data.get_uint32()
# print "version = %u, num_modules = %u" %
# (version, num_modules)
for i in range(num_modules):
data_offset = data.get_uint64()
data_size = data.get_uint64()
name_offset = data.get_uint32()
language = data.get_uint32()
flags = data.get_uint32()
data.seek(name_offset)
module_name = data.get_c_string()
# print "module[%u] data_offset = %#16.16x,
# data_size = %#16.16x, name_offset =
# %#16.16x (%s), language = %u, flags =
# %#x" % (i, data_offset, data_size,
# name_offset, module_name, language,
# flags)
data.seek(data_offset)
outfile.write(data.read_size(data_size))
else:
print "Saving section %s to '%s'" % (sectname, options.outfile)
outfile.write(sect_bytes)
outfile.close()
saved_section_to_disk = True
else:
print "error: you can only save a single section to disk at a time, skipping section '%s'" % (sectname)
else:
print 'section %s:\n' % (sectname)
section.dump_header()
print '%s\n' % (section)
dump_memory(0, sect_bytes, options.max_count, 16)
else:
print 'error: no section named "%s" was found' % (sectname)
def get_segment(self, segname):
if len(self.segments) == 1 and self.segments[0].segname == '':
return self.segments[0]
for segment in self.segments:
if segment.segname == segname:
return segment
return None
def get_first_load_command(self, lc_enum_value):
for lc in self.commands:
if lc.command.value == lc_enum_value:
return lc
return None
def get_symtab(self):
if self.data and not self.symbols:
lc_symtab = self.get_first_load_command(LC_SYMTAB)
if lc_symtab:
symtab_offset = self.file_off
if self.data.is_in_memory():
linkedit_segment = self.get_segment('__LINKEDIT')
if linkedit_segment:
linkedit_vmaddr = linkedit_segment.vmaddr
linkedit_fileoff = linkedit_segment.fileoff
symtab_offset = linkedit_vmaddr + lc_symtab.symoff - linkedit_fileoff
symtab_offset = linkedit_vmaddr + lc_symtab.stroff - linkedit_fileoff
else:
symtab_offset += lc_symtab.symoff
self.data.seek(symtab_offset)
is_64 = self.is_64_bit()
for i in range(lc_symtab.nsyms):
nlist = Mach.NList()
nlist.unpack(self, self.data, lc_symtab)
self.symbols.append(nlist)
else:
print "no LC_SYMTAB"
def dump_symtab(self, dump_description=True, options=None):
self.get_symtab()
if dump_description:
print self.description()
for i, symbol in enumerate(self.symbols):
print '[%5u] %s' % (i, symbol)
def dump_symbol_names_matching_regex(self, regex, file=None):
self.get_symtab()
for symbol in self.symbols:
if symbol.name and regex.search(symbol.name):
print symbol.name
if file:
file.write('%s\n' % (symbol.name))
def is_64_bit(self):
return self.magic.is_64_bit()
class LoadCommand:
class Command(dict_utils.Enum):
enum = {
'LC_SEGMENT': LC_SEGMENT,
'LC_SYMTAB': LC_SYMTAB,
'LC_SYMSEG': LC_SYMSEG,
'LC_THREAD': LC_THREAD,
'LC_UNIXTHREAD': LC_UNIXTHREAD,
'LC_LOADFVMLIB': LC_LOADFVMLIB,
'LC_IDFVMLIB': LC_IDFVMLIB,
'LC_IDENT': LC_IDENT,
'LC_FVMFILE': LC_FVMFILE,
'LC_PREPAGE': LC_PREPAGE,
'LC_DYSYMTAB': LC_DYSYMTAB,
'LC_LOAD_DYLIB': LC_LOAD_DYLIB,
'LC_ID_DYLIB': LC_ID_DYLIB,
'LC_LOAD_DYLINKER': LC_LOAD_DYLINKER,
'LC_ID_DYLINKER': LC_ID_DYLINKER,
'LC_PREBOUND_DYLIB': LC_PREBOUND_DYLIB,
'LC_ROUTINES': LC_ROUTINES,
'LC_SUB_FRAMEWORK': LC_SUB_FRAMEWORK,
'LC_SUB_UMBRELLA': LC_SUB_UMBRELLA,
'LC_SUB_CLIENT': LC_SUB_CLIENT,
'LC_SUB_LIBRARY': LC_SUB_LIBRARY,
'LC_TWOLEVEL_HINTS': LC_TWOLEVEL_HINTS,
'LC_PREBIND_CKSUM': LC_PREBIND_CKSUM,
'LC_LOAD_WEAK_DYLIB': LC_LOAD_WEAK_DYLIB,
'LC_SEGMENT_64': LC_SEGMENT_64,
'LC_ROUTINES_64': LC_ROUTINES_64,
'LC_UUID': LC_UUID,
'LC_RPATH': LC_RPATH,
'LC_CODE_SIGNATURE': LC_CODE_SIGNATURE,
'LC_SEGMENT_SPLIT_INFO': LC_SEGMENT_SPLIT_INFO,
'LC_REEXPORT_DYLIB': LC_REEXPORT_DYLIB,
'LC_LAZY_LOAD_DYLIB': LC_LAZY_LOAD_DYLIB,
'LC_ENCRYPTION_INFO': LC_ENCRYPTION_INFO,
'LC_DYLD_INFO': LC_DYLD_INFO,
'LC_DYLD_INFO_ONLY': LC_DYLD_INFO_ONLY,
'LC_LOAD_UPWARD_DYLIB': LC_LOAD_UPWARD_DYLIB,
'LC_VERSION_MIN_MACOSX': LC_VERSION_MIN_MACOSX,
'LC_VERSION_MIN_IPHONEOS': LC_VERSION_MIN_IPHONEOS,
'LC_FUNCTION_STARTS': LC_FUNCTION_STARTS,
'LC_DYLD_ENVIRONMENT': LC_DYLD_ENVIRONMENT
}
def __init__(self, initial_value=0):
dict_utils.Enum.__init__(self, initial_value, self.enum)
def __init__(self, c=None, l=0, o=0):
if c is not None:
self.command = c
else:
self.command = Mach.LoadCommand.Command(0)
self.length = l
self.file_off = o
def unpack(self, mach_file, data):
self.file_off = data.tell()
self.command.value, self.length = data.get_n_uint32(2)
def skip(self, data):
data.seek(self.file_off + self.length, 0)
def __str__(self):
lc_name = self.command.get_enum_name()
return '%#8.8x: <%#4.4x> %-24s' % (self.file_off,
self.length, lc_name)
class Section:
def __init__(self):
self.index = 0
self.is_64 = False
self.sectname = None
self.segname = None
self.addr = 0
self.size = 0
self.offset = 0
self.align = 0
self.reloff = 0
self.nreloc = 0
self.flags = 0
self.reserved1 = 0
self.reserved2 = 0
self.reserved3 = 0
def unpack(self, is_64, data):
self.is_64 = is_64
self.sectname = data.get_fixed_length_c_string(16, '', True)
self.segname = data.get_fixed_length_c_string(16, '', True)
if self.is_64:
self.addr, self.size = data.get_n_uint64(2)
self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.reserved3 = data.get_n_uint32(
8)
else:
self.addr, self.size = data.get_n_uint32(2)
self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2 = data.get_n_uint32(
7)
def dump_header(self):
if self.is_64:
print "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 RESERVED3 NAME"
print "===== ------------------ ------------------ ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------"
else:
print "INDEX ADDRESS SIZE OFFSET ALIGN RELOFF NRELOC FLAGS RESERVED1 RESERVED2 NAME"
print "===== ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------------------"
def __str__(self):
if self.is_64:
return "[%3u] %#16.16x %#16.16x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" % (
self.index, self.addr, self.size, self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.reserved3, self.segname, self.sectname)
else:
return "[%3u] %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %#8.8x %s.%s" % (
self.index, self.addr, self.size, self.offset, self.align, self.reloff, self.nreloc, self.flags, self.reserved1, self.reserved2, self.segname, self.sectname)
def get_contents(self, mach_file):
'''Get the section contents as a python string'''
if self.size > 0 and mach_file.get_segment(
self.segname).filesize > 0:
data = mach_file.get_data()
if data:
section_data_offset = mach_file.file_off + self.offset
# print '%s.%s is at offset 0x%x with size 0x%x' %
# (self.segname, self.sectname, section_data_offset,
# self.size)
data.push_offset_and_seek(section_data_offset)
bytes = data.read_size(self.size)
data.pop_offset_and_seek()
return bytes
return None
class DylibLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.name = None
self.timestamp = 0
self.current_version = 0
self.compatibility_version = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
name_offset, self.timestamp, self.current_version, self.compatibility_version = data.get_n_uint32(
4)
data.seek(self.file_off + name_offset, 0)
self.name = data.get_fixed_length_c_string(self.length - 24)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "%#8.8x %#8.8x %#8.8x " % (self.timestamp,
self.current_version,
self.compatibility_version)
s += self.name
return s
class LoadDYLDLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.name = None
def unpack(self, mach_file, data):
data.get_uint32()
self.name = data.get_fixed_length_c_string(self.length - 12)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "%s" % self.name
return s
class UnixThreadLoadCommand(LoadCommand):
class ThreadState:
def __init__(self):
self.flavor = 0
self.count = 0
self.register_values = list()
def unpack(self, data):
self.flavor, self.count = data.get_n_uint32(2)
self.register_values = data.get_n_uint32(self.count)
def __str__(self):
s = "flavor = %u, count = %u, regs =" % (
self.flavor, self.count)
i = 0
for register_value in self.register_values:
if i % 8 == 0:
s += "\n "
s += " %#8.8x" % register_value
i += 1
return s
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.reg_sets = list()
def unpack(self, mach_file, data):
reg_set = Mach.UnixThreadLoadCommand.ThreadState()
reg_set.unpack(data)
self.reg_sets.append(reg_set)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
for reg_set in self.reg_sets:
s += "%s" % reg_set
return s
class DYLDInfoOnlyLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.rebase_off = 0
self.rebase_size = 0
self.bind_off = 0
self.bind_size = 0
self.weak_bind_off = 0
self.weak_bind_size = 0
self.lazy_bind_off = 0
self.lazy_bind_size = 0
self.export_off = 0
self.export_size = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
self.rebase_off, self.rebase_size, self.bind_off, self.bind_size, self.weak_bind_off, self.weak_bind_size, self.lazy_bind_off, self.lazy_bind_size, self.export_off, self.export_size = data.get_n_uint32(
10)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "rebase_off = %#8.8x, rebase_size = %u, " % (
self.rebase_off, self.rebase_size)
s += "bind_off = %#8.8x, bind_size = %u, " % (
self.bind_off, self.bind_size)
s += "weak_bind_off = %#8.8x, weak_bind_size = %u, " % (
self.weak_bind_off, self.weak_bind_size)
s += "lazy_bind_off = %#8.8x, lazy_bind_size = %u, " % (
self.lazy_bind_off, self.lazy_bind_size)
s += "export_off = %#8.8x, export_size = %u, " % (
self.export_off, self.export_size)
return s
class DYLDSymtabLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.ilocalsym = 0
self.nlocalsym = 0
self.iextdefsym = 0
self.nextdefsym = 0
self.iundefsym = 0
self.nundefsym = 0
self.tocoff = 0
self.ntoc = 0
self.modtaboff = 0
self.nmodtab = 0
self.extrefsymoff = 0
self.nextrefsyms = 0
self.indirectsymoff = 0
self.nindirectsyms = 0
self.extreloff = 0
self.nextrel = 0
self.locreloff = 0
self.nlocrel = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
self.ilocalsym, self.nlocalsym, self.iextdefsym, self.nextdefsym, self.iundefsym, self.nundefsym, self.tocoff, self.ntoc, self.modtaboff, self.nmodtab, self.extrefsymoff, self.nextrefsyms, self.indirectsymoff, self.nindirectsyms, self.extreloff, self.nextrel, self.locreloff, self.nlocrel = data.get_n_uint32(
18)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
# s += "ilocalsym = %u, nlocalsym = %u, " % (self.ilocalsym, self.nlocalsym)
# s += "iextdefsym = %u, nextdefsym = %u, " % (self.iextdefsym, self.nextdefsym)
# s += "iundefsym %u, nundefsym = %u, " % (self.iundefsym, self.nundefsym)
# s += "tocoff = %#8.8x, ntoc = %u, " % (self.tocoff, self.ntoc)
# s += "modtaboff = %#8.8x, nmodtab = %u, " % (self.modtaboff, self.nmodtab)
# s += "extrefsymoff = %#8.8x, nextrefsyms = %u, " % (self.extrefsymoff, self.nextrefsyms)
# s += "indirectsymoff = %#8.8x, nindirectsyms = %u, " % (self.indirectsymoff, self.nindirectsyms)
# s += "extreloff = %#8.8x, nextrel = %u, " % (self.extreloff, self.nextrel)
# s += "locreloff = %#8.8x, nlocrel = %u" % (self.locreloff,
# self.nlocrel)
s += "ilocalsym = %-10u, nlocalsym = %u\n" % (
self.ilocalsym, self.nlocalsym)
s += " iextdefsym = %-10u, nextdefsym = %u\n" % (
self.iextdefsym, self.nextdefsym)
s += " iundefsym = %-10u, nundefsym = %u\n" % (
self.iundefsym, self.nundefsym)
s += " tocoff = %#8.8x, ntoc = %u\n" % (
self.tocoff, self.ntoc)
s += " modtaboff = %#8.8x, nmodtab = %u\n" % (
self.modtaboff, self.nmodtab)
s += " extrefsymoff = %#8.8x, nextrefsyms = %u\n" % (
self.extrefsymoff, self.nextrefsyms)
s += " indirectsymoff = %#8.8x, nindirectsyms = %u\n" % (
self.indirectsymoff, self.nindirectsyms)
s += " extreloff = %#8.8x, nextrel = %u\n" % (
self.extreloff, self.nextrel)
s += " locreloff = %#8.8x, nlocrel = %u" % (
self.locreloff, self.nlocrel)
return s
class SymtabLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.symoff = 0
self.nsyms = 0
self.stroff = 0
self.strsize = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
self.symoff, self.nsyms, self.stroff, self.strsize = data.get_n_uint32(
4)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "symoff = %#8.8x, nsyms = %u, stroff = %#8.8x, strsize = %u" % (
self.symoff, self.nsyms, self.stroff, self.strsize)
return s
class UUIDLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.uuid = None
def unpack(self, mach_file, data):
uuid_data = data.get_n_uint8(16)
uuid_str = ''
for byte in uuid_data:
uuid_str += '%2.2x' % byte
self.uuid = uuid.UUID(uuid_str)
mach_file.uuid = self.uuid
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += self.uuid.__str__()
return s
class DataBlobLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.dataoff = 0
self.datasize = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
self.dataoff, self.datasize = data.get_n_uint32(2)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "dataoff = %#8.8x, datasize = %u" % (
self.dataoff, self.datasize)
return s
class EncryptionInfoLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.cryptoff = 0
self.cryptsize = 0
self.cryptid = 0
def unpack(self, mach_file, data):
byte_order_char = mach_file.magic.get_byte_order()
self.cryptoff, self.cryptsize, self.cryptid = data.get_n_uint32(3)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
s += "file-range = [%#8.8x - %#8.8x), cryptsize = %u, cryptid = %u" % (
self.cryptoff, self.cryptoff + self.cryptsize, self.cryptsize, self.cryptid)
return s
class SegmentLoadCommand(LoadCommand):
def __init__(self, lc):
Mach.LoadCommand.__init__(self, lc.command, lc.length, lc.file_off)
self.segname = None
self.vmaddr = 0
self.vmsize = 0
self.fileoff = 0
self.filesize = 0
self.maxprot = 0
self.initprot = 0
self.nsects = 0
self.flags = 0
def unpack(self, mach_file, data):
is_64 = self.command.get_enum_value() == LC_SEGMENT_64
self.segname = data.get_fixed_length_c_string(16, '', True)
if is_64:
self.vmaddr, self.vmsize, self.fileoff, self.filesize = data.get_n_uint64(
4)
else:
self.vmaddr, self.vmsize, self.fileoff, self.filesize = data.get_n_uint32(
4)
self.maxprot, self.initprot, self.nsects, self.flags = data.get_n_uint32(
4)
mach_file.segments.append(self)
for i in range(self.nsects):
section = Mach.Section()
section.unpack(is_64, data)
section.index = len(mach_file.sections)
mach_file.sections.append(section)
def __str__(self):
s = Mach.LoadCommand.__str__(self)
if self.command.get_enum_value() == LC_SEGMENT:
s += "%#8.8x %#8.8x %#8.8x %#8.8x " % (
self.vmaddr, self.vmsize, self.fileoff, self.filesize)
else:
s += "%#16.16x %#16.16x %#16.16x %#16.16x " % (
self.vmaddr, self.vmsize, self.fileoff, self.filesize)
s += "%s %s %3u %#8.8x" % (vm_prot_names[self.maxprot], vm_prot_names[
self.initprot], self.nsects, self.flags)
s += ' ' + self.segname
return s
class NList:
class Type:
class Stab(dict_utils.Enum):
enum = {
'N_GSYM': N_GSYM,
'N_FNAME': N_FNAME,
'N_FUN': N_FUN,
'N_STSYM': N_STSYM,
'N_LCSYM': N_LCSYM,
'N_BNSYM': N_BNSYM,
'N_OPT': N_OPT,
'N_RSYM': N_RSYM,
'N_SLINE': N_SLINE,
'N_ENSYM': N_ENSYM,
'N_SSYM': N_SSYM,
'N_SO': N_SO,
'N_OSO': N_OSO,
'N_LSYM': N_LSYM,
'N_BINCL': N_BINCL,
'N_SOL': N_SOL,
'N_PARAMS': N_PARAMS,
'N_VERSION': N_VERSION,
'N_OLEVEL': N_OLEVEL,
'N_PSYM': N_PSYM,
'N_EINCL': N_EINCL,
'N_ENTRY': N_ENTRY,
'N_LBRAC': N_LBRAC,
'N_EXCL': N_EXCL,
'N_RBRAC': N_RBRAC,
'N_BCOMM': N_BCOMM,
'N_ECOMM': N_ECOMM,
'N_ECOML': N_ECOML,
'N_LENG': N_LENG
}
def __init__(self, magic=0):
dict_utils.Enum.__init__(self, magic, self.enum)
def __init__(self, t=0):
self.value = t
def __str__(self):
n_type = self.value
if n_type & N_STAB:
stab = Mach.NList.Type.Stab(self.value)
return '%s' % stab
else:
type = self.value & N_TYPE
type_str = ''
if type == N_UNDF:
type_str = 'N_UNDF'
elif type == N_ABS:
type_str = 'N_ABS '
elif type == N_SECT:
type_str = 'N_SECT'
elif type == N_PBUD:
type_str = 'N_PBUD'
elif type == N_INDR:
type_str = 'N_INDR'
else:
type_str = "??? (%#2.2x)" % type
if n_type & N_PEXT:
type_str += ' | PEXT'
if n_type & N_EXT:
type_str += ' | EXT '
return type_str
def __init__(self):
self.index = 0
self.name_offset = 0
self.name = 0
self.type = Mach.NList.Type()
self.sect_idx = 0
self.desc = 0
self.value = 0
def unpack(self, mach_file, data, symtab_lc):
self.index = len(mach_file.symbols)
self.name_offset = data.get_uint32()
self.type.value, self.sect_idx = data.get_n_uint8(2)
self.desc = data.get_uint16()
if mach_file.is_64_bit():
self.value = data.get_uint64()
else:
self.value = data.get_uint32()
data.push_offset_and_seek(
mach_file.file_off +
symtab_lc.stroff +
self.name_offset)
# print "get string for symbol[%u]" % self.index
self.name = data.get_c_string()
data.pop_offset_and_seek()
def __str__(self):
name_display = ''
if len(self.name):
name_display = ' "%s"' % self.name
return '%#8.8x %#2.2x (%-20s) %#2.2x %#4.4x %16.16x%s' % (self.name_offset,
self.type.value, self.type, self.sect_idx, self.desc, self.value, name_display)
class Interactive(cmd.Cmd):
'''Interactive command interpreter to mach-o files.'''
def __init__(self, mach, options):
cmd.Cmd.__init__(self)
self.intro = 'Interactive mach-o command interpreter'
self.prompt = 'mach-o: %s %% ' % mach.path
self.mach = mach
self.options = options
def default(self, line):
'''Catch all for unknown command, which will exit the interpreter.'''
print "uknown command: %s" % line
return True
def do_q(self, line):
'''Quit command'''
return True
def do_quit(self, line):
'''Quit command'''
return True
def do_header(self, line):
'''Dump mach-o file headers'''
self.mach.dump_header(True, self.options)
return False
def do_load(self, line):
'''Dump all mach-o load commands'''
self.mach.dump_load_commands(True, self.options)
return False
def do_sections(self, line):
'''Dump all mach-o sections'''
self.mach.dump_sections(True, self.options)
return False
def do_symtab(self, line):
'''Dump all mach-o symbols in the symbol table'''
self.mach.dump_symtab(True, self.options)
return False
if __name__ == '__main__':
parser = optparse.OptionParser(
description='A script that parses skinny and universal mach-o files.')
parser.add_option(
'--arch',
'-a',
type='string',
metavar='arch',
dest='archs',
action='append',
help='specify one or more architectures by name')
parser.add_option(
'-v',
'--verbose',
action='store_true',
dest='verbose',
help='display verbose debug info',
default=False)
parser.add_option(
'-H',
'--header',
action='store_true',
dest='dump_header',
help='dump the mach-o file header',
default=False)
parser.add_option(
'-l',
'--load-commands',
action='store_true',
dest='dump_load_commands',
help='dump the mach-o load commands',
default=False)
parser.add_option(
'-s',
'--symtab',
action='store_true',
dest='dump_symtab',
help='dump the mach-o symbol table',
default=False)
parser.add_option(
'-S',
'--sections',
action='store_true',
dest='dump_sections',
help='dump the mach-o sections',
default=False)
parser.add_option(
'--section',
type='string',
metavar='sectname',
dest='section_names',
action='append',
help='Specify one or more section names to dump',
default=[])
parser.add_option(
'-o',
'--out',
type='string',
dest='outfile',
help='Used in conjunction with the --section=NAME option to save a single section\'s data to disk.',
default=False)
parser.add_option(
'-i',
'--interactive',
action='store_true',
dest='interactive',
help='enable interactive mode',
default=False)
parser.add_option(
'-m',
'--mangled',
action='store_true',
dest='find_mangled',
help='dump all mangled names in a mach file',
default=False)
parser.add_option(
'-c',
'--compare',
action='store_true',
dest='compare',
help='compare two mach files',
default=False)
parser.add_option(
'-M',
'--extract-modules',
action='store_true',
dest='extract_modules',
help='Extract modules from file',
default=False)
parser.add_option(
'-C',
'--count',
type='int',
dest='max_count',
help='Sets the max byte count when dumping section data',
default=-1)
(options, mach_files) = parser.parse_args()
if options.extract_modules:
if options.section_names:
print "error: can't use --section option with the --extract-modules option"
exit(1)
if not options.outfile:
print "error: the --output=FILE option must be specified with the --extract-modules option"
exit(1)
options.section_names.append("__apple_ast")
if options.compare:
if len(mach_files) == 2:
mach_a = Mach()
mach_b = Mach()
mach_a.parse(mach_files[0])
mach_b.parse(mach_files[1])
mach_a.compare(mach_b)
else:
print 'error: --compare takes two mach files as arguments'
else:
if not (options.dump_header or options.dump_load_commands or options.dump_symtab or options.dump_sections or options.find_mangled or options.section_names):
options.dump_header = True
options.dump_load_commands = True
if options.verbose:
print 'options', options
print 'mach_files', mach_files
for path in mach_files:
mach = Mach()
mach.parse(path)
if options.interactive:
interpreter = Mach.Interactive(mach, options)
interpreter.cmdloop()
else:
mach.dump(options)
| 39,288 |
778 | package org.aion.zero.impl.sync.msg;
import static com.google.common.truth.Truth.assertThat;
import static org.aion.zero.impl.sync.DatabaseType.DETAILS;
import static org.aion.zero.impl.sync.DatabaseType.STATE;
import static org.aion.zero.impl.sync.DatabaseType.STORAGE;
import static org.aion.zero.impl.sync.msg.RequestTrieDataTest.altNodeKey;
import static org.aion.zero.impl.sync.msg.RequestTrieDataTest.largeNodeKey;
import static org.aion.zero.impl.sync.msg.RequestTrieDataTest.nodeKey;
import static org.aion.zero.impl.sync.msg.RequestTrieDataTest.smallNodeKey;
import static org.aion.zero.impl.sync.msg.RequestTrieDataTest.zeroNodeKey;
import static org.aion.zero.impl.sync.msg.ResponseTrieData.encodeReferencedNodes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.aion.p2p.Ver;
import org.aion.rlp.RLP;
import org.aion.util.types.ByteArrayWrapper;
import org.aion.zero.impl.sync.Act;
import org.aion.zero.impl.sync.DatabaseType;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Unit tests for {@link ResponseTrieData} messages.
*
* @author <NAME>
*/
@RunWith(JUnitParamsRunner.class)
public class ResponseTrieDataTest {
// keys
public static final ByteArrayWrapper wrappedNodeKey = ByteArrayWrapper.wrap(nodeKey);
private static final ByteArrayWrapper wrappedAltNodeKey = ByteArrayWrapper.wrap(altNodeKey);
private static final ByteArrayWrapper wrappedZeroNodeKey = ByteArrayWrapper.wrap(zeroNodeKey);
// values (taken from TrieTest#testGetReferencedTrieNodes_withStartFromAllNodes)
public static final byte[] emptyValue = new byte[] {};
public static final byte[] leafValue =
new byte[] {
-8, 114, -97, 60, -96, -3, -97, 10, 112, 111, 28, -32, 44, 18, 101, -106, 51, 6,
-107, 0, 24, 13, 50, 81, -84, 68, 125, 110, 118, 97, -109, -96, -30, 107, -72, 80,
-8, 78, -128, -118, -45, -62, 27, -50, -52, -19, -95, 0, 0, 0, -96, 69, -80, -49,
-62, 32, -50, -20, 91, 124, 28, 98, -60, -44, 25, 61, 56, -28, -21, -92, -114, -120,
21, 114, -100, -25, 95, -100, 10, -80, -28, -63, -64, -96, 14, 87, 81, -64, 38, -27,
67, -78, -24, -85, 46, -80, 96, -103, -38, -95, -47, -27, -33, 71, 119, -113, 119,
-121, -6, -85, 69, -51, -15, 47, -29, -88
};
public static final byte[] branchValue =
new byte[] {
-8, -111, -128, -96, -99, -57, 89, 41, -60, -8, -93, -128, 9, -59, -23, -116, 4, 70,
-94, -76, 119, -16, 22, 117, -72, -96, -117, 125, -57, 95, 123, -29, -46, 37, -78,
86, -96, 89, -62, -94, 108, -21, -48, -19, 80, 5, 59, -70, 24, 90, 125, 19, -31,
-82, 88, 49, 78, 44, 55, -44, 108, 31, 123, -120, 95, -39, 59, 104, 122, -96, -102,
-109, -7, 6, 55, -12, 8, 32, -45, 116, 125, -50, 117, 7, 6, -59, -109, 88, 32, 95,
92, 97, 26, -107, -84, 85, 25, 9, 83, 78, -20, -37, -128, -128, -128, -128, -96,
-35, -15, -76, -107, -93, -23, -114, 24, -105, -87, -79, 37, 125, 65, 114, -43, -97,
-53, -32, -37, -94, 59, -117, -121, -127, 44, -94, -91, 89, 25, -39, -85, -128,
-128, -128, -128, -128, -128, -128, -128
};
private static final byte[] extensionValue =
new byte[] {
-28, -126, 0, -96, -96, 47, 42, 45, 74, -35, -117, 16, -124, 44, -19, 49, -116, -10,
-40, 41, -109, 34, -77, -58, -109, -116, -57, -110, 51, 7, 24, -70, 33, 120, 116,
10, -106
};
// referenced nodes
private static final Map<ByteArrayWrapper, byte[]> emptyReferences = Map.of();
public static final Map<ByteArrayWrapper, byte[]> singleReference =
Map.of(wrappedAltNodeKey, branchValue);
public static final Map<ByteArrayWrapper, byte[]> multipleReferences =
Map.of(wrappedAltNodeKey, branchValue, wrappedZeroNodeKey, extensionValue);
// other
private static final byte[] emptyByteArray = new byte[] {};
/**
* Parameters for testing:
*
* <ul>
* <li>{@link #testDecode_correct(ByteArrayWrapper, byte[], Map, DatabaseType)}
* <li>{@link #testEncode_4Parameters_correct(ByteArrayWrapper, byte[], Map, DatabaseType)}
* <li>{@link #testEncodeDecode(ByteArrayWrapper, byte[], Map, DatabaseType)}
* </ul>
*/
@SuppressWarnings("unused")
private Object correctParameters() {
List<Object> parameters = new ArrayList<>();
ByteArrayWrapper[] keyOptions =
new ByteArrayWrapper[] {wrappedNodeKey, wrappedAltNodeKey, wrappedZeroNodeKey};
byte[][] valueOptions = new byte[][] {leafValue, branchValue, extensionValue};
Object[] refOptions = new Object[] {emptyReferences, singleReference, multipleReferences};
DatabaseType[] dbOptions = new DatabaseType[] {STATE, STORAGE, DETAILS};
// network and directory
String[] net_values = new String[] {"mainnet", "invalid"};
for (ByteArrayWrapper key : keyOptions) {
for (byte[] value : valueOptions) {
for (Object refs : refOptions) {
for (DatabaseType db : dbOptions) {
parameters.add(new Object[] {key, value, refs, db});
}
}
}
}
return parameters.toArray();
}
/**
* Parameters for testing:
*
* <ul>
* <li>{@link #testEncode_3Parameters_correct(ByteArrayWrapper, byte[], DatabaseType)}
* <li>{@link #testEncodeDecode_3Parameters(ByteArrayWrapper, byte[], DatabaseType)}
* </ul>
*/
@SuppressWarnings("unused")
private Object correct3Parameters() {
List<Object> parameters = new ArrayList<>();
ByteArrayWrapper[] keyOptions =
new ByteArrayWrapper[] {wrappedNodeKey, wrappedAltNodeKey, wrappedZeroNodeKey};
byte[][] valueOptions = new byte[][] {leafValue, branchValue, extensionValue};
DatabaseType[] dbOptions = new DatabaseType[] {STATE, STORAGE, DETAILS};
// network and directory
String[] net_values = new String[] {"mainnet", "invalid"};
for (ByteArrayWrapper key : keyOptions) {
for (byte[] value : valueOptions) {
for (DatabaseType db : dbOptions) {
parameters.add(new Object[] {key, value, db});
}
}
}
return parameters.toArray();
}
@Test(expected = NullPointerException.class)
public void testConstructor_3Parameters_nullKey() {
new ResponseTrieData(null, leafValue, STATE);
}
@Test(expected = NullPointerException.class)
public void testConstructor_4Parameters_nullKey() {
new ResponseTrieData(null, leafValue, multipleReferences, STATE);
}
@Test(expected = NullPointerException.class)
public void testConstructor_3Parameters_nullValue() {
new ResponseTrieData(wrappedNodeKey, null, STATE);
}
@Test(expected = NullPointerException.class)
public void testConstructor_4Parameters_nullValue() {
new ResponseTrieData(wrappedNodeKey, null, multipleReferences, STATE);
}
@Test(expected = NullPointerException.class)
public void testConstructor_4Parameters_nullReferencedNodes() {
new ResponseTrieData(wrappedNodeKey, leafValue, null, STATE);
}
@Test(expected = NullPointerException.class)
public void testConstructor_3Parameters_nullType() {
new ResponseTrieData(wrappedNodeKey, leafValue, null);
}
@Test(expected = NullPointerException.class)
public void testConstructor_4Parameters_nullType() {
new ResponseTrieData(wrappedNodeKey, leafValue, multipleReferences, null);
}
@Test
public void testHeader_newObject_3Parameters() {
ResponseTrieData message = new ResponseTrieData(wrappedAltNodeKey, leafValue, STATE);
// check message header
assertThat(message.getHeader().getVer()).isEqualTo(Ver.V1);
assertThat(message.getHeader().getAction()).isEqualTo(Act.RESPONSE_TRIE_DATA);
}
@Test
public void testHeader_newObject_4Parameters() {
ResponseTrieData message =
new ResponseTrieData(wrappedAltNodeKey, leafValue, multipleReferences, STATE);
// check message header
assertThat(message.getHeader().getVer()).isEqualTo(Ver.V1);
assertThat(message.getHeader().getAction()).isEqualTo(Act.RESPONSE_TRIE_DATA);
}
@Test
public void testHeader_decode() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
ResponseTrieData message = ResponseTrieData.decode(encoding);
// check message header
assertThat(message).isNotNull();
assertThat(message.getHeader().getVer()).isEqualTo(Ver.V1);
assertThat(message.getHeader().getAction()).isEqualTo(Act.RESPONSE_TRIE_DATA);
}
@Test
public void testDecode_nullMessage() {
assertThat(ResponseTrieData.decode(null)).isNull();
}
@Test
public void testDecode_emptyMessage() {
assertThat(ResponseTrieData.decode(emptyByteArray)).isNull();
}
@Test
public void testDecode_missingKey() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_missingValue() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_missingReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_missingType() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_additionalValue() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_notAList() {
byte[] encoding = RLP.encodeElement(nodeKey);
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_outOfOrder() {
byte[] encoding =
RLP.encodeList(
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_smallerKeySize() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(smallNodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_largerKeySize() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(largeNodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_emptyValue() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(emptyValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectElementReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeElement(branchValue),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectListReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeElement(branchValue)),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectPairReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(
RLP.encodeList(
RLP.encodeElement(nodeKey), RLP.encodeElement(leafValue)),
branchValue),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectValueReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(
RLP.encodeList(
RLP.encodeElement(nodeKey), RLP.encodeElement(leafValue)),
RLP.encodeList(
RLP.encodeElement(wrappedAltNodeKey.toBytes()),
RLP.encodeElement(emptyValue))),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectKeyReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(
RLP.encodeList(
RLP.encodeElement(nodeKey), RLP.encodeElement(leafValue)),
RLP.encodeList(
RLP.encodeElement(smallNodeKey),
RLP.encodeElement(branchValue))),
RLP.encodeString(STATE.toString()));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
public void testDecode_incorrectType() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString("random"));
assertThat(ResponseTrieData.decode(encoding)).isNull();
}
@Test
@Parameters(method = "correctParameters")
public void testDecode_correct(
ByteArrayWrapper key,
byte[] value,
Map<ByteArrayWrapper, byte[]> referencedNodes,
DatabaseType dbType) {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(key.toBytes()),
RLP.encodeElement(value),
RLP.encodeList(encodeReferencedNodes(referencedNodes)),
RLP.encodeString(dbType.toString()));
ResponseTrieData message = ResponseTrieData.decode(encoding);
assertThat(message).isNotNull();
assertThat(message.getNodeKey()).isEqualTo(key);
assertThat(message.getNodeValue()).isEqualTo(value);
assertThat(message.getReferencedNodes().size()).isEqualTo(referencedNodes.size());
for (Map.Entry<ByteArrayWrapper, byte[]> entry : message.getReferencedNodes().entrySet()) {
assertThat(Arrays.equals(referencedNodes.get(entry.getKey()), entry.getValue()))
.isTrue();
}
assertThat(message.getDbType()).isEqualTo(dbType);
}
@Test
@Parameters(method = "correct3Parameters")
public void testEncode_3Parameters_correct(
ByteArrayWrapper key, byte[] value, DatabaseType dbType) {
byte[] expected =
RLP.encodeList(
RLP.encodeElement(key.toBytes()),
RLP.encodeElement(value),
RLP.encodeList(encodeReferencedNodes(emptyReferences)),
RLP.encodeString(dbType.toString()));
ResponseTrieData message = new ResponseTrieData(key, value, dbType);
assertThat(message.encode()).isEqualTo(expected);
}
@Test
@Parameters(method = "correctParameters")
public void testEncode_4Parameters_correct(
ByteArrayWrapper key,
byte[] value,
Map<ByteArrayWrapper, byte[]> referencedNodes,
DatabaseType dbType) {
byte[] expected =
RLP.encodeList(
RLP.encodeElement(key.toBytes()),
RLP.encodeElement(value),
RLP.encodeList(encodeReferencedNodes(referencedNodes)),
RLP.encodeString(dbType.toString()));
ResponseTrieData message = new ResponseTrieData(key, value, referencedNodes, dbType);
assertThat(message.encode()).isEqualTo(expected);
}
@Test
@Parameters(method = "correctParameters")
public void testEncodeDecode(
ByteArrayWrapper key,
byte[] value,
Map<ByteArrayWrapper, byte[]> referencedNodes,
DatabaseType dbType) {
// encode
ResponseTrieData message = new ResponseTrieData(key, value, referencedNodes, dbType);
assertThat(message.getNodeKey()).isEqualTo(key);
assertThat(message.getNodeValue()).isEqualTo(value);
assertThat(message.getReferencedNodes()).isEqualTo(referencedNodes);
assertThat(message.getDbType()).isEqualTo(dbType);
byte[] encoding = message.encode();
// decode
ResponseTrieData decoded = ResponseTrieData.decode(encoding);
assertThat(decoded).isNotNull();
assertThat(decoded.getNodeKey()).isEqualTo(key);
assertThat(decoded.getNodeValue()).isEqualTo(value);
assertThat(decoded.getReferencedNodes().size()).isEqualTo(referencedNodes.size());
for (Map.Entry<ByteArrayWrapper, byte[]> entry : decoded.getReferencedNodes().entrySet()) {
assertThat(Arrays.equals(referencedNodes.get(entry.getKey()), entry.getValue()))
.isTrue();
}
assertThat(decoded.getDbType()).isEqualTo(dbType);
}
@Test
@Parameters(method = "correct3Parameters")
public void testEncodeDecode_3Parameters(
ByteArrayWrapper key, byte[] value, DatabaseType dbType) {
// encode
ResponseTrieData message = new ResponseTrieData(key, value, dbType);
assertThat(message.getNodeKey()).isEqualTo(key);
assertThat(message.getNodeValue()).isEqualTo(value);
assertThat(message.getReferencedNodes()).isEmpty();
assertThat(message.getDbType()).isEqualTo(dbType);
byte[] encoding = message.encode();
// decode
ResponseTrieData decoded = ResponseTrieData.decode(encoding);
assertThat(decoded).isNotNull();
assertThat(decoded.getNodeKey()).isEqualTo(key);
assertThat(decoded.getNodeValue()).isEqualTo(value);
assertThat(decoded.getReferencedNodes()).isEmpty();
assertThat(decoded.getDbType()).isEqualTo(dbType);
}
@Test
public void testEncode_differentKey() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
ResponseTrieData message =
new ResponseTrieData(wrappedAltNodeKey, leafValue, multipleReferences, STATE);
assertThat(message.encode()).isNotEqualTo(encoding);
}
@Test
public void testEncode_differentValue() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
ResponseTrieData message =
new ResponseTrieData(wrappedNodeKey, branchValue, multipleReferences, STATE);
assertThat(message.encode()).isNotEqualTo(encoding);
}
@Test
public void testEncode_differentReferences() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
ResponseTrieData message =
new ResponseTrieData(wrappedNodeKey, leafValue, singleReference, STATE);
assertThat(message.encode()).isNotEqualTo(encoding);
}
@Test
public void testEncode_differentType() {
byte[] encoding =
RLP.encodeList(
RLP.encodeElement(nodeKey),
RLP.encodeElement(leafValue),
RLP.encodeList(encodeReferencedNodes(multipleReferences)),
RLP.encodeString(STATE.toString()));
ResponseTrieData message =
new ResponseTrieData(wrappedNodeKey, leafValue, multipleReferences, STORAGE);
assertThat(message.encode()).isNotEqualTo(encoding);
}
}
| 11,607 |
370 | <reponame>gabrielfougeron/SuiteSparse
/* ========================================================================== */
/* === Source/Mongoose_QPDelta.cpp ========================================== */
/* ========================================================================== */
/* -----------------------------------------------------------------------------
* Mongoose Graph Partitioning Library Copyright (C) 2017-2018,
* <NAME>, <NAME>, <NAME>, <NAME>
* Mongoose is licensed under Version 3 of the GNU General Public License.
* Mongoose is also available under other licenses; contact authors for details.
* -------------------------------------------------------------------------- */
#include "Mongoose_QPDelta.hpp"
#include "Mongoose_Internal.hpp"
namespace Mongoose
{
QPDelta *QPDelta::Create(Int numVars)
{
QPDelta *ret = (QPDelta *)SuiteSparse_calloc(1, sizeof(QPDelta));
if (!ret)
return NULL;
ret->x = (double *)SuiteSparse_malloc(static_cast<size_t>(numVars),
sizeof(double));
ret->FreeSet_status
= (Int *)SuiteSparse_malloc(static_cast<size_t>(numVars), sizeof(Int));
ret->FreeSet_list = (Int *)SuiteSparse_malloc(
static_cast<size_t>(numVars + 1), sizeof(Int));
ret->gradient = (double *)SuiteSparse_malloc(static_cast<size_t>(numVars),
sizeof(double));
ret->D = (double *)SuiteSparse_malloc(static_cast<size_t>(numVars),
sizeof(double));
for (int i = 0; i < WISIZE; i++)
{
ret->wi[i] = (Int *)SuiteSparse_malloc(static_cast<size_t>(numVars + 1),
sizeof(Int));
}
for (Int i = 0; i < WXSIZE; i++)
{
ret->wx[i] = (double *)SuiteSparse_malloc(static_cast<size_t>(numVars),
sizeof(double));
}
#ifndef NDEBUG
ret->check_cost = INFINITY;
#endif
if (!ret->x || !ret->FreeSet_status || !ret->FreeSet_list || !ret->gradient
|| !ret->D || !ret->wi[0]
|| !ret->wi[1]
//|| !ret->Change_location
|| !ret->wx[0] || !ret->wx[1] || !ret->wx[2])
{
ret->~QPDelta();
ret = (QPDelta *)SuiteSparse_free(ret);
}
return ret;
}
QPDelta::~QPDelta()
{
x = (double *)SuiteSparse_free(x);
FreeSet_status = (Int *)SuiteSparse_free(FreeSet_status);
FreeSet_list = (Int *)SuiteSparse_free(FreeSet_list);
gradient = (double *)SuiteSparse_free(gradient);
D = (double *)SuiteSparse_free(D);
// Change_location = (Int*) SuiteSparse_free(Change_location);
for (Int i = 0; i < WISIZE; i++)
{
wi[i] = (Int *)SuiteSparse_free(wi[i]);
}
for (Int i = 0; i < WXSIZE; i++)
{
wx[i] = (double *)SuiteSparse_free(wx[i]);
}
}
} // end namespace Mongoose
| 1,300 |
648 | {"resourceType":"ValueSet","id":"claim-type-link","meta":{"lastUpdated":"2015-10-24T07:41:03.495+11:00","profile":["http://hl7.org/fhir/StructureDefinition/valueset-shareable-definition"]},"text":{"status":"generated","div":"<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <h2>ClaimType</h2>\n <p>The type or discipline-style of the claim.</p>\n <p>This value set has an inline code system http://hl7.org/fhir/claim-type-link, which defines the following codes:</p>\n <table class=\"codes\">\n <tr>\n <td>\n <b>Code</b>\n </td>\n <td>\n <b>Display</b>\n </td>\n <td>\n <b>Definition</b>\n </td>\n </tr>\n <tr>\n <td>institutional\n <a name=\"institutional\"> </a>\n </td>\n <td>Institutional</td>\n <td>A claim for Institution based, typically in-patient, goods and services.</td>\n </tr>\n <tr>\n <td>oral\n <a name=\"oral\"> </a>\n </td>\n <td>Oral Health</td>\n <td>A claim for Oral Health (Dentist, Denturist, Hygienist) goods and services.</td>\n </tr>\n <tr>\n <td>pharmacy\n <a name=\"pharmacy\"> </a>\n </td>\n <td>Pharmacy</td>\n <td>A claim for Pharmacy based goods and services.</td>\n </tr>\n <tr>\n <td>professional\n <a name=\"professional\"> </a>\n </td>\n <td>Professional</td>\n <td>A claim for Professional, typically out-patient, goods and services.</td>\n </tr>\n <tr>\n <td>vision\n <a name=\"vision\"> </a>\n </td>\n <td>Vision</td>\n <td>A claim for Vision (Ophthamologist, Optometrist and Optician) goods and services.</td>\n </tr>\n </table>\n </div>"},"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.2.322"}],"url":"http://hl7.org/fhir/ValueSet/claim-type-link","version":"1.0.2","name":"ClaimType","status":"draft","experimental":false,"publisher":"HL7 (FHIR Project)","contact":[{"telecom":[{"system":"other","value":"http://hl7.org/fhir"},{"system":"email","value":"<EMAIL>"}]}],"date":"2015-10-24T07:41:03+11:00","description":"The type or discipline-style of the claim.","codeSystem":{"extension":[{"url":"http://hl7.org/fhir/StructureDefinition/valueset-oid","valueUri":"urn:oid:2.16.840.1.113883.4.642.1.322"}],"system":"http://hl7.org/fhir/claim-type-link","version":"1.0.2","caseSensitive":true,"concept":[{"code":"institutional","display":"Institutional","definition":"A claim for Institution based, typically in-patient, goods and services."},{"code":"oral","display":"Oral Health","definition":"A claim for Oral Health (Dentist, Denturist, Hygienist) goods and services."},{"code":"pharmacy","display":"Pharmacy","definition":"A claim for Pharmacy based goods and services."},{"code":"professional","display":"Professional","definition":"A claim for Professional, typically out-patient, goods and services."},{"code":"vision","display":"Vision","definition":"A claim for Vision (Ophthamologist, Optometrist and Optician) goods and services."}]}} | 1,739 |
19,438 | <filename>Tests/AK/TestFixedArray.cpp
/*
* Copyright (c) 2018-2021, <NAME> <<EMAIL>>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestSuite.h>
#include <AK/FixedArray.h>
#include <AK/String.h>
TEST_CASE(construct)
{
EXPECT(FixedArray<int>().size() == 0);
}
TEST_CASE(ints)
{
FixedArray<int> ints(3);
ints[0] = 0;
ints[1] = 1;
ints[2] = 2;
EXPECT_EQ(ints[0], 0);
EXPECT_EQ(ints[1], 1);
EXPECT_EQ(ints[2], 2);
ints.clear();
EXPECT_EQ(ints.size(), 0u);
}
| 261 |
3,494 | <reponame>rsh/Cinder-Emscripten<filename>test/_audio/ParamTest/src/ParamTestApp.cpp
#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/Rand.h"
#include "cinder/Timeline.h"
#include "cinder/CinderAssert.h"
#include "cinder/Log.h"
#include "cinder/audio/Context.h"
#include "cinder/audio/GenNode.h"
#include "cinder/audio/NodeEffects.h"
#include "cinder/audio/FilterNode.h"
#include "cinder/audio/Target.h"
#include "../../common/AudioTestGui.h"
using namespace ci;
using namespace ci::app;
using namespace std;
class ParamTestApp : public App {
public:
void setup() override;
void update() override;
void draw() override;
void keyDown( KeyEvent event ) override;
void setupBasic();
void setupFilter();
void setupUI();
void processDrag( ivec2 pos );
void processTap( ivec2 pos );
void testApply();
void testApply0();
void testApply2();
void testAppend();
void testDelay();
void testAppendCancel();
void testProcessor();
void testSchedule();
void writeParamEval( audio::Param *param );
audio::GenNodeRef mGen;
audio::GainNodeRef mGain;
audio::Pan2dNodeRef mPan;
audio::FilterLowPassNodeRef mLowPass;
vector<TestWidget *> mWidgets;
Button mPlayButton, mApplyButton, mApply0Button, mApplyAppendButton, mAppendButton;
Button mDelayButton, mProcessorButton, mAppendCancelButton, mScheduleButton;
VSelector mTestSelector;
HSlider mGainSlider, mPanSlider, mLowPassFreqSlider, mGenFreqSlider;
};
void ParamTestApp::setup()
{
auto ctx = audio::master();
mGain = ctx->makeNode( new audio::GainNode() );
mGain->setValue( 0.8f );
mPan = ctx->makeNode( new audio::Pan2dNode() );
mGen = ctx->makeNode( new audio::GenSineNode() );
// mGen = ctx->makeNode( new audio::GenTriangleNode() );
// mGen = ctx->makeNode( new audio::GenPhasorNode() );
mGen = ctx->makeNode( new audio::GenPulseNode );
mGen->setFreq( 220 );
mLowPass = ctx->makeNode( new audio::FilterLowPassNode() );
setupBasic();
setupUI();
PRINT_GRAPH( ctx );
testApply();
// testApply2();
// connectProcessor();
}
void ParamTestApp::setupBasic()
{
mGen >> mGain >> audio::master()->getOutput();
mGen->enable();
}
void ParamTestApp::setupFilter()
{
mGen >> mLowPass >> mGain >> mPan >> audio::master()->getOutput();
mGen->enable();
}
void ParamTestApp::testApply()
{
// (a): ramp volume to 0.7 of 0.2 seconds
// mGain->getParam()->applyRamp( 0.7f, 0.2f );
mGen->getParamFreq()->applyRamp( 220, 440, 2 );
// PSEUDO CODE: possible syntax where context keeps references to Params, calling updateValueArray() (or just process() ?) on them each block:
// - problem I have with this right now is that its alot more syntax for the common case (see: (a)) of ramping up volume
// Context::master()->timeline()->apply( mGen->getParamFreq(), 220, 440, 1 );
// - a bit shorter:
// audio::timeline()->apply( mGen->getParamFreq(), 220, 440, 1 );
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
}
// same as testApply(), but ramp time = 0. end value should still be set.
void ParamTestApp::testApply0()
{
mGen->getParamFreq()->applyRamp( 220, 440, 0 );
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
}
// 2 events - first apply the ramp, blowing away anything else, then append another event to happen after that
void ParamTestApp::testApply2()
{
mGen->getParamFreq()->applyRamp( 220, 880, 1 );
mGen->getParamFreq()->appendRamp( 369.994f, 1 ); // F#4
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
// writeParamEval( mGen->getParamFreq() );
}
// append an event with random frequency and duration 1 second, allowing them to build up. new events begin from the end of the last event
void ParamTestApp::testAppend()
{
mGen->getParamFreq()->appendRamp( randFloat( 50, 800 ), 1.0f );
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
}
// make a ramp after a 1 second delay
void ParamTestApp::testDelay()
{
mGen->getParamFreq()->applyRamp( 50, 440, 1, audio::Param::Options().delay( 1 ) );
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
}
// apply a ramp from 220 to 880 over 2 seconds and then after a 1 second delay, cancel it. result should be ~ 550: 220 + (880 - 220) / 2.
void ParamTestApp::testAppendCancel()
{
audio::EventRef ramp = mGen->getParamFreq()->applyRamp( 220, 880, 2 );
CI_LOG_V( "num events: " << mGen->getParamFreq()->getNumEvents() );
timeline().add( [ramp] {
CI_LOG_V( "canceling." );
ramp->cancel();
}, (float)getElapsedSeconds() + 1 );
}
void ParamTestApp::testProcessor()
{
auto ctx = audio::master();
auto mod = ctx->makeNode( new audio::GenSineNode( audio::Node::Format().autoEnable() ) );
mod->setFreq( 2 );
mGain->getParam()->setProcessor( mod );
}
void ParamTestApp::testSchedule()
{
bool enabled = mGen->isEnabled();
mGen->setEnabled( ! enabled, audio::master()->getNumProcessedSeconds() + 0.5f );
}
void ParamTestApp::setupUI()
{
const float padding = 10.0f;
mPlayButton = Button( true, "stopped", "playing" );
mPlayButton.mBounds = Rectf( 0, 0, 200, 60 );
mWidgets.push_back( &mPlayButton );
Rectf paramButtonRect( 0, mPlayButton.mBounds.y2 + padding, 120, mPlayButton.mBounds.y2 + padding + 40 );
mApplyButton = Button( false, "apply" );
mApplyButton.mBounds = paramButtonRect;
mWidgets.push_back( &mApplyButton );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mApply0Button = Button( false, "apply0" );
mApply0Button.mBounds = paramButtonRect;
mWidgets.push_back( &mApply0Button );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mApplyAppendButton = Button( false, "apply 2" );
mApplyAppendButton.mBounds = paramButtonRect;
mWidgets.push_back( &mApplyAppendButton );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mAppendButton = Button( false, "append" );
mAppendButton.mBounds = paramButtonRect;
mWidgets.push_back( &mAppendButton );
paramButtonRect = mApplyButton.mBounds + vec2( 0, mApplyButton.mBounds.getHeight() + padding );
mDelayButton = Button( false, "delay" );
mDelayButton.mBounds = paramButtonRect;
mWidgets.push_back( &mDelayButton );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mProcessorButton = Button( false, "processor" );
mProcessorButton.mBounds = paramButtonRect;
mWidgets.push_back( &mProcessorButton );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mAppendCancelButton = Button( false, "cancel" );
mAppendCancelButton.mBounds = paramButtonRect;
mWidgets.push_back( &mAppendCancelButton );
paramButtonRect += vec2( paramButtonRect.getWidth() + padding, 0 );
mScheduleButton = Button( false, "schedule" );
mScheduleButton.mBounds = paramButtonRect;
mWidgets.push_back( &mScheduleButton );
mTestSelector.mSegments.push_back( "basic" );
mTestSelector.mSegments.push_back( "filter" );
mTestSelector.mBounds = Rectf( (float)getWindowWidth() * 0.67f, 0, (float)getWindowWidth(), 160 );
mWidgets.push_back( &mTestSelector );
float width = std::min( (float)getWindowWidth() - 20.0f, 440.0f );
Rectf sliderRect( getWindowCenter().x - width / 2.0f, 200, getWindowCenter().x + width / 2.0f, 250 );
mGainSlider.mBounds = sliderRect;
mGainSlider.mTitle = "GainNode";
mGainSlider.set( mGain->getValue() );
mWidgets.push_back( &mGainSlider );
sliderRect += vec2( 0.0f, sliderRect.getHeight() + 10.0f );
mPanSlider.mBounds = sliderRect;
mPanSlider.mTitle = "Pan";
mPanSlider.set( mPan->getPos() );
mWidgets.push_back( &mPanSlider );
sliderRect += vec2( 0.0f, sliderRect.getHeight() + 10.0f );
mGenFreqSlider.mBounds = sliderRect;
mGenFreqSlider.mTitle = "Gen Freq";
mGenFreqSlider.mMin = -200.0f;
mGenFreqSlider.mMax = 1200.0f;
mGenFreqSlider.set( mGen->getFreq() );
mWidgets.push_back( &mGenFreqSlider );
sliderRect += vec2( 0.0f, sliderRect.getHeight() + 10.0f );
mLowPassFreqSlider.mBounds = sliderRect;
mLowPassFreqSlider.mTitle = "LowPass Freq";
mLowPassFreqSlider.mMax = 1000.0f;
mLowPassFreqSlider.set( mLowPass->getCutoffFreq() );
mWidgets.push_back( &mLowPassFreqSlider );
getWindow()->getSignalMouseDown().connect( [this] ( MouseEvent &event ) { processTap( event.getPos() ); } );
getWindow()->getSignalMouseDrag().connect( [this] ( MouseEvent &event ) { processDrag( event.getPos() ); } );
getWindow()->getSignalTouchesBegan().connect( [this] ( TouchEvent &event ) { processTap( event.getTouches().front().getPos() ); } );
getWindow()->getSignalTouchesMoved().connect( [this] ( TouchEvent &event ) {
for( const TouchEvent::Touch &touch : getActiveTouches() )
processDrag( touch.getPos() );
} );
gl::enableAlphaBlending();
}
void ParamTestApp::processDrag( ivec2 pos )
{
if( mGainSlider.hitTest( pos ) ) {
// mGain->setValue( mGainSlider.mValueScaled );
// mGain->getParam()->applyRamp( mGainSlider.mValueScaled );
mGain->getParam()->applyRamp( mGainSlider.mValueScaled, 0.15f );
}
if( mPanSlider.hitTest( pos ) ) {
// mPan->setPos( mPanSlider.mValueScaled );
mPan->getParamPos()->applyRamp( mPanSlider.mValueScaled, 0.3f, audio::Param::Options().rampFn( &audio::rampOutQuad ) );
}
if( mGenFreqSlider.hitTest( pos ) ) {
// mGen->setFreq( mGenFreqSlider.mValueScaled );
// mGen->getParamFreq()->applyRamp( mGenFreqSlider.mValueScaled, 0.3f );
mGen->getParamFreq()->applyRamp( mGenFreqSlider.mValueScaled, 0.3f, audio::Param::Options().rampFn( &audio::rampOutQuad ) );
}
if( mLowPassFreqSlider.hitTest( pos ) )
mLowPass->setCutoffFreq( mLowPassFreqSlider.mValueScaled );
}
void ParamTestApp::processTap( ivec2 pos )
{
auto ctx = audio::master();
size_t selectorIndex = mTestSelector.mCurrentSectionIndex;
if( mPlayButton.hitTest( pos ) )
ctx->setEnabled( ! ctx->isEnabled() );
else if( mApplyButton.hitTest( pos ) )
testApply();
else if( mApply0Button.hitTest( pos ) )
testApply0();
else if( mApplyAppendButton.hitTest( pos ) )
testApply2();
else if( mAppendButton.hitTest( pos ) )
testAppend();
else if( mDelayButton.hitTest( pos ) )
testDelay();
else if( mProcessorButton.hitTest( pos ) )
testProcessor();
else if( mAppendCancelButton.hitTest( pos ) )
testAppendCancel();
else if( mScheduleButton.hitTest( pos ) )
testSchedule();
else if( mTestSelector.hitTest( pos ) && selectorIndex != mTestSelector.mCurrentSectionIndex ) {
string currentTest = mTestSelector.currentSection();
CI_LOG_V( "selected: " << currentTest );
bool enabled = ctx->isEnabled();
ctx->disable();
ctx->disconnectAllNodes();
if( currentTest == "basic" )
setupBasic();
if( currentTest == "filter" )
setupFilter();
ctx->setEnabled( enabled );
PRINT_GRAPH( ctx );
}
else
processDrag( pos );
}
void ParamTestApp::keyDown( KeyEvent event )
{
if( event.getCode() == KeyEvent::KEY_e )
CI_LOG_V( "mGen freq events: " << mGen->getParamFreq()->getNumEvents() );
}
void ParamTestApp::update()
{
if( audio::master()->isEnabled() ) {
mGainSlider.set( mGain->getValue() );
mGenFreqSlider.set( mGen->getFreq() );
mPanSlider.set( mPan->getPos() );
}
}
void ParamTestApp::draw()
{
gl::clear();
drawWidgets( mWidgets );
}
// TODO: this will be formalized once there is an offline audio context and OutputFileNode.
void ParamTestApp::writeParamEval( audio::Param *param )
{
auto ctx = audio::master();
float duration = param->findDuration();
float currTime = (float)ctx->getNumProcessedSeconds();
size_t sampleRate = ctx->getSampleRate();
audio::Buffer audioBuffer( (size_t)duration * sampleRate );
param->eval( currTime, audioBuffer.getData(), audioBuffer.getSize(), sampleRate );
auto target = audio::TargetFile::create( "param.wav", sampleRate, 1 );
target->write( &audioBuffer );
CI_LOG_V( "write complete" );
}
CINDER_APP( ParamTestApp, RendererGl, []( App::Settings *settings ) {
settings->setWindowSize( 800, 600 );
} )
| 4,875 |
1,537 | <gh_stars>1000+
/****************************************************************************
*
* Copyright (c) 2021 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file PublicationManager.cpp
*
* Manages the dynamic (run-time configurable) UAVCAN publications
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
#include "PublicationManager.hpp"
PublicationManager::~PublicationManager()
{
_dynpublishers.clear();
}
void PublicationManager::updateDynamicPublications()
{
for (auto &sub : _uavcan_pubs) {
bool found_publisher = false;
for (auto &dynpub : _dynpublishers) {
// Check if subscriber has already been created
const char *subj_name = dynpub->getSubjectName();
const uint8_t instance = dynpub->getInstance();
if (strcmp(subj_name, sub.subject_name) == 0 && instance == sub.instance) {
found_publisher = true;
break;
}
}
if (found_publisher) {
continue;
}
char uavcan_param[90];
snprintf(uavcan_param, sizeof(uavcan_param), "uavcan.pub.%s.%d.id", sub.subject_name, sub.instance);
uavcan_register_Value_1_0 value;
if (_param_manager.GetParamByName(uavcan_param, value)) {
uint16_t port_id = value.natural16.value.elements[0];
if (port_id <= CANARD_PORT_ID_MAX) { // PortID is set, create a subscriber
UavcanPublisher *dynpub = sub.create_pub(_canard_instance, _param_manager);
if (dynpub == nullptr) {
PX4_ERR("Out of memory");
return;
}
_dynpublishers.add(dynpub);
dynpub->updateParam();
}
} else {
PX4_ERR("Port ID param for publisher %s.%u not found", sub.subject_name, sub.instance);
return;
}
}
}
void PublicationManager::printInfo()
{
for (auto &dynpub : _dynpublishers) {
dynpub->printInfo();
}
}
void PublicationManager::updateParams()
{
for (auto &dynpub : _dynpublishers) {
dynpub->updateParam();
}
// Check for any newly-enabled publication
updateDynamicPublications();
}
void PublicationManager::update()
{
for (auto &dynpub : _dynpublishers) {
dynpub->update();
}
}
| 1,206 |
407 | <gh_stars>100-1000
package com.alibaba.tesla.appmanager.server.dynamicscript.handler;
import com.alibaba.tesla.appmanager.dynamicscript.core.GroovyHandler;
public interface TraitHandler extends GroovyHandler {
}
| 70 |
311 | /**
* Copyright 2019 The JoyQueue Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.joyqueue.broker.network.protocol;
import com.google.common.collect.Lists;
import org.joyqueue.network.protocol.ProtocolServer;
import org.joyqueue.network.transport.TransportServer;
import org.joyqueue.network.transport.config.ServerConfig;
import org.joyqueue.network.transport.support.ChannelTransportServer;
import org.joyqueue.toolkit.service.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.List;
/**
* MultiProtocolTransportServer
*
* author: gaohaoxiang
* date: 2018/8/13
*/
public class MultiProtocolTransportServer extends Service implements TransportServer {
protected static final Logger logger = LoggerFactory.getLogger(MultiProtocolTransportServer.class);
private ServerConfig serverConfig;
private String host;
private int port;
private ProtocolManager protocolManager;
private MultiProtocolHandlerPipelineFactory multiProtocolHandlerPipelineFactory;
private ProtocolHandlerPipelineFactory protocolHandlerPipelineFactory;
private TransportServer protocolServiceServer;
private List<ProtocolContext> protocolServers;
public MultiProtocolTransportServer(ServerConfig serverConfig, String host,
int port, ProtocolManager protocolManager,
MultiProtocolHandlerPipelineFactory multiProtocolHandlerPipelineFactory,
ProtocolHandlerPipelineFactory protocolHandlerPipelineFactory) {
this.serverConfig = serverConfig;
this.host = host;
this.port = port;
this.protocolManager = protocolManager;
this.multiProtocolHandlerPipelineFactory = multiProtocolHandlerPipelineFactory;
this.protocolHandlerPipelineFactory = protocolHandlerPipelineFactory;
}
@Override
public InetSocketAddress getSocketAddress() {
return new InetSocketAddress(host, port);
}
@Override
public boolean isSSLServer() {
return false;
}
@Override
protected void validate() throws Exception {
this.protocolServiceServer = new ChannelTransportServer(multiProtocolHandlerPipelineFactory.createPipeline(), serverConfig, host, port);
this.protocolServers = initProtocolServers();
}
@Override
protected void doStart() throws Exception {
protocolServiceServer.start();
for (ProtocolContext protocolServer : protocolServers) {
try {
protocolServer.getTransportServer().start();
logger.info("protocol {} is start, address: {}", protocolServer.getProtocol().type(), protocolServer.getTransportServer().getSocketAddress());
} catch (Exception e) {
logger.error("protocol {} start failed", protocolServer.getProtocol().type(), e);
}
}
}
@Override
protected void doStop() {
protocolServiceServer.stop();
for (ProtocolContext protocolServer : protocolServers) {
try {
protocolServer.getTransportServer().stop();
logger.info("protocol {} is stop", protocolServer.getProtocol().type(), protocolServer.getTransportServer().getSocketAddress());
} catch (Exception e) {
logger.error("protocol {} stop failed", protocolServer.getProtocol().type(), e);
}
}
}
protected List<ProtocolContext> initProtocolServers() {
List<ProtocolContext> result = Lists.newArrayList();
for (ProtocolServer protocolServer : protocolManager.getProtocolServers()) {
ServerConfig protocolServerConfig = protocolServer.createServerConfig(serverConfig);
TransportServer transportServer = new ChannelTransportServer(protocolHandlerPipelineFactory.createPipeline(protocolServer),
protocolServerConfig, protocolServerConfig.getHost(), protocolServerConfig.getPort());
result.add(new ProtocolContext(protocolServer, transportServer));
}
return result;
}
} | 1,622 |
480 | <gh_stars>100-1000
/*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.group.utils;
import com.alibaba.polardbx.common.utils.logger.Logger;
import com.alibaba.polardbx.common.utils.logger.LoggerFactory;
import com.alibaba.polardbx.druid.sql.parser.ByteString;
import com.alibaba.polardbx.optimizer.parse.HintParser;
/**
* @author <a href="<EMAIL>">junyu</a>
* @version 1.0
* @since 1.6
*/
public class GroupHintParser {
public static final int NOT_EXIST_USER_SPECIFIED_INDEX = -1;
public static Logger log = LoggerFactory.getLogger(GroupHintParser.class);
public static int extraIndexFromHint(ByteString sql) {
String groupIndexHint = extractTDDLGroupHint(sql);
if (null != groupIndexHint && !groupIndexHint.equals("")) {
String[] hintWithRetry = groupIndexHint.split(",");
if (hintWithRetry.length == 1 || hintWithRetry.length == 2) {
return GroupHintParser.getIndexFromHintPiece(hintWithRetry[0]);
} else {
throw new IllegalArgumentException("the standard group hint is:'groupIndex:12[,failRetry:true]'"
+ ",current hint is:" + groupIndexHint);
}
} else {
return NOT_EXIST_USER_SPECIFIED_INDEX;
}
}
private static int getIndexFromHintPiece(String indexPiece) {
String[] piece = indexPiece.split(":");
if (piece[0].trim().equalsIgnoreCase("groupIndex")) {
return Integer.valueOf(piece[1]);
} else {
throw new IllegalArgumentException(
"the standard group hint is:'groupIndex:12[,failRetry:true]'" + ",current index hint is:" + indexPiece);
}
}
private static boolean getFailRetryFromHintPiece(String retryPiece) {
String[] piece = retryPiece.split(":");
if (piece[0].trim().equalsIgnoreCase("failRetry")) {
return Boolean.valueOf(piece[1]);
} else {
throw new IllegalArgumentException(
"the standard group hint is:'groupIndex:12[,failRetry:true]'" + ",current retry hint is:" + retryPiece);
}
}
public static String extractTDDLGroupHint(ByteString sql) {
int i = 0;
for (; i < sql.length(); ++i) {
switch (sql.charAt(i)) {
case ' ':
case '\t':
case '\r':
case '\n':
continue;
}
break;
}
if (sql.startsWith("/*+TDDL_GROUP", i)) {
return HintParser.getInstance().getTddlGroupHint(sql);
}
return null;
}
public static ByteString removeTddlGroupHint(ByteString sql) {
String tddlHint = extractTDDLGroupHint(sql);
if (null == tddlHint || "".equals(tddlHint)) {
return sql;
}
sql = HintParser.getInstance().removeGroupHint(sql);
return sql;
}
public static String buildTddlGroupHint(String groupHint) {
return "/*+TDDL_GROUP({" + groupHint + "})*/";
}
}
| 1,538 |
11,356 | <reponame>shreyasvj25/turicreate<gh_stars>1000+
// Boost string_algo library predicate.hpp header file ---------------------------//
// Copyright <NAME> 2002-2003.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/ for updates, documentation, and revision history.
#ifndef BOOST_STRING_PREDICATE_HPP
#define BOOST_STRING_PREDICATE_HPP
#include <boost/algorithm/string/config.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator.hpp>
#include <boost/range/const_iterator.hpp>
#include <boost/range/as_literal.hpp>
#include <boost/range/iterator_range_core.hpp>
#include <boost/algorithm/string/compare.hpp>
#include <boost/algorithm/string/find.hpp>
#include <boost/algorithm/string/detail/predicate.hpp>
/*! \file boost/algorithm/string/predicate.hpp
Defines string-related predicates.
The predicates determine whether a substring is contained in the input string
under various conditions: a string starts with the substring, ends with the
substring, simply contains the substring or if both strings are equal.
Additionaly the algorithm \c all() checks all elements of a container to satisfy a
condition.
All predicates provide the strong exception guarantee.
*/
namespace boost {
namespace algorithm {
// starts_with predicate -----------------------------------------------//
//! 'Starts with' predicate
/*!
This predicate holds when the test string is a prefix of the Input.
In other words, if the input starts with the test.
When the optional predicate is specified, it is used for character-wise
comparison.
\param Input An input sequence
\param Test A test sequence
\param Comp An element comparison predicate
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T, typename PredicateT>
inline bool starts_with(
const Range1T& Input,
const Range2T& Test,
PredicateT Comp)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type> lit_input(::boost::as_literal(Input));
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type> lit_test(::boost::as_literal(Test));
typedef BOOST_STRING_TYPENAME
range_const_iterator<Range1T>::type Iterator1T;
typedef BOOST_STRING_TYPENAME
range_const_iterator<Range2T>::type Iterator2T;
Iterator1T InputEnd=::boost::end(lit_input);
Iterator2T TestEnd=::boost::end(lit_test);
Iterator1T it=::boost::begin(lit_input);
Iterator2T pit=::boost::begin(lit_test);
for(;
it!=InputEnd && pit!=TestEnd;
++it,++pit)
{
if( !(Comp(*it,*pit)) )
return false;
}
return pit==TestEnd;
}
//! 'Starts with' predicate
/*!
\overload
*/
template<typename Range1T, typename Range2T>
inline bool starts_with(
const Range1T& Input,
const Range2T& Test)
{
return ::boost::algorithm::starts_with(Input, Test, is_equal());
}
//! 'Starts with' predicate ( case insensitive )
/*!
This predicate holds when the test string is a prefix of the Input.
In other words, if the input starts with the test.
Elements are compared case insensitively.
\param Input An input sequence
\param Test A test sequence
\param Loc A locale used for case insensitive comparison
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T>
inline bool istarts_with(
const Range1T& Input,
const Range2T& Test,
const std::locale& Loc=std::locale())
{
return ::boost::algorithm::starts_with(Input, Test, is_iequal(Loc));
}
// ends_with predicate -----------------------------------------------//
//! 'Ends with' predicate
/*!
This predicate holds when the test string is a suffix of the Input.
In other words, if the input ends with the test.
When the optional predicate is specified, it is used for character-wise
comparison.
\param Input An input sequence
\param Test A test sequence
\param Comp An element comparison predicate
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T, typename PredicateT>
inline bool ends_with(
const Range1T& Input,
const Range2T& Test,
PredicateT Comp)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type> lit_input(::boost::as_literal(Input));
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type> lit_test(::boost::as_literal(Test));
typedef BOOST_STRING_TYPENAME
range_const_iterator<Range1T>::type Iterator1T;
typedef BOOST_STRING_TYPENAME boost::detail::
iterator_traits<Iterator1T>::iterator_category category;
return detail::
ends_with_iter_select(
::boost::begin(lit_input),
::boost::end(lit_input),
::boost::begin(lit_test),
::boost::end(lit_test),
Comp,
category());
}
//! 'Ends with' predicate
/*!
\overload
*/
template<typename Range1T, typename Range2T>
inline bool ends_with(
const Range1T& Input,
const Range2T& Test)
{
return ::boost::algorithm::ends_with(Input, Test, is_equal());
}
//! 'Ends with' predicate ( case insensitive )
/*!
This predicate holds when the test container is a suffix of the Input.
In other words, if the input ends with the test.
Elements are compared case insensitively.
\param Input An input sequence
\param Test A test sequence
\param Loc A locale used for case insensitive comparison
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T>
inline bool iends_with(
const Range1T& Input,
const Range2T& Test,
const std::locale& Loc=std::locale())
{
return ::boost::algorithm::ends_with(Input, Test, is_iequal(Loc));
}
// contains predicate -----------------------------------------------//
//! 'Contains' predicate
/*!
This predicate holds when the test container is contained in the Input.
When the optional predicate is specified, it is used for character-wise
comparison.
\param Input An input sequence
\param Test A test sequence
\param Comp An element comparison predicate
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T, typename PredicateT>
inline bool contains(
const Range1T& Input,
const Range2T& Test,
PredicateT Comp)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type> lit_input(::boost::as_literal(Input));
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type> lit_test(::boost::as_literal(Test));
if (::boost::empty(lit_test))
{
// Empty range is contained always
return true;
}
// Use the temporary variable to make VACPP happy
bool bResult=(::boost::algorithm::first_finder(lit_test,Comp)(::boost::begin(lit_input), ::boost::end(lit_input)));
return bResult;
}
//! 'Contains' predicate
/*!
\overload
*/
template<typename Range1T, typename Range2T>
inline bool contains(
const Range1T& Input,
const Range2T& Test)
{
return ::boost::algorithm::contains(Input, Test, is_equal());
}
//! 'Contains' predicate ( case insensitive )
/*!
This predicate holds when the test container is contained in the Input.
Elements are compared case insensitively.
\param Input An input sequence
\param Test A test sequence
\param Loc A locale used for case insensitive comparison
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T>
inline bool icontains(
const Range1T& Input,
const Range2T& Test,
const std::locale& Loc=std::locale())
{
return ::boost::algorithm::contains(Input, Test, is_iequal(Loc));
}
// equals predicate -----------------------------------------------//
//! 'Equals' predicate
/*!
This predicate holds when the test container is equal to the
input container i.e. all elements in both containers are same.
When the optional predicate is specified, it is used for character-wise
comparison.
\param Input An input sequence
\param Test A test sequence
\param Comp An element comparison predicate
\return The result of the test
\note This is a two-way version of \c std::equal algorithm
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T, typename PredicateT>
inline bool equals(
const Range1T& Input,
const Range2T& Test,
PredicateT Comp)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type> lit_input(::boost::as_literal(Input));
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type> lit_test(::boost::as_literal(Test));
typedef BOOST_STRING_TYPENAME
range_const_iterator<Range1T>::type Iterator1T;
typedef BOOST_STRING_TYPENAME
range_const_iterator<Range2T>::type Iterator2T;
Iterator1T InputEnd=::boost::end(lit_input);
Iterator2T TestEnd=::boost::end(lit_test);
Iterator1T it=::boost::begin(lit_input);
Iterator2T pit=::boost::begin(lit_test);
for(;
it!=InputEnd && pit!=TestEnd;
++it,++pit)
{
if( !(Comp(*it,*pit)) )
return false;
}
return (pit==TestEnd) && (it==InputEnd);
}
//! 'Equals' predicate
/*!
\overload
*/
template<typename Range1T, typename Range2T>
inline bool equals(
const Range1T& Input,
const Range2T& Test)
{
return ::boost::algorithm::equals(Input, Test, is_equal());
}
//! 'Equals' predicate ( case insensitive )
/*!
This predicate holds when the test container is equal to the
input container i.e. all elements in both containers are same.
Elements are compared case insensitively.
\param Input An input sequence
\param Test A test sequence
\param Loc A locale used for case insensitive comparison
\return The result of the test
\note This is a two-way version of \c std::equal algorithm
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T>
inline bool iequals(
const Range1T& Input,
const Range2T& Test,
const std::locale& Loc=std::locale())
{
return ::boost::algorithm::equals(Input, Test, is_iequal(Loc));
}
// lexicographical_compare predicate -----------------------------//
//! Lexicographical compare predicate
/*!
This predicate is an overload of std::lexicographical_compare
for range arguments
It check whether the first argument is lexicographically less
then the second one.
If the optional predicate is specified, it is used for character-wise
comparison
\param Arg1 First argument
\param Arg2 Second argument
\param Pred Comparison predicate
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T, typename PredicateT>
inline bool lexicographical_compare(
const Range1T& Arg1,
const Range2T& Arg2,
PredicateT Pred)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range1T>::type> lit_arg1(::boost::as_literal(Arg1));
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<Range2T>::type> lit_arg2(::boost::as_literal(Arg2));
return std::lexicographical_compare(
::boost::begin(lit_arg1),
::boost::end(lit_arg1),
::boost::begin(lit_arg2),
::boost::end(lit_arg2),
Pred);
}
//! Lexicographical compare predicate
/*!
\overload
*/
template<typename Range1T, typename Range2T>
inline bool lexicographical_compare(
const Range1T& Arg1,
const Range2T& Arg2)
{
return ::boost::algorithm::lexicographical_compare(Arg1, Arg2, is_less());
}
//! Lexicographical compare predicate (case-insensitive)
/*!
This predicate is an overload of std::lexicographical_compare
for range arguments.
It check whether the first argument is lexicographically less
then the second one.
Elements are compared case insensitively
\param Arg1 First argument
\param Arg2 Second argument
\param Loc A locale used for case insensitive comparison
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename Range1T, typename Range2T>
inline bool ilexicographical_compare(
const Range1T& Arg1,
const Range2T& Arg2,
const std::locale& Loc=std::locale())
{
return ::boost::algorithm::lexicographical_compare(Arg1, Arg2, is_iless(Loc));
}
// all predicate -----------------------------------------------//
//! 'All' predicate
/*!
This predicate holds it all its elements satisfy a given
condition, represented by the predicate.
\param Input An input sequence
\param Pred A predicate
\return The result of the test
\note This function provides the strong exception-safety guarantee
*/
template<typename RangeT, typename PredicateT>
inline bool all(
const RangeT& Input,
PredicateT Pred)
{
iterator_range<BOOST_STRING_TYPENAME range_const_iterator<RangeT>::type> lit_input(::boost::as_literal(Input));
typedef BOOST_STRING_TYPENAME
range_const_iterator<RangeT>::type Iterator1T;
Iterator1T InputEnd=::boost::end(lit_input);
for( Iterator1T It=::boost::begin(lit_input); It!=InputEnd; ++It)
{
if (!Pred(*It))
return false;
}
return true;
}
} // namespace algorithm
// pull names to the boost namespace
using algorithm::starts_with;
using algorithm::istarts_with;
using algorithm::ends_with;
using algorithm::iends_with;
using algorithm::contains;
using algorithm::icontains;
using algorithm::equals;
using algorithm::iequals;
using algorithm::all;
using algorithm::lexicographical_compare;
using algorithm::ilexicographical_compare;
} // namespace boost
#endif // BOOST_STRING_PREDICATE_HPP
| 7,656 |
570 | <reponame>langston-barrett/souffle
/*
* Souffle - A Datalog Compiler
* Copyright (c) 2020, The Souffle Developers. All rights reserved.
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file SumTypeBranches.h
*
* A wrapper/cache for calculating a mapping between branches and types that declare them.
*
***********************************************************************/
#pragma once
#include "ast/QualifiedName.h"
#include "ast/TranslationUnit.h"
#include "ast/analysis/typesystem/TypeSystem.h"
#include "souffle/utility/ContainerUtil.h"
#include <map>
#include <string>
namespace souffle::ast {
namespace analysis {
class SumTypeBranchesAnalysis : public Analysis {
public:
static constexpr const char* name = "sum-type-branches";
SumTypeBranchesAnalysis() : Analysis(name) {}
void run(const TranslationUnit& translationUnit) override;
/**
* A type can be nullptr in case of a malformed program.
*/
const Type* getType(const QualifiedName& branch) const {
if (contains(branchToType, branch)) {
return branchToType.at(branch);
} else {
return nullptr;
}
}
const AlgebraicDataType& unsafeGetType(const QualifiedName& branch) const {
return *as<AlgebraicDataType>(branchToType.at(branch));
}
private:
std::map<QualifiedName, const Type*> branchToType;
};
} // namespace analysis
} // namespace souffle::ast
| 545 |
9,782 | <reponame>sreekanth370/presto<gh_stars>1000+
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.rcfile;
import io.airlift.slice.Slice;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.function.Supplier;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
public interface RcFileCompressor
{
CompressedSliceOutput createCompressedSliceOutput(int minChunkSize, int maxChunkSize);
// This specialized SliceOutput has direct access buffered output slices to
// report buffer sizes and to get he final output. Additionally, a new
// CompressedSliceOutput can be created that reuses the underlying output
// buffer
final class CompressedSliceOutput
extends BufferedOutputStreamSliceOutput
{
private final ChunkedSliceOutput bufferedOutput;
private final Supplier<CompressedSliceOutput> resetFactory;
private final Runnable onDestroy;
private boolean closed;
private boolean destroyed;
/**
* @param compressionStream the compressed output stream to delegate to
* @param bufferedOutput the output for the compressionStream
* @param resetFactory the function to create a new CompressedSliceOutput that reuses the bufferedOutput
* @param onDestroy used to cleanup the compression when done
*/
public CompressedSliceOutput(OutputStream compressionStream, ChunkedSliceOutput bufferedOutput, Supplier<CompressedSliceOutput> resetFactory, Runnable onDestroy)
{
super(compressionStream);
this.bufferedOutput = requireNonNull(bufferedOutput, "bufferedOutput is null");
this.resetFactory = requireNonNull(resetFactory, "resetFactory is null");
this.onDestroy = requireNonNull(onDestroy, "onDestroy is null");
}
@Override
public long getRetainedSize()
{
return super.getRetainedSize() + bufferedOutput.getRetainedSize();
}
public int getCompressedSize()
{
checkState(closed, "Stream has not been closed");
checkState(!destroyed, "Stream has been destroyed");
return bufferedOutput.size();
}
public List<Slice> getCompressedSlices()
{
checkState(closed, "Stream has not been closed");
checkState(!destroyed, "Stream has been destroyed");
return bufferedOutput.getSlices();
}
public CompressedSliceOutput createRecycledCompressedSliceOutput()
{
checkState(closed, "Stream has not been closed");
checkState(!destroyed, "Stream has been destroyed");
destroyed = true;
return resetFactory.get();
}
@Override
public void close()
throws IOException
{
if (!closed) {
closed = true;
super.close();
}
}
public void destroy()
throws IOException
{
if (!destroyed) {
destroyed = true;
try {
close();
}
finally {
onDestroy.run();
}
}
}
}
}
| 1,535 |
460 | /*
Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#ifndef _WEBSECURITYORIGIN_H_
#define _WEBSECURITYORIGIN_H_
#include <QtCore/qurl.h>
#include <QtCore/qshareddata.h>
#include "qwebkitglobal.h"
namespace WebCore {
class SecurityOrigin;
class ChromeClientQt;
}
class QWebSecurityOriginPrivate;
class QWebDatabase;
class QWebFrame;
class QWEBKIT_EXPORT QWebSecurityOrigin {
public:
static QList<QWebSecurityOrigin> allOrigins();
static void addLocalScheme(const QString& scheme);
static void removeLocalScheme(const QString& scheme);
static QStringList localSchemes();
~QWebSecurityOrigin();
QString scheme() const;
QString host() const;
int port() const;
qint64 databaseUsage() const;
qint64 databaseQuota() const;
void setDatabaseQuota(qint64 quota);
QList<QWebDatabase> databases() const;
QWebSecurityOrigin(const QWebSecurityOrigin& other);
QWebSecurityOrigin &operator=(const QWebSecurityOrigin& other);
private:
friend class QWebDatabase;
friend class QWebFrame;
friend class WebCore::ChromeClientQt;
QWebSecurityOrigin(QWebSecurityOriginPrivate* priv);
private:
QExplicitlySharedDataPointer<QWebSecurityOriginPrivate> d;
};
#endif
| 730 |
5,856 | <filename>voltron/plugins/view/command.py
import logging
import pygments
from pygments.lexers import get_lexer_by_name
from voltron.view import *
from voltron.plugin import *
from voltron.api import *
log = logging.getLogger('view')
class CommandView (TerminalView):
@classmethod
def configure_subparser(cls, subparsers):
sp = subparsers.add_parser('command', aliases=('c', 'cmd'),
help='run a command each time the debugger host stops')
VoltronView.add_generic_arguments(sp)
sp.add_argument('command', action='store', help='command to run')
sp.add_argument('--lexer', '-l', action='store',
help='apply a Pygments lexer to the command output (e.g. "c")',
default=None)
sp.set_defaults(func=CommandView)
def build_requests(self):
return [api_request('command', block=self.block, command=self.args.command)]
def render(self, results):
[res] = results
# Set up header and error message if applicable
self.title = '[cmd:' + self.args.command + ']'
if res and res.is_success:
if get_lexer_by_name and self.args.lexer:
try:
lexer = get_lexer_by_name(self.args.lexer, stripall=True)
self.body = pygments.highlight(res.output, lexer, pygments.formatters.TerminalFormatter())
except Exception as e:
log.warning('Failed to highlight view contents: ' + repr(e))
self.body = res.output
else:
self.body = res.output
else:
log.error("Error executing command: {}".format(res.message))
self.body = self.colour(res.message, 'red')
# Call parent's render method
super(CommandView, self).render(results)
class CommandViewPlugin(ViewPlugin):
plugin_type = 'view'
name = 'command'
view_class = CommandView
| 873 |
337 | package com.edotassi.amazmod.event;
import com.huami.watch.transport.DataBundle;
import amazmod.com.transport.data.BatteryData;
public class BatteryStatus {
private BatteryData batteryData;
public BatteryStatus(DataBundle dataBundle) {
batteryData = BatteryData.fromDataBundle(dataBundle);
}
public BatteryData getBatteryData() {
return batteryData;
}
}
| 138 |
2,904 | <reponame>EgorKraevTransferwise/dowhy<filename>dowhy/causal_identifiers/id_identifier.py
import numpy as np
import pandas as pd
import networkx as nx
from dowhy.utils.ordered_set import OrderedSet
from dowhy.utils.graph_operations import find_c_components, induced_graph, find_ancestor
from dowhy.causal_identifier import CausalIdentifier
from dowhy.utils.api import parse_state
class IDExpression:
"""
Class for storing a causal estimand, as a result of the identification step using the ID algorithm.
The object stores a list of estimators(self._product) whose porduct must be obtained and a list of variables (self._sum) over which the product must be marginalized.
"""
def __init__(self):
self._product = []
self._sum = []
def add_product(self, element):
'''
Add an estimator to the list of product.
:param element: Estimator to append to the product list.
'''
self._product.append(element)
def add_sum(self, element):
'''
Add variables to the list.
:param element: Set of variables to append to the list self._sum.
'''
for el in element:
self._sum.append(el)
def get_val(self, return_type):
"""
Get either the list of estimators (for product) or list of variables (for the marginalization).
:param return_type: "prod" to return the list of estimators or "sum" to return the list of variables.
"""
if return_type=="prod":
return self._product
elif return_type=="sum":
return self._sum
else:
raise Exception("Provide correct return type.")
def _print_estimator(self, prefix, estimator=None, start=False):
'''
Print the IDExpression object.
'''
if estimator is None:
return None
string = ""
if isinstance(estimator, IDExpression):
s = True if len(estimator.get_val(return_type="sum"))>0 else False
if s:
sum_vars = "{" + ",".join(estimator.get_val(return_type="sum")) + "}"
string += prefix + "Sum over " + sum_vars + ":\n"
prefix += "\t"
for expression in estimator.get_val(return_type='prod'):
add_string = self._print_estimator(prefix, expression)
if add_string is None:
return None
else:
string += add_string
else:
outcome_vars = list(estimator['outcome_vars'])
condition_vars = list(estimator['condition_vars'])
string += prefix + "Predictor: P(" + ",".join(outcome_vars)
if len(condition_vars)>0:
string += "|" + ",".join(condition_vars)
string += ")\n"
if start:
string = string[:-1]
return string
def __str__(self):
string = self._print_estimator(prefix="", estimator=self, start=True)
if string is None:
return "The graph is not identifiable."
else:
return string
class IDIdentifier(CausalIdentifier):
def __init__(self, graph, estimand_type,
method_name = "default",
proceed_when_unidentifiable=None):
'''
Class to perform identification using the ID algorithm.
:param self: instance of the IDIdentifier class.
:param estimand_type: Type of estimand ("nonparametric-ate", "nonparametric-nde" or "nonparametric-nie").
:param method_name: Identification method ("id-algorithm" in this case).
:param proceed_when_unidentifiable: If True, proceed with identification even in the presence of unobserved/missing variables.
'''
super().__init__(graph, estimand_type, method_name, proceed_when_unidentifiable)
if self.estimand_type != CausalIdentifier.NONPARAMETRIC_ATE:
raise Exception("The estimand type should be 'non-parametric ate' for the ID method type.")
self._treatment_names = OrderedSet(parse_state(graph.treatment_name))
self._outcome_names = OrderedSet(parse_state(graph.outcome_name))
self._adjacency_matrix = graph.get_adjacency_matrix()
try:
self._tsort_node_names = OrderedSet(list(nx.topological_sort(graph._graph))) # topological sorting of graph nodes
except:
raise Exception("The graph must be a directed acyclic graph (DAG).")
self._node_names = OrderedSet(graph._graph.nodes)
def identify_effect(self, treatment_names=None, outcome_names=None, adjacency_matrix=None, node_names=None):
'''
Implementation of the ID algorithm.
Link - https://ftp.cs.ucla.edu/pub/stat_ser/shpitser-thesis.pdf
The pseudo code has been provided on Pg 40.
:param self: instance of the IDIdentifier class.
:param treatment_names: OrderedSet comprising names of treatment variables.
:param outcome_names:OrderedSet comprising names of outcome variables.
:param adjacency_matrix: Graph adjacency matrix.
:param node_names: OrderedSet comprising names of all nodes in the graph.
:returns: target estimand, an instance of the IDExpression class.
'''
if adjacency_matrix is None:
adjacency_matrix = self._adjacency_matrix
if treatment_names is None:
treatment_names = self._treatment_names
if outcome_names is None:
outcome_names = self._outcome_names
if node_names is None:
node_names = self._node_names
node2idx, idx2node = self._idx_node_mapping(node_names)
# Estimators list for returning after identification
estimators = IDExpression()
# Line 1
# If no action has been taken, the effect on Y is just the marginal of the observational distribution P(v) on Y.
if len(treatment_names) == 0:
identifier = IDExpression()
estimator = {}
estimator['outcome_vars'] = node_names
estimator['condition_vars'] = OrderedSet()
identifier.add_product(estimator)
identifier.add_sum(node_names.difference(outcome_names))
estimators.add_product(identifier)
return estimators
# Line 2
# If we are interested in the effect on Y, it is sufficient to restrict our attention on the parts of the model ancestral to Y.
ancestors = find_ancestor(outcome_names, node_names, adjacency_matrix, node2idx, idx2node)
if len(node_names.difference(ancestors)) != 0: # If there are elements which are not the ancestor of the outcome variables
# Modify list of valid nodes
treatment_names = treatment_names.intersection(ancestors)
node_names = node_names.intersection(ancestors)
adjacency_matrix = induced_graph(node_set=node_names, adjacency_matrix=adjacency_matrix, node2idx=node2idx)
return self.identify_effect(treatment_names=treatment_names, outcome_names=outcome_names, adjacency_matrix=adjacency_matrix, node_names=node_names)
# Line 3 - forces an action on any node where such an action would have no effect on Y – assuming we already acted on X.
# Modify adjacency matrix to obtain that corresponding to do(X)
adjacency_matrix_do_x = adjacency_matrix.copy()
for x in treatment_names:
x_idx = node2idx[x]
for i in range(len(node_names)):
adjacency_matrix_do_x[i, x_idx] = 0
ancestors = find_ancestor(outcome_names, node_names, adjacency_matrix_do_x, node2idx, idx2node)
W = node_names.difference(treatment_names).difference(ancestors)
if len(W) != 0:
return self.identify_effect(treatment_names = treatment_names.union(W), outcome_names=outcome_names, adjacency_matrix=adjacency_matrix, node_names=node_names)
# Line 4 - Decomposes the problem into a set of smaller problems using the key property of C-component factorization of causal models.
# If the entire graph is a single C-component already, further problem decomposition is impossible, and we must provide base cases.
# Modify adjacency matrix to remove treatment variables
node_names_minus_x = node_names.difference(treatment_names)
node2idx_minus_x, idx2node_minus_x = self._idx_node_mapping(node_names_minus_x)
adjacency_matrix_minus_x = induced_graph(node_set=node_names_minus_x, adjacency_matrix=adjacency_matrix, node2idx=node2idx)
c_components = find_c_components(adjacency_matrix=adjacency_matrix_minus_x, node_set=node_names_minus_x, idx2node=idx2node_minus_x)
if len(c_components)>1:
identifier = IDExpression()
sum_over_set = node_names.difference(outcome_names.union(treatment_names))
for component in c_components:
expressions = self.identify_effect(treatment_names=node_names.difference(component), outcome_names=OrderedSet(list(component)), adjacency_matrix=adjacency_matrix, node_names=node_names)
for expression in expressions.get_val(return_type="prod"):
identifier.add_product(expression)
identifier.add_sum(sum_over_set)
estimators.add_product(identifier)
return estimators
# Line 5 - The algorithms fails due to the presence of a hedge - the graph G, and a subgraph S that does not contain any X nodes.
S = c_components[0]
c_components_G = find_c_components(adjacency_matrix=adjacency_matrix, node_set=node_names, idx2node=idx2node)
if len(c_components_G)==1 and c_components_G[0] == node_names:
return None
# Line 6 - If there are no bidirected arcs from X to the other nodes in the current subproblem under consideration, then we can replace acting on X by conditioning, and thus solve the subproblem.
if S in c_components_G:
sum_over_set = S.difference(outcome_names)
prev_nodes = []
for node in self._tsort_node_names:
if node in S:
identifier = IDExpression()
estimator = {}
estimator['outcome_vars'] = OrderedSet([node])
estimator['condition_vars'] = OrderedSet(prev_nodes)
identifier.add_product(estimator)
identifier.add_sum(sum_over_set)
estimators.add_product(identifier)
prev_nodes.append(node)
return estimators
# Line 7 - This is the most complicated case in the algorithm. Explain in the second last paragraph on Pg 41 of the link provided in the docstring above.
for component in c_components_G:
C = S.difference(component)
if C.is_empty() is None:
return self.identify_effect(treatment_names=treatment_names.intersection(component), outcome_names=outcome_names, adjacency_matrix=induced_graph(node_set=component, adjacency_matrix=adjacency_matrix,node2idx=node2idx), node_names=node_names)
def _idx_node_mapping(self, node_names):
'''
Obtain the node name to index and index to node name mappings.
:param node_names: Name of all nodes in the graph.
:return: node to index and index to node mappings.
'''
node2idx = {}
idx2node = {}
for i, node in enumerate(node_names.get_all()):
node2idx[node] = i
idx2node[i] = node
return node2idx, idx2node | 4,943 |
368 | <reponame>AlexRogalskiy/serendipity
package org.serendipity.party.model;
import lombok.*;
import org.springframework.hateoas.RepresentationModel;
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Setter
@Getter
public class AddressModel extends RepresentationModel<AddressModel> {
private Long id;
private LocationModel location;
private String name;
private String line1;
private String line2;
private String city;
private String state;
private String postalCode;
private String country;
private String addressType;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddressModel))
return false;
AddressModel other = (AddressModel) o;
return id != 0L && id.equals(other.getId());
}
@Override
public int hashCode() {
return 31;
}
}
| 272 |
1,444 | package mage.cards.d;
import java.util.UUID;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.effects.common.ReturnFromGraveyardToHandTargetEffect;
import mage.abilities.keyword.BoastAbility;
import mage.constants.SubType;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.filter.StaticFilters;
import mage.target.common.TargetCardInYourGraveyard;
/**
*
* @author weirddan455
*/
public final class DraugrRecruiter extends CardImpl {
public DraugrRecruiter(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{B}");
this.subtype.add(SubType.ZOMBIE);
this.subtype.add(SubType.CLERIC);
this.power = new MageInt(3);
this.toughness = new MageInt(3);
// Boast — {3}{B}: Return target creature card from your graveyard to your hand.
Ability ability = new BoastAbility(new ReturnFromGraveyardToHandTargetEffect(), "{3}{B}");
ability.addTarget(new TargetCardInYourGraveyard(StaticFilters.FILTER_CARD_CREATURE_YOUR_GRAVEYARD));
this.addAbility(ability);
}
private DraugrRecruiter(final DraugrRecruiter card) {
super(card);
}
@Override
public DraugrRecruiter copy() {
return new DraugrRecruiter(this);
}
}
| 506 |
19,046 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <thread>
#include <vector>
#include <folly/container/Array.h>
#include <folly/io/async/test/RequestContextHelper.h>
#include <folly/portability/GFlags.h>
#include <folly/synchronization/test/Barrier.h>
DEFINE_int32(reps, 10, "number of reps");
DEFINE_int32(ops, 1000000, "number of operations per rep");
using namespace folly;
RequestToken token("test");
template <typename Func>
inline uint64_t run_once(int nthr, const Func& fn) {
folly::test::Barrier b1(nthr + 1);
std::vector<std::thread> thr(nthr);
for (int tid = 0; tid < nthr; ++tid) {
thr[tid] = std::thread([&, tid] {
b1.wait();
fn(tid);
});
}
b1.wait();
/* begin time measurement */
auto const tbegin = std::chrono::steady_clock::now();
/* wait for completion */
for (int i = 0; i < nthr; ++i) {
thr[i].join();
}
/* end time measurement */
auto const tend = std::chrono::steady_clock::now();
auto const dur = tend - tbegin;
return std::chrono::duration_cast<std::chrono::nanoseconds>(dur).count();
}
template <typename Func>
uint64_t runBench(int ops, int nthr, const Func& fn) {
uint64_t reps = FLAGS_reps;
uint64_t min = UINTMAX_MAX;
uint64_t max = 0;
uint64_t sum = 0;
std::vector<uint64_t> durs(reps);
for (uint64_t r = 0; r < reps; ++r) {
uint64_t dur = run_once(nthr, fn);
durs[r] = dur;
sum += dur;
min = std::min(min, dur);
max = std::max(max, dur);
// if each rep takes too long run at least 3 reps
const uint64_t minute = 60000000000UL;
if (sum > minute && r >= 2) {
reps = r + 1;
break;
}
}
const std::string ns_unit = " ns";
uint64_t avg = sum / reps;
uint64_t res = min;
uint64_t varsum = 0;
for (uint64_t r = 0; r < reps; ++r) {
auto term = int64_t(reps * durs[r]) - int64_t(sum);
varsum += term * term;
}
uint64_t dev = uint64_t(std::sqrt(varsum) * std::pow(reps, -1.5));
std::cout << " " << std::setw(4) << max / ops << ns_unit;
std::cout << " " << std::setw(4) << avg / ops << ns_unit;
std::cout << " " << std::setw(4) << dev / ops << ns_unit;
std::cout << " " << std::setw(4) << res / ops << ns_unit;
std::cout << std::endl;
return res;
}
uint64_t bench_set_clearContextData(int nthr, uint64_t ops) {
auto fn = [&](int tid) {
RequestContextScopeGuard g;
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(tid));
RequestContext::get()->clearContextData(token);
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_hasContextData(int nthr, uint64_t ops, bool hit) {
auto fn = [&](int tid) {
RequestContextScopeGuard g;
if (hit) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(tid));
}
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContext::get()->hasContextData(token);
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_getContextData(int nthr, uint64_t ops, bool hit) {
auto fn = [&](int tid) {
RequestContextScopeGuard g;
if (hit) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(tid));
}
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContext::get()->getContextData(token);
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_onSet(int nthr, uint64_t ops, bool nonempty) {
auto fn = [&](int tid) {
RequestContextScopeGuard g;
if (nonempty) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(tid));
}
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContext::get()->onSet();
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_onUnset(int nthr, uint64_t ops, bool nonempty) {
auto fn = [&](int tid) {
RequestContextScopeGuard g;
if (nonempty) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(tid));
}
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContext::get()->onUnset();
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_setContext(int nthr, uint64_t ops, bool nonempty) {
auto fn = [&](int tid) {
auto ctx = std::make_shared<RequestContext>();
if (nonempty) {
ctx->setContextData(token, std::make_unique<TestData>(1));
}
RequestContext::setContext(std::move(ctx));
ctx = std::make_shared<RequestContext>();
if (nonempty) {
ctx->setContextData(token, std::make_unique<TestData>(2));
}
for (uint64_t i = tid; i < ops; i += nthr) {
ctx = RequestContext::setContext(std::move(ctx));
}
RequestContext::setContext(nullptr);
};
return runBench(ops, nthr, fn);
}
uint64_t bench_RequestContextScopeGuard(int nthr, uint64_t ops, bool nonempty) {
auto fn = [&](int tid) {
RequestContextScopeGuard g1;
if (nonempty) {
RequestContext::get()->setContextData(
token, std::make_unique<TestData>(1));
}
auto ctx = std::make_shared<RequestContext>();
if (nonempty) {
ctx->setContextData(token, std::make_unique<TestData>(2));
}
for (uint64_t i = tid; i < ops; i += nthr) {
RequestContextScopeGuard g2(ctx);
}
};
return runBench(ops, nthr, fn);
}
uint64_t bench_ShallowCopyRequestContextScopeGuard(
int nthr, uint64_t ops, int keep, bool replace) {
auto fn = [&](int tid) {
RequestContextScopeGuard g1;
auto ctx = RequestContext::get();
for (int i = 0; i < keep; ++i) {
ctx->setContextData(
folly::to<std::string>(1000 + i), std::make_unique<TestData>(i));
}
if (replace) {
ctx->setContextData(token, std::make_unique<TestData>(1));
for (uint64_t i = tid; i < ops; i += nthr) {
ShallowCopyRequestContextScopeGuard g2(
token, std::make_unique<TestData>(2));
}
} else {
for (uint64_t i = tid; i < ops; i += nthr) {
ShallowCopyRequestContextScopeGuard g2;
}
}
};
return runBench(ops, nthr, fn);
}
void dottedLine() {
std::cout
<< "........................................................................"
<< std::endl;
}
void doubleLine() {
std::cout
<< "========================================================================"
<< std::endl;
}
constexpr auto nthr = folly::make_array<int>(1, 10);
void benches() {
doubleLine();
std::cout << std::setw(2) << FLAGS_reps << " reps of " << std::setw(8)
<< FLAGS_ops << " operations\n";
dottedLine();
std::cout << "$ numactl -N 1 $dir/request_context_benchmark\n";
doubleLine();
std::cout
<< "Test name Max time Avg time Dev time Min time"
<< std::endl;
for (int i : nthr) {
std::cout << "============================== " << std::setw(2) << i
<< " threads "
<< "==============================" << std::endl;
const uint64_t ops = FLAGS_ops;
std::cout << "hasContextData ";
bench_hasContextData(i, ops, true);
std::cout << "getContextData ";
bench_getContextData(i, ops, true);
std::cout << "onSet ";
bench_onSet(i, ops, true);
std::cout << "onUnset ";
bench_onUnset(i, ops, true);
std::cout << "setContext ";
bench_setContext(i, ops, true);
std::cout << "RequestContextScopeGuard ";
bench_RequestContextScopeGuard(i, ops, true);
std::cout << "ShallowCopyRequestC...-replace ";
bench_ShallowCopyRequestContextScopeGuard(i, ops, 0, true);
std::cout << "ShallowCopyReq...-keep&replace ";
bench_ShallowCopyRequestContextScopeGuard(i, ops, 12, true);
}
doubleLine();
}
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
benches();
}
/*
========================================================================
10 reps of 1000000 operations
........................................................................
$ numactl -N 1 $dir/request_context_benchmark
========================================================================
Test name Max time Avg time Dev time Min time
============================== 1 threads ==============================
hasContextData 7 ns 7 ns 0 ns 7 ns
getContextData 7 ns 7 ns 0 ns 7 ns
onSet 12 ns 12 ns 0 ns 12 ns
onUnset 12 ns 12 ns 0 ns 12 ns
setContext 46 ns 44 ns 1 ns 42 ns
RequestContextScopeGuard 113 ns 103 ns 3 ns 101 ns
ShallowCopyRequestC...-replace 213 ns 201 ns 5 ns 196 ns
ShallowCopyReq...-keep&replace 883 ns 835 ns 20 ns 814 ns
============================== 10 threads ==============================
hasContextData 1 ns 1 ns 0 ns 1 ns
getContextData 2 ns 1 ns 0 ns 1 ns
onSet 2 ns 2 ns 0 ns 1 ns
onUnset 2 ns 2 ns 0 ns 1 ns
setContext 11 ns 7 ns 2 ns 5 ns
RequestContextScopeGuard 22 ns 15 ns 5 ns 11 ns
ShallowCopyRequestC...-replace 48 ns 30 ns 11 ns 21 ns
ShallowCopyReq...-keep&replace 98 ns 93 ns 2 ns 91 ns
========================================================================
*/
| 4,418 |
407 | package com.alibaba.smart.framework.engine.common.expression.evaluator;
import java.util.Map;
/**
* Created by 高海军 帝奇 74394 on 2017 February 22:17.
*/
public class CustomExpressionEvaluator implements ExpressionEvaluator {
@Override
public Object eval(String expression, Map<String, Object> vars,boolean needCached) {
return true;
}
}
| 128 |
334 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.service.server.permission;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.service.permission.PermissionService;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectReference;
import org.spongepowered.common.bridge.authlib.GameProfileHolderBridge;
import org.spongepowered.common.bridge.permissions.SubjectBridge;
import java.util.Objects;
/**
* {@link SubjectBridge} helper class to apply the appropriate subject to the
* mixin.
*/
public final class SubjectHelper {
private SubjectHelper() {
}
public static void applySubject(final SubjectBridge ref, final String subjectCollectionIdentifier) {
Objects.requireNonNull(ref);
final PermissionService service = Sponge.server().serviceProvider().permissionService();
final SubjectReference subject;
// check if we're using the native Sponge impl
// we can skip some unnecessary instance creation this way.
if (service instanceof SpongePermissionService) {
final SpongePermissionService serv = (SpongePermissionService) service;
final SpongeSubjectCollection collection = serv.get(subjectCollectionIdentifier);
if (ref instanceof GameProfileHolderBridge && collection instanceof UserCollection) {
// GameProfile is already resolved, use it directly
subject = ((UserCollection) collection).get(((GameProfileHolderBridge) ref).bridge$getGameProfile()).asSubjectReference();
} else {
subject = collection.get(((Subject) ref).identifier()).asSubjectReference();
}
} else {
// build a new subject reference using the permission service
// this doesn't actually load the subject, so it will be lazily init'd when needed.
subject = service.newSubjectReference(subjectCollectionIdentifier, ((Subject) ref).identifier());
}
ref.bridge$setSubject(subject);
}
}
| 989 |
389 | <gh_stars>100-1000
//
// QSBlocks.h
// Q Branch Standard Kit
//
// Created by <NAME> on 10/22/13.
// Copyright (c) 2013 Q Branch LLC. All rights reserved.
//
@import Foundation;
#import "QSPlatform.h"
typedef void (^QSVoidBlock)(void);
typedef QSVoidBlock QSVoidCompletionBlock;
typedef BOOL (^QSBoolBlock)(void);
typedef void (^QSFetchResultsBlock)(NSArray *fetchedObjects);
typedef void (^QSDataResultBlock)(NSData *d);
typedef void (^QSObjectResultBlock)(id obj);
typedef void (^QSBoolResultBlock)(BOOL flag);
/*Images*/
typedef void (^QSImageResultBlock)(QS_IMAGE *image);
typedef QS_IMAGE *(^QSImageRenderBlock)(QS_IMAGE *imageToRender);
/*Calls on main thread. Ignores if nil.*/
void QSCallCompletionBlock(QSVoidCompletionBlock completion);
void QSCallBlockWithParameter(QSObjectResultBlock block, id obj);
void QSCallFetchResultsBlock(QSFetchResultsBlock fetchResultsBlock, NSArray *fetchedObjects);
| 339 |
832 | <reponame>tmexcept/android-lite-http
package com.litesuits.http.exception.handler;
import com.litesuits.http.data.HttpStatus;
import com.litesuits.http.exception.*;
/**
* Handle Response on UI Thread
*
* @author MaTianyu
* 2014-2-26下午9:02:09
*/
public abstract class HttpExceptionHandler {
public HttpExceptionHandler handleException(HttpException e) {
if (e != null) {
if (e instanceof HttpClientException) {
HttpClientException ce = ((HttpClientException) e);
onClientException(ce, ce.getExceptionType());
} else if (e instanceof HttpNetException) {
HttpNetException ne = ((HttpNetException) e);
onNetException(ne, ne.getExceptionType());
} else if (e instanceof HttpServerException) {
HttpServerException se = ((HttpServerException) e);
onServerException(se, se.getExceptionType(), se.getHttpStatus());
} else {
HttpClientException ce = new HttpClientException(e);
onClientException(ce, ce.getExceptionType());
}
e.setHandled(true);
}
return this;
}
/**
* 比如 URL为空,构建参数异常以及请求过程中遇到的其他客户端异常。
*
* @param e
*/
protected abstract void onClientException(HttpClientException e, ClientException type);
/**
* 比如 无网络,网络不稳定,该网络类型已被禁用等。
*
* @param e
*/
protected abstract void onNetException(HttpNetException e, NetException type);
/**
* 这个时候,连接是成功的。http header已经返回,但是status code是400~599之间。
* [400-499]:因为客户端原因,服务器拒绝服务
* [500~599]:基本是服务器内部错误或者网关异常造成的
*
* @param e
*/
protected abstract void onServerException(HttpServerException e, ServerException type, HttpStatus status);
}
| 966 |
1,433 | //******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#if defined(__linux__)
#include <unistd.h>
#endif
#include <string>
#include <map>
#include <vector>
#include <memory>
#include <UnitTestHelper.h>
#include <gtest/gtest.h>
#include <HippoMocks/hippomocks.h>
#include "Configuration.h"
#include "BundleActivator.h"
#include "BundleResource.h"
#include "RCSResourceContainer.h"
#include "ResourceContainerBundleAPI.h"
#include "ResourceContainerImpl.h"
#include "RemoteResourceUnit.h"
#include "RCSResourceObject.h"
#include "RCSRemoteResourceObject.h"
#include "ResourceContainerTestSimulator.h"
using namespace std;
using namespace testing;
using namespace OIC::Service;
#define MAX_PATH 2048
string CONFIG_FILE = "ResourceContainerTestConfig.xml";
void getCurrentPath(std::string *pPath)
{
char buffer[MAX_PATH];
#if defined(__linux__)
char *strPath = NULL;
int length = readlink("/proc/self/exe", buffer, MAX_PATH - 1);
if (length != -1)
{
buffer[length] = '\0';
strPath = strrchr(buffer, '/');
if (strPath != NULL)
*strPath = '\0';
}
#endif
pPath->append(buffer);
}
template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del>
static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
auto d = static_cast<Derived *>(p.release());
return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
}
template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del>
dynamic_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
if(Derived *result = dynamic_cast<Derived *>(p.get())) {
p.release();
return std::unique_ptr<Derived, Del>(result, std::move(p.get_deleter()));
}
return std::unique_ptr<Derived, Del>(nullptr, p.get_deleter());
}
/*Fake bundle resource class for testing*/
class TestBundleResource: public BundleResource
{
public:
virtual void initAttributes() { }
virtual void handleSetAttributesRequest(RCSResourceAttributes &attr)
{
BundleResource::setAttributes(attr);
}
virtual RCSResourceAttributes &handleGetAttributesRequest()
{
return BundleResource::getAttributes();
}
};
class ResourceContainerTest: public TestWithMock
{
public:
RCSResourceContainer *m_pResourceContainer;
std::string m_strConfigPath;
protected:
void SetUp()
{
TestWithMock::SetUp();
m_pResourceContainer = RCSResourceContainer::getInstance();
getCurrentPath(&m_strConfigPath);
m_strConfigPath.append("/");
m_strConfigPath.append(CONFIG_FILE);
}
};
TEST_F(ResourceContainerTest, BundleRegisteredWhenContainerStartedWithValidConfigFile)
{
m_pResourceContainer->startContainer(m_strConfigPath);
EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
cout << "now checking for bunlde ids " << endl;
EXPECT_STREQ("oic.bundle.test",
(*m_pResourceContainer->listBundles().begin())->getID().c_str());
EXPECT_STREQ("libTestBundle.so",
(*m_pResourceContainer->listBundles().begin())->getPath().c_str());
EXPECT_STREQ("1.0.0", (*m_pResourceContainer->listBundles().begin())->getVersion().c_str());
cout << "Now stopping container." << endl;
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, BundleLoadedWhenContainerStartedWithValidConfigFile)
{
m_pResourceContainer->startContainer(m_strConfigPath);
EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
EXPECT_TRUE( firstInternal->isLoaded() );
EXPECT_NE(nullptr,
firstInternal->getBundleHandle());
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, BundleActivatedWhenContainerStartedWithValidConfigFile)
{
m_pResourceContainer->startContainer(m_strConfigPath);
EXPECT_GT(m_pResourceContainer->listBundles().size(), (unsigned int) 0);
unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
EXPECT_TRUE(firstInternal->isActivated());
EXPECT_NE(nullptr,firstInternal->getBundleActivator());
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, BundleNotRegisteredWhenContainerStartedWithInvalidConfigFile)
{
m_pResourceContainer->startContainer("invalidConfig");
EXPECT_EQ((unsigned int) 0, m_pResourceContainer->listBundles().size());
}
TEST_F(ResourceContainerTest, BundleNotRegisteredWhenContainerStartedWithEmptyConfigFile)
{
m_pResourceContainer->startContainer("");
EXPECT_EQ((unsigned int) 0, m_pResourceContainer->listBundles().size());
}
TEST_F(ResourceContainerTest, BundleUnregisteredWhenContainerStopped)
{
m_pResourceContainer->startContainer(m_strConfigPath);
m_pResourceContainer->stopContainer();
EXPECT_EQ((unsigned int) 0, m_pResourceContainer->listBundles().size());
}
TEST_F(ResourceContainerTest, BundleStoppedWithStartBundleAPI)
{
m_pResourceContainer->startContainer(m_strConfigPath);
m_pResourceContainer->stopBundle("oic.bundle.test");
unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
EXPECT_FALSE(firstInternal->isActivated());
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, BundleStartedWithStartBundleAPI)
{
m_pResourceContainer->startContainer(m_strConfigPath);
m_pResourceContainer->stopBundle("oic.bundle.test");
m_pResourceContainer->startBundle("oic.bundle.test");
unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
EXPECT_TRUE(firstInternal->isActivated());
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, AddNewSoBundleToContainer)
{
std::map<string, string> bundleParams;
std::list<std::unique_ptr<RCSBundleInfo>> bundles;
bundles = m_pResourceContainer->listBundles();
m_pResourceContainer->addBundle("oic.bundle.test", "", "libTestBundle.so", "test", bundleParams);
EXPECT_EQ(bundles.size() + 1, m_pResourceContainer->listBundles().size());
unique_ptr<RCSBundleInfo> first = std::move(*m_pResourceContainer->listBundles().begin());
unique_ptr<BundleInfoInternal> firstInternal(static_cast<BundleInfoInternal*>(first.release()));
EXPECT_TRUE(firstInternal->isLoaded());
}
TEST_F(ResourceContainerTest, RemoveSoBundleFromContainer)
{
std::map<string, string> bundleParams;
std::list<std::unique_ptr<RCSBundleInfo>> bundles;
bundles = m_pResourceContainer->listBundles();
m_pResourceContainer->removeBundle("oic.bundle.test");
EXPECT_EQ(bundles.size() - 1, m_pResourceContainer->listBundles().size());
}
TEST_F(ResourceContainerTest, AddBundleAlreadyRegistered)
{
std::map<string, string> bundleParams;
std::list<std::unique_ptr<RCSBundleInfo> > bundles;
m_pResourceContainer->addBundle("oic.bundle.test", "", "libTestBundle.so", "test", bundleParams);
bundles = m_pResourceContainer->listBundles();
m_pResourceContainer->addBundle("oic.bundle.test", "", "libTestBundle.so", "test", bundleParams);
EXPECT_EQ(bundles.size(), m_pResourceContainer->listBundles().size());
}
TEST_F(ResourceContainerTest, AddAndRemoveSoBundleResource)
{
std::list<string> resources;
std::map<string, string> resourceParams;
resourceParams["resourceType"] = "container.test";
m_pResourceContainer->startContainer(m_strConfigPath);
resources = m_pResourceContainer->listBundleResources("oic.bundle.test");
m_pResourceContainer->addResourceConfig("oic.bundle.test", "/test_resource", resourceParams);
EXPECT_EQ(resources.size() + 1,
m_pResourceContainer->listBundleResources("oic.bundle.test").size());
m_pResourceContainer->removeResourceConfig("oic.bundle.test", "/test_resource");
EXPECT_EQ(resources.size(), m_pResourceContainer->listBundleResources("oic.bundle.test").size());
m_pResourceContainer->stopContainer();
}
TEST_F(ResourceContainerTest, TryAddingSoBundleResourceToNotRegisteredBundle)
{
std::map<string, string> resourceParams;
mocks.NeverCallFunc(ResourceContainerImpl::buildResourceObject);
m_pResourceContainer->addResourceConfig("unvalidBundleId", "", resourceParams);
}
class ResourceContainerBundleAPITest: public TestWithMock
{
public:
RCSResourceObject *m_pResourceObject;
ResourceContainerBundleAPI *m_pResourceContainer;
BundleResource::Ptr m_pBundleResource;
std::string m_strConfigPath;
protected:
void SetUp()
{
TestWithMock::SetUp();
m_pResourceObject = mocks.Mock<RCSResourceObject>();
m_pResourceContainer = ResourceContainerBundleAPI::getInstance();
getCurrentPath(&m_strConfigPath);
m_strConfigPath.append("/");
m_strConfigPath.append(CONFIG_FILE);
m_pBundleResource = std::make_shared< TestBundleResource >();
m_pBundleResource->m_bundleId = "oic.bundle.test";
m_pBundleResource->m_uri = "/test_resource";
m_pBundleResource->m_resourceType = "container.test";
}
};
TEST_F(ResourceContainerBundleAPITest, ResourceServerCreatedWhenRegisterResourceCalled)
{
m_pBundleResource = std::make_shared< TestBundleResource >();
m_pBundleResource->m_bundleId = "oic.bundle.test";
m_pBundleResource->m_uri = "/test_resource/test";
m_pBundleResource->m_resourceType = "container.test";
mocks.ExpectCallFunc(ResourceContainerImpl::buildResourceObject).With(m_pBundleResource->m_uri,
m_pBundleResource->m_resourceType).Return(nullptr);
m_pResourceContainer->registerResource(m_pBundleResource);
}
TEST_F(ResourceContainerBundleAPITest, RequestHandlerForResourceServerSetWhenRegisterResourceCalled)
{
mocks.OnCallFunc(ResourceContainerImpl::buildResourceObject).Return(
RCSResourceObject::Ptr(m_pResourceObject, [](RCSResourceObject *)
{}));
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setGetRequestHandler);
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setSetRequestHandler);
m_pResourceContainer->registerResource(m_pBundleResource);
m_pResourceContainer->unregisterResource(m_pBundleResource);
}
TEST_F(ResourceContainerBundleAPITest, BundleResourceUnregisteredWhenUnregisterResourceCalled)
{
mocks.OnCallFunc(ResourceContainerImpl::buildResourceObject).Return(
RCSResourceObject::Ptr(m_pResourceObject, [](RCSResourceObject *)
{}));
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setGetRequestHandler);
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setSetRequestHandler);
m_pResourceContainer->registerResource(m_pBundleResource);
m_pResourceContainer->unregisterResource(m_pBundleResource);
EXPECT_EQ((unsigned int) 0,
((ResourceContainerImpl *)m_pResourceContainer)->listBundleResources(
m_pBundleResource->m_bundleId).size());
}
TEST_F(ResourceContainerBundleAPITest,
ServerNotifiesToObserversWhenNotificationReceivedFromResource)
{
mocks.OnCallFunc(ResourceContainerImpl::buildResourceObject).Return(
RCSResourceObject::Ptr(m_pResourceObject, [](RCSResourceObject *)
{}));
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setGetRequestHandler);
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::setSetRequestHandler);
m_pResourceContainer->registerResource(m_pBundleResource);
mocks.ExpectCall(m_pResourceObject, RCSResourceObject::notify);
m_pResourceContainer->onNotificationReceived(m_pBundleResource->m_uri);
m_pResourceContainer->unregisterResource(m_pBundleResource);
}
TEST_F(ResourceContainerBundleAPITest, BundleConfigurationParsedWithValidBundleId)
{
configInfo bundle;
map< string, string > results;
((ResourceContainerImpl *)m_pResourceContainer)->startContainer(m_strConfigPath);
m_pResourceContainer->getBundleConfiguration("oic.bundle.test", &bundle);
results = *bundle.begin();
EXPECT_STREQ("oic.bundle.test", results["id"].c_str());
EXPECT_STREQ("libTestBundle.so", results["path"].c_str());
EXPECT_STREQ("1.0.0", results["version"].c_str());
((ResourceContainerImpl *)m_pResourceContainer)->stopContainer();
}
TEST_F(ResourceContainerBundleAPITest, BundleResourceConfigurationListParsed)
{
vector< resourceInfo > resourceConfig;
resourceInfo result;
((ResourceContainerImpl *)m_pResourceContainer)->startContainer(m_strConfigPath);
m_pResourceContainer->getResourceConfiguration("oic.bundle.test", &resourceConfig);
result = *resourceConfig.begin();
EXPECT_STREQ("test_resource", result.name.c_str());
EXPECT_STREQ("container.test", result.resourceType.c_str());
((ResourceContainerImpl *)m_pResourceContainer)->stopContainer();
}
class ResourceContainerImplTest: public TestWithMock
{
public:
ResourceContainerImpl *m_pResourceContainer;
BundleInfoInternal *m_pBundleInfo;
protected:
void SetUp()
{
TestWithMock::SetUp();
m_pResourceContainer = ResourceContainerImpl::getImplInstance();
m_pBundleInfo = new BundleInfoInternal();
}
void TearDown()
{
delete m_pBundleInfo;
}
};
TEST_F(ResourceContainerImplTest, SoBundleLoadedWhenRegisteredWithRegisterBundleAPI)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath(".");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleHandle());
}
#if (JAVA_SUPPORT_TEST)
TEST_F(ResourceContainerImplTest, JavaBundleLoadedWhenRegisteredWithRegisterBundleAPIWrongPath)
{
m_pBundleInfo->setPath("wrong_path.jar");
m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setID("oic.bundle.java.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isLoaded());
}
TEST_F(ResourceContainerImplTest, JavaBundleTest)
{
m_pBundleInfo->setPath("TestBundleJava/hue-0.1-jar-with-dependencies.jar");
m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setID("oic.bundle.java.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
EXPECT_TRUE(((BundleInfoInternal *)m_pBundleInfo)->isLoaded());
m_pResourceContainer->activateBundle(m_pBundleInfo);
EXPECT_TRUE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
m_pResourceContainer->deactivateBundle(m_pBundleInfo);
EXPECT_FALSE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
}
#endif
TEST_F(ResourceContainerImplTest, BundleNotRegisteredIfBundlePathIsInvalid)
{
m_pBundleInfo->setPath("");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
EXPECT_EQ(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleHandle());
}
TEST_F(ResourceContainerImplTest, SoBundleActivatedWithValidBundleInfo)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
m_pResourceContainer->activateBundle(m_pBundleInfo);
EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
}
TEST_F(ResourceContainerImplTest, BundleNotActivatedWhenNotRegistered)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->activateBundle(m_pBundleInfo);
EXPECT_EQ(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
}
TEST_F(ResourceContainerImplTest, SoBundleActivatedWithBundleID)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
m_pResourceContainer->activateBundle(m_pBundleInfo->getID());
EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleActivator());
EXPECT_TRUE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
}
TEST_F(ResourceContainerImplTest, BundleDeactivatedWithBundleInfo)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
m_pResourceContainer->activateBundle(m_pBundleInfo);
m_pResourceContainer->deactivateBundle(m_pBundleInfo);
EXPECT_NE(nullptr, ((BundleInfoInternal *)m_pBundleInfo)->getBundleDeactivator());
EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
}
TEST_F(ResourceContainerImplTest, BundleDeactivatedWithBundleInfoJava)
{
m_pBundleInfo->setPath("TestBundle/hue-0.1-jar-with-dependencies.jar");
m_pBundleInfo->setActivatorName("org/iotivity/bundle/hue/HueBundleActivator");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setID("oic.bundle.java.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
m_pResourceContainer->activateBundle(m_pBundleInfo);
m_pResourceContainer->deactivateBundle(m_pBundleInfo);
EXPECT_FALSE(((BundleInfoInternal *) m_pBundleInfo)->isActivated());
}
TEST_F(ResourceContainerImplTest, SoBundleDeactivatedWithBundleID)
{
m_pBundleInfo->setPath("libTestBundle.so");
m_pBundleInfo->setVersion("1.0");
m_pBundleInfo->setLibraryPath("../.");
m_pBundleInfo->setActivatorName("test");
m_pBundleInfo->setID("oic.bundle.test");
m_pResourceContainer->registerBundle(m_pBundleInfo);
m_pResourceContainer->activateBundle(m_pBundleInfo);
m_pResourceContainer->deactivateBundle(m_pBundleInfo->getID());
EXPECT_FALSE(((BundleInfoInternal *)m_pBundleInfo)->isActivated());
}
/* Test for Configuration */
TEST(ConfigurationTest, ConfigFileLoadedWithValidPath)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
EXPECT_TRUE(config->isLoaded());
delete config;
}
TEST(ConfigurationTest, ConfigFileNotLoadedWithInvalidPath)
{
Configuration *config = new Configuration("InvalidPath");
EXPECT_FALSE(config->isLoaded());
delete config;
}
TEST(ConfigurationTest, BundleConfigurationListParsed)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
configInfo bundles;
map< string, string > results;
config->getConfiguredBundles(&bundles);
results = *bundles.begin();
EXPECT_STREQ("oic.bundle.test", results["id"].c_str());
EXPECT_STREQ("libTestBundle.so", results["path"].c_str());
EXPECT_STREQ("1.0.0", results["version"].c_str());
delete config;
}
TEST(ConfigurationTest, BundleConfigurationParsedWithValidBundleId)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
configInfo bundle;
map< string, string > results;
config->getBundleConfiguration("oic.bundle.test", &bundle);
results = *bundle.begin();
EXPECT_STREQ("oic.bundle.test", results["id"].c_str());
EXPECT_STREQ("libTestBundle.so", results["path"].c_str());
EXPECT_STREQ("1.0.0", results["version"].c_str());
delete config;
}
TEST(ConfigurationTest, BundleConfigurationNotParsedWithInvalidBundleId)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
configInfo bundles;
config->getBundleConfiguration("test", &bundles);
EXPECT_TRUE(bundles.empty());
delete config;
}
TEST(ConfigurationTest, BundleResourceConfigurationListParsed)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
vector< resourceInfo > resourceConfig;
resourceInfo result;
config->getResourceConfiguration("oic.bundle.test", &resourceConfig);
result = *resourceConfig.begin();
EXPECT_STREQ("test_resource", result.name.c_str());
EXPECT_STREQ("container.test", result.resourceType.c_str());
delete config;
}
TEST(ConfigurationTest, BundleResourceConfigurationNotParsedWithInvalidBundleId)
{
std::string strConfigPath;
getCurrentPath(&strConfigPath);
strConfigPath.append("/");
strConfigPath.append(CONFIG_FILE);
Configuration *config = new Configuration(strConfigPath);
configInfo bundles;
vector< resourceInfo > resourceConfig;
config->getResourceConfiguration("test", &resourceConfig);
EXPECT_TRUE(bundles.empty());
delete config;
}
namespace
{
void discoverdCB(RCSRemoteResourceObject::Ptr);
void onUpdate(RemoteResourceUnit::UPDATE_MSG, RCSRemoteResourceObject::Ptr);
}
class DiscoverResourceUnitTest: public TestWithMock
{
private:
typedef std::function<void(const std::string attributeName,
std::vector<RCSResourceAttributes::Value> values)>
UpdatedCB;
public:
ResourceContainerTestSimulator::Ptr testObject;
DiscoverResourceUnit::Ptr m_pDiscoverResourceUnit;
std::string m_bundleId;
UpdatedCB m_updatedCB;
protected:
void SetUp()
{
TestWithMock::SetUp();
testObject = std::make_shared<ResourceContainerTestSimulator>();
testObject->createResource();
m_bundleId = "/a/TempHumSensor/Container";
m_pDiscoverResourceUnit = std::make_shared< DiscoverResourceUnit >( m_bundleId );
m_updatedCB = ([](const std::string, std::vector< RCSResourceAttributes::Value >) { });
}
void TearDown()
{
m_pDiscoverResourceUnit.reset();
testObject.reset();
TestWithMock::TearDown();
}
};
TEST_F(DiscoverResourceUnitTest, startDiscover)
{
std::string type = "Resource.Container";
std::string attributeName = "TestResourceContainer";
m_pDiscoverResourceUnit->startDiscover(
DiscoverResourceUnit::DiscoverResourceInfo("", type, attributeName), m_updatedCB);
std::chrono::milliseconds interval(400);
std::this_thread::sleep_for(interval);
}
TEST_F(DiscoverResourceUnitTest, onUpdateCalled)
{
std::string type = "Resource.Container";
std::string attributeName = "TestResourceContainer";
m_pDiscoverResourceUnit->startDiscover(
DiscoverResourceUnit::DiscoverResourceInfo("", type, attributeName), m_updatedCB);
std::chrono::milliseconds interval(400);
std::this_thread::sleep_for(interval);
testObject->ChangeAttributeValue();
}
namespace
{
void onStateCB(ResourceState) { }
void onCacheCB(const RCSResourceAttributes &) { }
}
class RemoteResourceUnitTest: public TestWithMock
{
private:
typedef std::function<void(RemoteResourceUnit::UPDATE_MSG, RCSRemoteResourceObject::Ptr)>
UpdatedCBFromServer;
public:
ResourceContainerTestSimulator::Ptr testObject;
RemoteResourceUnit::Ptr m_pRemoteResourceUnit;
RCSRemoteResourceObject::Ptr m_pRCSRemoteResourceObject;
UpdatedCBFromServer m_updatedCBFromServer;
protected:
void SetUp()
{
TestWithMock::SetUp();
testObject = std::make_shared<ResourceContainerTestSimulator>();
testObject->defaultRunSimulator();
m_pRCSRemoteResourceObject = testObject->getRemoteResource();
m_updatedCBFromServer = ([](RemoteResourceUnit::UPDATE_MSG, RCSRemoteResourceObject::Ptr) {});
}
void TearDown()
{
m_pRCSRemoteResourceObject.reset();
testObject.reset();
TestWithMock::TearDown();
}
};
TEST_F(RemoteResourceUnitTest, createRemoteResourceInfo)
{
EXPECT_NE(nullptr, m_pRemoteResourceUnit->createRemoteResourceInfo(m_pRCSRemoteResourceObject,
m_updatedCBFromServer));
}
TEST_F(RemoteResourceUnitTest, getRemoteResourceObject)
{
RemoteResourceUnit::Ptr ptr = m_pRemoteResourceUnit->createRemoteResourceInfo(
m_pRCSRemoteResourceObject, m_updatedCBFromServer);
EXPECT_EQ(m_pRCSRemoteResourceObject, ptr->getRemoteResourceObject());
}
TEST_F(RemoteResourceUnitTest, getRemoteResourceUri)
{
RemoteResourceUnit::Ptr ptr = m_pRemoteResourceUnit->createRemoteResourceInfo(
m_pRCSRemoteResourceObject, m_updatedCBFromServer);
EXPECT_NE("", ptr->getRemoteResourceUri());
}
TEST_F(RemoteResourceUnitTest, startCaching)
{
RemoteResourceUnit::Ptr ptr = m_pRemoteResourceUnit->createRemoteResourceInfo(
m_pRCSRemoteResourceObject, m_updatedCBFromServer);
ptr->startCaching();
}
TEST_F(RemoteResourceUnitTest, startMonitoring)
{
RemoteResourceUnit::Ptr ptr = m_pRemoteResourceUnit->createRemoteResourceInfo(
m_pRCSRemoteResourceObject, m_updatedCBFromServer);
ptr->startMonitoring();
}
TEST_F(RemoteResourceUnitTest, onCacheCBCalled)
{
bool isCalled = false;
mocks.ExpectCallFunc(onCacheCB).Do(
[this, &isCalled](const RCSResourceAttributes &)
{
isCalled = true;
});
RemoteResourceUnit::Ptr ptr = m_pRemoteResourceUnit->createRemoteResourceInfoWithCacheCB(
m_pRCSRemoteResourceObject, m_updatedCBFromServer, onCacheCB);
ptr->startCaching();
testObject->ChangeAttributeValue();
EXPECT_TRUE(isCalled);
}
| 10,511 |
1,056 | <filename>java/maven.model/src/org/netbeans/modules/maven/model/settings/impl/SettingsImpl.java
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.maven.model.settings.impl;
import java.util.List;
import org.netbeans.modules.maven.model.settings.Mirror;
import org.netbeans.modules.maven.model.settings.ModelList;
import org.netbeans.modules.maven.model.settings.Profile;
import org.netbeans.modules.maven.model.settings.Proxy;
import org.netbeans.modules.maven.model.settings.Server;
import org.netbeans.modules.maven.model.settings.Settings;
import org.netbeans.modules.maven.model.settings.SettingsComponent;
import org.netbeans.modules.maven.model.settings.SettingsComponentVisitor;
import org.netbeans.modules.maven.model.settings.SettingsModel;
import org.netbeans.modules.maven.model.settings.StringList;
import org.netbeans.modules.maven.model.util.ModelImplUtils;
import org.w3c.dom.Element;
/**
*
* @author mkleint
*/
public class SettingsImpl extends SettingsComponentImpl implements Settings {
@SuppressWarnings("unchecked")
private static final Class<SettingsComponent>[] ORDER = new Class[] {
ProfileImpl.List.class,
MirrorImpl.List.class,
ServerImpl.List.class,
ProxyImpl.List.class,
StringListImpl.class, //active profiles
};
public SettingsImpl(SettingsModel model, Element element) {
super(model, element);
}
public SettingsImpl(SettingsModel model) {
this(model, createElementNS(model, model.getSettingsQNames().SETTINGS));
}
// attributes
@Override
public List<Profile> getProfiles() {
ModelList<Profile> childs = getChild(ProfileImpl.List.class);
if (childs != null) {
return childs.getListChildren();
}
return null;
}
@Override
public void addProfile(Profile profile) {
ModelList<Profile> childs = getChild(ProfileImpl.List.class);
if (childs == null) {
setChild(ProfileImpl.List.class,
getModel().getSettingsQNames().PROFILES.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().PROFILES.getQName()),
getClassesBefore(ORDER, ProfileImpl.List.class));
childs = getChild(ProfileImpl.List.class);
assert childs != null;
}
childs.addListChild(profile);
}
@Override
public void removeProfile(Profile profile) {
ModelList<Profile> childs = getChild(ProfileImpl.List.class);
if (childs != null) {
childs.removeListChild(profile);
}
}
@Override
public void accept(SettingsComponentVisitor visitor) {
visitor.visit(this);
}
@Override
public List<String> getActiveProfiles() {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (getModel().getSettingsQNames().ACTIVEPROFILES.getName().equals(list.getPeer().getNodeName())) {
return list.getListChildren();
}
}
return null;
}
@Override
public void addActiveProfile(String profileid) {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (getModel().getSettingsQNames().ACTIVEPROFILES.getName().equals(list.getPeer().getNodeName())) {
list.addListChild(profileid);
return;
}
}
setChild(StringListImpl.class,
getModel().getSettingsQNames().ACTIVEPROFILES.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().ACTIVEPROFILES.getQName()),
getClassesBefore(ORDER, StringListImpl.class));
lists = getChildren(StringList.class);
for (StringList list : lists) {
if (getModel().getSettingsQNames().ACTIVEPROFILES.getName().equals(list.getPeer().getNodeName())) {
list.addListChild(profileid);
return;
}
}
}
@Override
public void removeActiveProfile(String profileid) {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (getModel().getSettingsQNames().ACTIVEPROFILES.getName().equals(list.getPeer().getNodeName())) {
list.removeListChild(profileid);
return;
}
}
}
@Override
public Profile findProfileById(String id) {
assert id != null;
java.util.List<Profile> profiles = getProfiles();
if (profiles != null) {
for (Profile p : profiles) {
if (id.equals(p.getId())) {
return p;
}
}
}
return null;
}
@Override
public List<String> getPluginGroups() {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (ModelImplUtils.hasName(list, getModel().getSettingsQNames().PLUGINGROUPS.getName())) {
return list.getListChildren();
}
}
return null;
}
@Override
public void addPluginGroup(String group) {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (ModelImplUtils.hasName(list, getModel().getSettingsQNames().PLUGINGROUPS.getName())) {
list.addListChild(group);
return;
}
}
setChild(StringListImpl.class,
getModel().getSettingsQNames().PLUGINGROUPS.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().PLUGINGROUPS.getQName()),
getClassesBefore(ORDER, StringListImpl.class));
lists = getChildren(StringList.class);
for (StringList list : lists) {
if (ModelImplUtils.hasName(list, getModel().getSettingsQNames().PLUGINGROUPS.getName())) {
list.addListChild(group);
return;
}
}
}
@Override
public void removePluginGroup(String group) {
List<StringList> lists = getChildren(StringList.class);
for (StringList list : lists) {
if (ModelImplUtils.hasName(list, getModel().getSettingsQNames().PLUGINGROUPS.getName())) {
list.removeListChild(group);
return;
}
}
}
@Override
public List<Proxy> getProxies() {
ModelList<Proxy> childs = getChild(ProxyImpl.List.class);
if (childs != null) {
return childs.getListChildren();
}
return null;
}
@Override
public void addProxy(Proxy proxy) {
ModelList<Proxy> childs = getChild(ProxyImpl.List.class);
if (childs == null) {
setChild(ProxyImpl.List.class,
getModel().getSettingsQNames().PROXIES.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().PROXIES.getQName()),
getClassesBefore(ORDER, ProxyImpl.List.class));
childs = getChild(ProxyImpl.List.class);
assert childs != null;
}
childs.addListChild(proxy);
}
@Override
public void removeProxy(Proxy proxy) {
ModelList<Proxy> childs = getChild(ProxyImpl.List.class);
if (childs != null) {
childs.removeListChild(proxy);
}
}
@Override
public List<Server> getServers() {
ModelList<Server> childs = getChild(ServerImpl.List.class);
if (childs != null) {
return childs.getListChildren();
}
return null;
}
@Override
public void addServer(Server server) {
ModelList<Server> childs = getChild(ServerImpl.List.class);
if (childs == null) {
setChild(ServerImpl.List.class,
getModel().getSettingsQNames().SERVERS.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().SERVERS.getQName()),
getClassesBefore(ORDER, ServerImpl.List.class));
childs = getChild(ServerImpl.List.class);
assert childs != null;
}
childs.addListChild(server);
}
@Override
public void removeServer(Server server) {
ModelList<Server> childs = getChild(ServerImpl.List.class);
if (childs != null) {
childs.removeListChild(server);
}
}
@Override
public List<Mirror> getMirrors() {
ModelList<Mirror> childs = getChild(MirrorImpl.List.class);
if (childs != null) {
return childs.getListChildren();
}
return null;
}
@Override
public void addMirror(Mirror mirror) {
ModelList<Mirror> childs = getChild(MirrorImpl.List.class);
if (childs == null) {
setChild(MirrorImpl.List.class,
getModel().getSettingsQNames().MIRRORS.getName(),
getModel().getFactory().create(this, getModel().getSettingsQNames().MIRRORS.getQName()),
getClassesBefore(ORDER, MirrorImpl.List.class));
childs = getChild(MirrorImpl.List.class);
assert childs != null;
}
childs.addListChild(mirror);
}
@Override
public void removeMirror(Mirror mirror) {
ModelList<Mirror> childs = getChild(MirrorImpl.List.class);
if (childs != null) {
childs.removeListChild(mirror);
}
}
@Override
public Mirror findMirrorById(String id) {
assert id != null;
java.util.List<Mirror> mirrors = getMirrors();
if (mirrors != null) {
for (Mirror m : mirrors) {
if (id.equals(m.getId())) {
return m;
}
}
}
return null;
}
@Override
public String getLocalRepository() {
return getChildElementText(getModel().getSettingsQNames().LOCALREPOSITORY.getQName());
}
@Override
public void setLocalRepository(String repo) {
setChildElementText(getModel().getSettingsQNames().LOCALREPOSITORY.getName(), repo,
getModel().getSettingsQNames().LOCALREPOSITORY.getQName());
}
@Override
public Boolean isInteractiveMode() {
String str = getChildElementText(getModel().getSettingsQNames().INTERACTIVEMODE.getQName());
if (str != null) {
return Boolean.valueOf(str);
}
return null;
}
@Override
public void setInteractiveMode(Boolean interactive) {
setChildElementText(getModel().getSettingsQNames().INTERACTIVEMODE.getName(),
interactive == null ? null : interactive.toString(),
getModel().getSettingsQNames().INTERACTIVEMODE.getQName());
}
@Override
public Boolean isUsePluginRegistry() {
String str = getChildElementText(getModel().getSettingsQNames().USEPLUGINREGISTRY.getQName());
if (str != null) {
return Boolean.valueOf(str);
}
return null;
}
@Override
public void setUsePluginRegistry(Boolean use) {
setChildElementText(getModel().getSettingsQNames().USEPLUGINREGISTRY.getName(),
use == null ? null : use.toString(),
getModel().getSettingsQNames().USEPLUGINREGISTRY.getQName());
}
@Override
public Boolean isOffline() {
String str = getChildElementText(getModel().getSettingsQNames().OFFLINE.getQName());
if (str != null) {
return Boolean.valueOf(str);
}
return null;
}
@Override
public void setOffline(Boolean offline) {
setChildElementText(getModel().getSettingsQNames().OFFLINE.getName(),
offline == null ? null : offline.toString(),
getModel().getSettingsQNames().OFFLINE.getQName());
}
}
| 5,510 |
493 | <reponame>SiddGururani/MUSI8903_Assignment_2
#ifndef UNITTEST_COMPOSITETESTREPORTER_H
#define UNITTEST_COMPOSITETESTREPORTER_H
#include "TestReporter.h"
namespace UnitTest {
class UNITTEST_LINKAGE CompositeTestReporter : public TestReporter
{
public:
CompositeTestReporter();
int GetReporterCount() const;
bool AddReporter(TestReporter* reporter);
bool RemoveReporter(TestReporter* reporter);
virtual void ReportTestStart(TestDetails const& test);
virtual void ReportFailure(TestDetails const& test, char const* failure);
virtual void ReportTestFinish(TestDetails const& test, float secondsElapsed);
virtual void ReportSummary(int totalTestCount, int failedTestCount, int failureCount, float secondsElapsed);
private:
enum { kMaxReporters = 16 };
TestReporter* m_reporters[kMaxReporters];
int m_reporterCount;
// revoked
CompositeTestReporter(const CompositeTestReporter&);
CompositeTestReporter& operator =(const CompositeTestReporter&);
};
}
#endif
| 325 |
5,349 | #!/usr/bin/env python3 -u
# -*- coding: utf-8 -*-
# copyright: sktime developers, BSD-3-Clause License (see LICENSE file)
"""Implements transformers raise time series to user provided exponent."""
__author__ = ["<NAME>"]
__all__ = ["ExponentTransformer", "SqrtTransformer"]
import numpy as np
import pandas as pd
from sktime.transformations.base import _SeriesToSeriesTransformer
from sktime.utils.validation.series import check_series
class ExponentTransformer(_SeriesToSeriesTransformer):
"""Apply exponent transformation to a timeseries.
Transformation raises input series to the `power` provided. By default,
when offset="auto", a series with negative values is shifted prior to the
exponentiation to avoid potential errors of applying certain fractional
exponents to negative values.
Parameters
----------
power : int or float, default=0.5
The power to raise the input timeseries to.
offset : "auto", int or float, default="auto"
Offset to be added to the input timeseries prior to raising
the timeseries to the given `power`. If "auto" the series is checked to
determine if it contains negative values. If negative values are found
then the offset will be equal to the absolute value of the most negative
value. If not negative values are present the offset is set to zero.
If an integer or float value is supplied it will be used as the offset.
Attributes
----------
power : int or float
User supplied power.
offset : int or float
User supplied offset value.
See Also
--------
BoxCoxTransformer :
Applies Box-Cox power transformation. Can help normalize data and
compress variance of the series.
LogTransformer :
Transformer input data using natural log. Can help normalize data and
compress variance of the series.
sktime.transformations.series.exponent.SqrtTransformer :
Transform input data by taking its square root. Can help compress
variance of input series.
Notes
-----
For an input series `Z` the exponent transformation is defined as
:math:`(Z + offset)^{power}`.
Examples
--------
>>> from sktime.transformations.series.exponent import ExponentTransformer
>>> from sktime.datasets import load_airline
>>> y = load_airline()
>>> transformer = ExponentTransformer()
>>> y_transform = transformer.fit_transform(y)
"""
_tags = {
"fit-in-transform": False,
"transform-returns-same-time-index": True,
"univariate-only": False,
}
def __init__(self, power=0.5, offset="auto"):
self.power = power
self.offset = offset
self._offset_value = None
super(ExponentTransformer, self).__init__()
def _fit(self, Z, X=None):
"""Logic used by fit method on `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
A time series to apply the transformation on.
Returns
-------
self
"""
if not isinstance(self.power, (int, float)):
raise ValueError(
f"Expected `power` to be int or float, but found {type(self.power)}."
)
if self.offset == "auto":
if isinstance(Z, pd.Series):
min_values = Z.min()
else:
min_values = Z.min(axis=0).values.reshape(1, -1)
self._offset_value = np.where(min_values < 0, np.abs(min_values), 0)
elif isinstance(self.offset, (int, float)):
self._offset_value = self.offset
else:
raise ValueError(
f"Expected `offset` to be int or float, but found {type(self.offset)}."
)
return self
def _transform(self, Z, X=None):
"""Logic used by `transform` to apply transformation to `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
The timeseries to be transformed.
Returns
-------
Zt : pd.Series or pd.DataFrame
Transformed timeseries.
"""
Zt = Z.copy()
Zt = np.power(Zt + self._offset_value, self.power)
return Zt
def _inverse_transform(self, Z, X=None):
"""Logic used by `inverse_transform` to reverse transformation on `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
A time series to apply reverse the transformation on.
Returns
-------
Z_inv : pd.Series or pd.DataFrame
The reconstructed timeseries after the transformation has been reversed.
"""
Z_inv = Z.copy()
Z_inv = np.power(Z_inv, 1.0 / self.power) - self._offset_value
return Z_inv
def fit(self, Z, X=None):
"""Fit the transformation on input series `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
A time series to apply the transformation on.
Returns
-------
self
"""
Z = check_series(Z)
self._fit(Z, X=X)
self._is_fitted = True
return self
def transform(self, Z, X=None):
"""Return transformed version of input series `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
A time series to apply the transformation on.
Returns
-------
Zt : pd.Series or pd.DataFrame
Transformed version of input series `Z`.
"""
self.check_is_fitted()
Z = check_series(Z)
Zt = self._transform(Z, X=X)
return Zt
def inverse_transform(self, Z, X=None):
"""Reverse transformation on input series `Z`.
Parameters
----------
Z : pd.Series or pd.DataFrame
A time series to reverse the transformation on.
Returns
-------
Z_inv : pd.Series or pd.DataFrame
The reconstructed timeseries after the transformation has been reversed.
"""
self.check_is_fitted()
Z = check_series(Z)
Z_inv = self._inverse_transform(Z, X=X)
return Z_inv
class SqrtTransformer(ExponentTransformer):
"""Apply square root transformation to a timeseries.
Transformation take the square root of the input series. By default,
when offset="auto", a series with negative values is shifted prior to the
exponentiation to avoid potential errors of applying square root
transformation to negative values.
Parameters
----------
offset : "auto", int or float, default="auto"
Offset to be added to the input timeseries prior to raising
the timeseries to the given `power`. If "auto" the series is checked to
determine if it contains negative values. If negative values are found
then the offset will be equal to the absolute value of the most negative
value. If not negative values are present the offset is set to zero.
If an integer or float value is supplied it will be used as the offset.
Attributes
----------
offset : int or float
User supplied offset value.
See Also
--------
BoxCoxTransformer :
Applies Box-Cox power transformation. Can help normalize data and
compress variance of the series.
LogTransformer :
Transformer input data using natural log. Can help normalize data and
compress variance of the series.
sktime.transformations.series.exponent.ExponentTransformer :
Transform input data by raising it to an exponent. Can help compress
variance of series if a fractional exponent is supplied.
Notes
-----
For an input series `Z` the square root transformation is defined as
:math:`(Z + offset)^{0.5}`.
Examples
--------
>>> from sktime.transformations.series.exponent import SqrtTransformer
>>> from sktime.datasets import load_airline
>>> y = load_airline()
>>> transformer = SqrtTransformer()
>>> y_transform = transformer.fit_transform(y)
"""
_tags = {
"fit-in-transform": False,
"transform-returns-same-time-index": True,
"univariate-only": False,
}
def __init__(self, offset="auto"):
super().__init__(power=0.5, offset=offset)
| 3,237 |
432 | <gh_stars>100-1000
package us.parr.bookish.model;
public class LineBreak extends OutputModelObject {
}
| 34 |
331 | /*
* Author <NAME>
* GitHub https://github.com/rurtle
*
* Description Given a list with consecutive duplicates, remove those
* duplicate characters and put them in a separate list.
* Linked list based implementation for efficient storage space
* utilization.
*
* Note Spaces need to be replaced with connecting characters (such as
* _,*,/,\,& etc) in the input string for proper functioning of this
* code.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAX_STRLEN 256
/* List node data structure */
typedef struct l_node {
int data;
struct l_node *next;
} node;
/*
* @brief Prints the state of the list
*/
void print_list(node *head)
{
node *tmp = head;
while (tmp)
{
printf("%c", tmp->data);
tmp = tmp->next;
}
}
/*
* @brief Adds a node at the end of the list
*/
node *add_node(node *head, int data)
{
node *tmp;
if (head == NULL)
{
head = malloc(sizeof(node));
assert(head != NULL);
head->data = data;
head->next = NULL;
}
else
{
tmp = head;
while (tmp->next)
tmp = tmp->next;
tmp->next = malloc(sizeof(node));
assert(tmp->next != NULL);
tmp = tmp->next;
tmp->data = data;
tmp->next = NULL;
}
return head;
}
/*
* @brief Removes duplicates from the list & puts those chars into a
* different list
*/
void remove_duplicates(node *head, node **aux)
{
node *curr = head;
node *tmp;
while (curr->next != NULL)
{
if (curr->data == curr->next->data)
{
tmp = curr->next;
curr->next = tmp->next;
*aux = add_node(*aux, tmp->data);
free(tmp);
}
else
curr = curr->next;
}
}
/*
* Driver function
*/
int main(int argc, char *argv[])
{
node *head = NULL;
node *aux = NULL;
char str[MAX_STRLEN];
int len = 0;
unsigned short i = 0;
/* Enter the string */
printf("Input string: ");
scanf("%s", str);
len = strlen(str);
/* Populate the list */
for (; i < len; i++)
head = add_node(head, str[i]);
/* Remove duplicates & put them in a separate list */
remove_duplicates(head, &aux);
/* Print the two lists after removing duplicates */
print_list(head);
printf(" ");
print_list(aux);
printf("\n");
return 0;
}
| 857 |
575 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_COMMAND_BUFFER_SERVICE_SURFACE_TEXTURE_GL_OWNER_H_
#define GPU_COMMAND_BUFFER_SERVICE_SURFACE_TEXTURE_GL_OWNER_H_
#include "base/threading/thread_checker.h"
#include "gpu/command_buffer/service/texture_owner.h"
#include "gpu/gpu_export.h"
#include "ui/gl/android/surface_texture.h"
namespace base {
namespace android {
class ScopedHardwareBufferFenceSync;
} // namespace android
} // namespace base
namespace gpu {
// This class wraps the Surface Texture usage. It is used to create a surface
// texture attached to a new texture of the current platform GL context. The
// surface handle of the SurfaceTexture is attached to the decoded media
// frames. Media frames can update the attached surface handle with image data.
// This class helps to update the attached texture using that image data
// present in the surface.
class GPU_GLES2_EXPORT SurfaceTextureGLOwner : public TextureOwner {
public:
gl::GLContext* GetContext() const override;
gl::GLSurface* GetSurface() const override;
void SetFrameAvailableCallback(
const base::RepeatingClosure& frame_available_cb) override;
gl::ScopedJavaSurface CreateJavaSurface() const override;
void UpdateTexImage() override;
void EnsureTexImageBound() override;
void ReleaseBackBuffers() override;
std::unique_ptr<base::android::ScopedHardwareBufferFenceSync>
GetAHardwareBuffer() override;
bool GetCodedSizeAndVisibleRect(gfx::Size rotated_visible_size,
gfx::Size* coded_size,
gfx::Rect* visible_rect) override;
void RunWhenBufferIsAvailable(base::OnceClosure callback) override;
protected:
void OnTextureDestroyed(gles2::AbstractTexture*) override;
private:
friend class TextureOwner;
friend class SurfaceTextureTransformTest;
SurfaceTextureGLOwner(std::unique_ptr<gles2::AbstractTexture> texture);
~SurfaceTextureGLOwner() override;
static bool DecomposeTransform(float matrix[16],
gfx::Size rotated_visible_size,
gfx::Size* coded_size,
gfx::Rect* visible_rect);
scoped_refptr<gl::SurfaceTexture> surface_texture_;
// The context and surface that were used to create |surface_texture_|.
scoped_refptr<gl::GLContext> context_;
scoped_refptr<gl::GLSurface> surface_;
// To ensure that SetFrameAvailableCallback() is called only once.
bool is_frame_available_callback_set_ = false;
THREAD_CHECKER(thread_checker_);
DISALLOW_COPY_AND_ASSIGN(SurfaceTextureGLOwner);
};
} // namespace gpu
#endif // GPU_COMMAND_BUFFER_SERVICE_SURFACE_TEXTURE_GL_OWNER_H_
| 964 |
826 | package io.eventuate.examples.tram.sagas.ordersandcustomers.orders.domain;
public enum OrderState { PENDING, APPROVED, REJECTED }
| 45 |
3,442 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.plugin.generalconfig;
import net.java.sip.communicator.service.resources.*;
import org.jitsi.service.resources.*;
/**
* The <tt>Resources</tt> class manages the access to the internationalization
* properties files and the image resources used in this plugin.
*
* @author <NAME>
*/
public class Resources
{
private static ResourceManagementService resourcesService;
/**
* Returns an internationalized string corresponding to the given key.
* @param key The key of the string.
* @return An internationalized string corresponding to the given key.
*/
public static String getString(String key)
{
return getResources().getI18NString(key);
}
/**
* Returns an internationalized string corresponding to the given key.
* @param key The key of the string.
* @param params parameters for I18.
* @return An internationalized string corresponding to the given key.
*/
public static String getString(String key, String[] params)
{
return getResources().getI18NString(key, params);
}
/**
* Returns an application property string corresponding to the given key.
* @param key The key of the string.
* @return A string corresponding to the given key.
*/
public static String getSettingsString(String key)
{
return getResources().getSettingsString(key);
}
/**
* Loads an image from a given image identifier.
* @param imageId The identifier of the image.
* @return The image for the given identifier.
*/
public static byte[] getImage(String imageId)
{
return getResources().getImageInBytes(imageId);
}
/**
* Returns the <tt>ResourceManagementService</tt>.
*
* @return the <tt>ResourceManagementService</tt>.
*/
public static ResourceManagementService getResources()
{
if (resourcesService == null)
resourcesService =
ResourceManagementServiceUtils
.getService(GeneralConfigPluginActivator.bundleContext);
return resourcesService;
}
}
| 893 |
487 | <gh_stars>100-1000
import os
import sys
import glob
import imagestoosm.config as osmcfg
import xml.etree.ElementTree as ET
import QuadKey.quadkey as quadkey
import shapely.geometry as geometry
import matplotlib.pyplot as plt
import skimage.io
import shutil
def _find_getch():
try:
import termios
except ImportError:
# Non-POSIX. Return msvcrt's (Windows') getch.
import msvcrt
return msvcrt.getch
# POSIX system. Create and return a getch that manipulates the tty.
import sys, tty
def _getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
return _getch
getch = _find_getch()
addDirectory = os.path.join( "anomaly","add","*.osm")
anomalyStatusFile = os.path.join( "anomaly","status.csv")
# read in OSM files, convert to pixels z18, make them shapely polygons
newWays = {}
for osmFileName in glob.glob(addDirectory):
(path,filename) = os.path.split(osmFileName);
wayNumber = os.path.splitext(filename)[0]
newEntry = {
"imageName" : os.path.join( path,str(wayNumber) + ".jpg") ,
"osmFile" : osmFileName,
"tags" : {},
"status" : ""
}
tree = ET.parse(osmFileName)
root = tree.getroot()
for tag in root.findall('./way/tag'):
key = tag.attrib["k"]
val = tag.attrib["v"]
newEntry['tags'][key] = val
pts =[]
for node in root.iter('node'):
pt = ( float(node.attrib['lat']),float(node.attrib['lon']))
pixel = quadkey.TileSystem.geo_to_pixel(pt,osmcfg.tileZoom)
pts.append(pixel)
if ( len(pts ) > 2 ):
newEntry["geometry"] = geometry.Polygon(pts)
#print(newEntry )
newWays[osmFileName] = newEntry
# read in review file, file status (accepted or rejected), path to osm
if ( os.path.exists(anomalyStatusFile)):
with open(anomalyStatusFile,"rt",encoding="ascii") as f:
for line in f:
(status,osmFileName) = line.split(',')
osmFileName = osmFileName.strip()
newWays[osmFileName]['status'] = status
fig = plt.figure()
for wayKey in sorted(newWays):
# if reviewed skip
way = newWays[wayKey]
if ( len(way['status']) == 0 ) :
# for each way, check for overlap, same tags, add to review cluster, handle more ways than maxSubPlots
subPlotCols = 2
subPlotRows = 2
maxSubPlots = subPlotCols*subPlotRows
reviewSet = [way]
for otherKey in sorted(newWays):
other = newWays[otherKey]
if ( other != way and len(other['status']) == 0 and way['tags'] == other['tags'] and other['geometry'].intersects( way['geometry'])):
reviewSet.append(other)
for wayIndex in range(len(reviewSet)):
other = reviewSet[wayIndex]
other['status'] = 'rejected'
acceptedWay = {}
viewSet = []
for wayIndex in range(len(reviewSet)):
viewSet.append(reviewSet[wayIndex])
if ( len(viewSet) == maxSubPlots or wayIndex+1 >= len(reviewSet)):
for plotIndex in range(maxSubPlots):
sb = fig.add_subplot(subPlotRows,subPlotCols,plotIndex+1)
sb.cla()
for wayIndex in range(len(viewSet)):
fig.add_subplot(subPlotRows,subPlotCols,wayIndex+1)
plt.title("{} {}".format(wayIndex+1,viewSet[wayIndex]['osmFile']))
image = skimage.io.imread( viewSet[wayIndex]['imageName'])
plt.imshow(image)
plt.show(block=False)
plt.pause(0.05)
goodInput = False
while goodInput == False:
print("{} - q to quit, 0 to reject all, to except use sub plot index".format(way['osmFile']))
c = getch()
try:
index = int(c)
if ( index > 0):
acceptedWay = viewSet[index-1 ]
viewSet = [acceptedWay]
print("selected {} {}".format(acceptedWay['osmFile'],index))
goodInput = True
if ( index == 0):
viewSet = [reviewSet[0]]
acceptedWay = {}
print("reject all")
goodInput = True
except:
if ( c == "q"):
sys.exit(0)
print("what??")
if ( bool(acceptedWay) ) :
acceptedWay['status'] = 'accepted'
print("accepted {}".format(acceptedWay['osmFile']))
if ( os.path.exists(anomalyStatusFile+".1")):
shutil.copy(anomalyStatusFile+".1",anomalyStatusFile+".2" )
if ( os.path.exists(anomalyStatusFile)):
shutil.copy(anomalyStatusFile,anomalyStatusFile+".1" )
with open(anomalyStatusFile,"wt",encoding="ascii") as f:
for otherKey in sorted(newWays):
other = newWays[otherKey]
if ( len(other['status']) > 0 ):
f.write("{},{}\n".format(other['status'],other['osmFile']))
| 2,821 |
777 | <reponame>kjthegod/chromium
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/file_manager/file_manager_jstest_base.h"
#include <vector>
#include "base/path_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/web_contents.h"
#include "content/public/test/browser_test_utils.h"
#include "net/base/filename_util.h"
FileManagerJsTestBase::FileManagerJsTestBase(const base::FilePath& base_path)
: base_path_(base_path) {}
void FileManagerJsTestBase::RunTest(const base::FilePath& file) {
base::FilePath root_path;
ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &root_path));
const GURL url = net::FilePathToFileURL(
root_path.Append(base_path_)
.Append(file));
ui_test_utils::NavigateToURL(browser(), url);
content::WebContents* const web_contents =
browser()->tab_strip_model()->GetActiveWebContents();
ASSERT_TRUE(web_contents);
const std::vector<int> empty_libraries;
EXPECT_TRUE(ExecuteWebUIResourceTest(web_contents, empty_libraries));
}
| 451 |
2,863 | <filename>spock-core/src/main/java/org/spockframework/mock/WrongInvocationOrderError.java<gh_stars>1000+
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.spockframework.mock;
import java.io.IOException;
import java.util.*;
import static java.util.Collections.unmodifiableList;
/**
* Thrown if an invocation on a mock object occurs too late. Example:
*
* <pre>
* when:
* ...
*
* then:
* 1 * foo.me()
* 1 * bar.me()
*
* then: // indicates that subsequent interactions must take place after previous interactions
* 1 * baz.me()
* </pre>
*
* Assuming the following invocation order:
*
* <ol>
* <li>bar.me()</li>
* <li>baz.me()</li>
* <li>foo.me()</li>
* </ol>
*
* A <tt>WrongInvocationOrderError</tt> will be thrown on the third call.
*/
public class WrongInvocationOrderError extends InteractionNotSatisfiedError {
private static final long serialVersionUID = 1L;
private final transient IMockInteraction interaction;
private final transient IMockInvocation lastInvocation;
private final transient List<IMockInvocation> previousInvocationsInReverseOrder;
private String message;
public WrongInvocationOrderError(IMockInteraction interaction, IMockInvocation lastInvocation,
Deque<IMockInvocation> previousInvocationsInReverseOrder) {
this.interaction = interaction;
this.lastInvocation = lastInvocation;
this.previousInvocationsInReverseOrder = unmodifiableList(new ArrayList<>(previousInvocationsInReverseOrder));
}
public IMockInteraction getInteraction() {
return interaction;
}
public IMockInvocation getLastInvocation() {
return lastInvocation;
}
public List<IMockInvocation> getPreviousInvocationsInReverseOrder() {
return previousInvocationsInReverseOrder;
}
@Override
public String getMessage() {
if (message != null) return message;
StringBuilder builder = new StringBuilder();
builder.append("Wrong invocation order for:\n\n");
builder.append(interaction);
builder.append("\n\n");
builder.append("Last invocation: ");
builder.append(lastInvocation);
builder.append("\n\n");
if (previousInvocationsInReverseOrder.size() == 1) {
builder.append("Previous invocation:\n\t");
builder.append(previousInvocationsInReverseOrder.get(0));
} else {
builder.append("Previous invocations in reverse order:");
previousInvocationsInReverseOrder.forEach(invocation -> {
builder.append("\n\t");
builder.append(invocation);
});
}
builder.append("\n");
message = builder.toString();
return message;
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
// create the message so that it is available for serialization
getMessage();
out.defaultWriteObject();
}
}
| 1,085 |
973 | <reponame>bcaglayan/pcap4j
/*_##########################################################################
_##
_## Copyright (C) 2014-2016 Pcap4J.org
_##
_##########################################################################
*/
package org.pcap4j;
import com.sun.jna.Platform;
import org.pcap4j.util.PropertiesLoader;
/**
* @author <NAME>
* @since pcap4j 1.0.1
*/
public final class Pcap4jPropertiesLoader {
private static final String KEY_PREFIX = Pcap4jPropertiesLoader.class.getPackage().getName();
/** */
public static final String PCAP4J_PROPERTIES_PATH_KEY = KEY_PREFIX + ".properties";
/** */
public static final String AF_INET_KEY = KEY_PREFIX + ".af.inet";
/** */
public static final String AF_INET6_KEY = KEY_PREFIX + ".af.inet6";
/** */
public static final String AF_PACKET_KEY = KEY_PREFIX + ".af.packet";
/** */
public static final String AF_LINK_KEY = KEY_PREFIX + ".af.link";
/** */
public static final String DLT_RAW_KEY = KEY_PREFIX + ".dlt.raw";
private static final int AF_INET_DEFAULT = 2;
private static final int AF_PACKET_DEFAULT = 17;
private static final int AF_LINK_DEFAULT = 18;
private static final int DLT_RAW_DEFAULT = 12;
private static final int DLT_RAW_OPENBSD = 14;
private static final int AF_INET6_DEFAULT = 23;
private static final int AF_INET6_LINUX = 10;
private static final int AF_INET6_FREEBSD = 28;
private static final int AF_INET6_MAC = 30;
private static final Pcap4jPropertiesLoader INSTANCE = new Pcap4jPropertiesLoader();
private PropertiesLoader loader =
new PropertiesLoader(
System.getProperty(
PCAP4J_PROPERTIES_PATH_KEY, KEY_PREFIX.replace('.', '/') + "/pcap4j.properties"),
true,
true);
private Pcap4jPropertiesLoader() {}
/** @return the singleton instance of Pcap4jPropertiesLoader. */
public static Pcap4jPropertiesLoader getInstance() {
return INSTANCE;
}
/** @return address family number for IPv4 addresses. Never null. */
public Integer getAfInet() {
return loader.getInteger(AF_INET_KEY, AF_INET_DEFAULT);
}
/** @return address family numbers for IPv6 addresses. Never null. */
public Integer getAfInet6() {
return loader.getInteger(AF_INET6_KEY, getDefaultAfInet6());
}
/**
* For Linux
*
* @return address family numbers for link layer addresses. Never null.
*/
public Integer getAfPacket() {
return loader.getInteger(AF_PACKET_KEY, AF_PACKET_DEFAULT);
}
/**
* For BSD including Mac OS X
*
* @return address family numbers for link layer addresses. Never null.
*/
public Integer getAfLink() {
return loader.getInteger(AF_LINK_KEY, AF_LINK_DEFAULT);
}
/**
* DLT_RAW
*
* @return the value of DLT_RAW. Never null.
*/
public Integer getDltRaw() {
return loader.getInteger(DLT_RAW_KEY, getDefaultDltRaw());
}
/** @return The default address family for IPv6 addresses (platform specific) */
private int getDefaultAfInet6() {
switch (Platform.getOSType()) {
case Platform.MAC:
return AF_INET6_MAC;
case Platform.FREEBSD:
case Platform.KFREEBSD:
return AF_INET6_FREEBSD;
case Platform.LINUX:
case Platform.ANDROID:
return AF_INET6_LINUX;
default:
return AF_INET6_DEFAULT;
}
}
/** @return The default value for DLT_RAW (platform specific) */
private int getDefaultDltRaw() {
switch (Platform.getOSType()) {
case Platform.OPENBSD:
return DLT_RAW_OPENBSD;
default:
return DLT_RAW_DEFAULT;
}
}
}
| 1,305 |
438 | {
"DESCRIPTION": "Antwortet mit einer zufälligen Zahl.",
"USAGE": "zufällig <LowNum> <HighNum>",
"RESPONSE": "🎲 Zufällige Zahl: {{NUMBER}}"
}
| 72 |
10,225 | <reponame>sixdouglas/quarkus
package io.quarkus.resteasy.reactive.common.runtime;
import java.util.List;
import java.util.Optional;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;
/**
* @author <NAME>, <EMAIL>
*/
@ConfigRoot(name = "security.jaxrs", phase = ConfigPhase.BUILD_AND_RUN_TIME_FIXED)
public class JaxRsSecurityConfig {
/**
* if set to true, access to all JAX-RS resources will be denied by default
*/
@ConfigItem(name = "deny-unannotated-endpoints")
public boolean denyJaxRs;
/**
* If no security annotations are affecting a method then they will default to requiring these roles,
* (equivalent to adding an @RolesAllowed annotation with the roles to every endpoint class).
*
* The role of '**' means any authenticated user, which is equivalent to the {@link io.quarkus.security.Authenticated}
* annotation.
*
*/
@ConfigItem
public Optional<List<String>> defaultRolesAllowed;
}
| 365 |
308 | <filename>src/conftest.py
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from seedwork.infrastructure.database import Base
from config.api_config import ApiConfig
@pytest.fixture
def db_session():
config = ApiConfig()
engine = create_engine(config.DATABASE_URL, echo=config.DEBUG)
with engine.begin() as connection:
Base.metadata.drop_all(connection)
Base.metadata.create_all(connection)
with Session(engine) as session:
yield session
| 175 |
769 | #pragma once
#include "platform.h"
#include "JniWorker.h"
#include "util/asyncWorker.h"
#include <jni.h>
#include <android/asset_manager.h>
#include <atomic>
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace Tangram {
struct LabelPickResult;
struct FeaturePickResult;
struct MarkerPickResult;
class Map;
struct SceneUpdate;
struct SceneError;
using SceneID = int32_t;
class AndroidPlatform : public Platform {
public:
AndroidPlatform(JNIEnv* jniEnv, jobject mapController, jobject assetManager);
void shutdown() override;
void requestRender() const override;
void setContinuousRendering(bool isContinuous) override;
FontSourceHandle systemFont(const std::string& name, const std::string& weight, const std::string& face) const override;
std::vector<FontSourceHandle> systemFontFallbacksHandle() const override;
bool startUrlRequestImpl(const Url& url, const UrlRequestHandle request, UrlRequestId& id) override;
void cancelUrlRequestImpl(const UrlRequestId id) override;
void onUrlComplete(JNIEnv* jniEnv, jlong jRequestHandle, jbyteArray jBytes, jstring jError);
static void jniOnLoad(JavaVM* javaVM, JNIEnv* jniEnv);
private:
std::vector<char> bytesFromFile(const Url& url) const;
bool bytesFromAssetManager(const char* path, std::function<char*(size_t)> allocator) const;
std::string fontPath(const std::string& family, const std::string& weight, const std::string& style) const;
jobject m_mapController;
AAssetManager* m_assetManager;
mutable JniWorker m_jniWorker;
AsyncWorker m_fileWorker;
};
} // namespace Tangram
| 551 |
666 | <gh_stars>100-1000
import sys
sys.path.append("../../")
corpora = ['a', 'b', 'c', 'd', 'e']
from appJar import gui
def update_corpora(value):
if value is "add_corpus":
name = app.entry("corpus_name")
corpora.append(app.entry("corpus_name"))
app.option("corpora", value=corpora, mode='replace') #Here, I'd like to update the values
app.option("corpora", selected=name) #Here, I'd like to select the new entry
elif value is "remove_corpus":
corpora.remove(app.option("corpora"))
app.option("corpora", value=corpora, mode='replace', selected=0) #Here, I'd like to update the values
with gui("MyGUI", bg="lightblue") as app:
app.option("corpora", value=corpora, label="Corpora", change=update_corpora, colspan=2)
app.entry("corpus_name", label="Corpus Name:", colspan=2)
app.button("add_corpus", update_corpora, label="Add Corpus")
app.button("remove_corpus", update_corpora, label="Remove Corpus", row=2, column=1)
| 385 |
4,772 | package example.repo;
import example.model.Customer545;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
public interface Customer545Repository extends CrudRepository<Customer545, Long> {
List<Customer545> findByLastName(String lastName);
}
| 83 |
3,589 | <gh_stars>1000+
# list
a = [
x + 1 for x in range(3)
]
# dict
b = {
x: x + 1 for x in range(3)
}
# generator
c = (
x * x for x in range(3)
)
# set
d = {
x + x for x in range(3)
}
# other styles
e = [
x + 1 for x
in range(3)
]
| 134 |
32,544 | package com.baeldung.performancetests.model.source;
import com.googlecode.jmapper.annotations.JGlobalMap;
import com.googlecode.jmapper.annotations.JMapAccessor;
import java.util.List;
public class RefundPolicy {
@JMapAccessor(get = "isRefundable", set = "setRefundable")
private boolean isRefundable;
private int refundTimeInDays;
public RefundPolicy() {
}
public boolean isRefundable() {
return isRefundable;
}
public void setRefundable(boolean refundable) {
isRefundable = refundable;
}
public int getRefundTimeInDays() {
return refundTimeInDays;
}
public void setRefundTimeInDays(int refundTimeInDays) {
this.refundTimeInDays = refundTimeInDays;
}
public List<String> getNotes() {
return notes;
}
public void setNotes(List<String> notes) {
this.notes = notes;
}
public RefundPolicy(boolean isRefundable, int refundTimeInDays, List<String> notes) {
this.isRefundable = isRefundable;
this.refundTimeInDays = refundTimeInDays;
this.notes = notes;
}
private List<String> notes;
}
| 451 |
9,425 | import pytest
import salt.states.mac_xattr as xattr
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
return {xattr: {}}
def test_exists_not():
"""
Test adding an attribute when it doesn't exist
"""
with patch("os.path.exists") as exists_mock:
expected = {
"changes": {"key": "value"},
"comment": "",
"name": "/path/to/file",
"result": True,
}
exists_mock.return_value = True
list_mock = MagicMock(return_value={"other.id": "value2"})
write_mock = MagicMock()
with patch.dict(
xattr.__salt__, {"xattr.list": list_mock, "xattr.write": write_mock}
):
out = xattr.exists("/path/to/file", ["key=value"])
list_mock.assert_called_once_with("/path/to/file")
write_mock.assert_called_once_with("/path/to/file", "key", "value", False)
assert out == expected
def test_exists_change():
"""
Test changing an attribute value
"""
with patch("os.path.exists") as exists_mock:
expected = {
"changes": {"key": "other_value"},
"comment": "",
"name": "/path/to/file",
"result": True,
}
exists_mock.return_value = True
list_mock = MagicMock(return_value={"key": "value"})
write_mock = MagicMock()
with patch.dict(
xattr.__salt__, {"xattr.list": list_mock, "xattr.write": write_mock}
):
out = xattr.exists("/path/to/file", ["key=other_value"])
list_mock.assert_called_once_with("/path/to/file")
write_mock.assert_called_once_with(
"/path/to/file", "key", "other_value", False
)
assert out == expected
def test_exists_already():
"""
Test with the same value does nothing
"""
with patch("os.path.exists") as exists_mock:
expected = {
"changes": {},
"comment": "All values existed correctly.",
"name": "/path/to/file",
"result": True,
}
exists_mock.return_value = True
list_mock = MagicMock(return_value={"key": "value"})
write_mock = MagicMock()
with patch.dict(
xattr.__salt__, {"xattr.list": list_mock, "xattr.write": write_mock}
):
out = xattr.exists("/path/to/file", ["key=value"])
list_mock.assert_called_once_with("/path/to/file")
assert not write_mock.called
assert out == expected
def test_delete():
"""
Test deleting an attribute from a file
"""
with patch("os.path.exists") as exists_mock:
expected = {
"changes": {"key": "delete"},
"comment": "",
"name": "/path/to/file",
"result": True,
}
exists_mock.return_value = True
list_mock = MagicMock(return_value={"key": "value2"})
delete_mock = MagicMock()
with patch.dict(
xattr.__salt__, {"xattr.list": list_mock, "xattr.delete": delete_mock}
):
out = xattr.delete("/path/to/file", ["key"])
list_mock.assert_called_once_with("/path/to/file")
delete_mock.assert_called_once_with("/path/to/file", "key")
assert out == expected
def test_delete_not():
"""
Test deleting an attribute that doesn't exist from a file
"""
with patch("os.path.exists") as exists_mock:
expected = {
"changes": {},
"comment": "All attributes were already deleted.",
"name": "/path/to/file",
"result": True,
}
exists_mock.return_value = True
list_mock = MagicMock(return_value={"other.key": "value2"})
delete_mock = MagicMock()
with patch.dict(
xattr.__salt__, {"xattr.list": list_mock, "xattr.delete": delete_mock}
):
out = xattr.delete("/path/to/file", ["key"])
list_mock.assert_called_once_with("/path/to/file")
assert not delete_mock.called
assert out == expected
| 2,030 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.