text stringlengths 2 1.04M | meta dict |
|---|---|
function sugar = detect_sugar_position(fl,nr_frames,ROI)
%DETECT_SUGAR_POSITION - This function computes the default position of
% the sugar pellet
% Inputs:
% fl - structure of required folder paths (fl.pre, fl.frames)
% nr_frames - nr of frames in video
% ROI - [x,y,width,heigth]
% coordinates of the area where the sugar pellet is
% expected
% Outputs:
% sugar - [x,y] coordinates of the sugar pellet
% Author: Biagio Brattoli, Uta Büchler
% Heidelberg Collaboratory for Image Processing (HCI), Heidelberg
% email address: uta.buechler@iwr.uni-heidelberg.de
% January 2017
if ~exist([fl.pre,'/sugar_location.mat'],'file')
if nargin<4
ROI = [500,730,150,315];
end
%take only a few images out of the video (choose linearly)
%for getting the sugar location
nr_choice = min(nr_frames,2000);
framesChoice = 1:floor(nr_frames/nr_choice):nr_frames;
circles = -ones(numel(framesChoice),2);
parfor ii=1:numel(framesChoice)
frame = imread([fl.frames,sprintf('/%06i.jpg',framesChoice(ii))]);
[centers, radii] = imfindcircles(frame,[10 30],'Sensitivity',0.82,'Method','twostage');
if isempty(centers); continue; end
circles(ii,:) = centers(1,:);
end
detections = circles(circles(:,1)~=-1,:);
detections(detections(:,1)<ROI(1),:)=[];
detections(detections(:,1)>ROI(2),:)=[];
detections(detections(:,2)<ROI(3),:)=[];
detections(detections(:,2)>ROI(4),:)=[];
[pdfx]= ksdensity(detections(:,1));
[pdfy]= ksdensity(detections(:,2));
[~,x] = max(pdfx);
[~,y] = max(pdfy);
x = detections(x,1);
y = detections(y,2);
sugar = [x,y];
save([fl.pre,'/sugar_location.mat'],'sugar');
else
load([fl.pre,'/sugar_location.mat'],'sugar');
end
end | {
"content_hash": "a2856f44ac4f9e73081577614d384e37",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 95,
"avg_line_length": 31.483333333333334,
"alnum_prop": 0.6003176283748015,
"repo_name": "CompVis/AutomaticBehaviorAnalysis_NatureComm",
"id": "c6a127ce17400da2174029397fef0627eba43b80",
"size": "1890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Code/preprocessing/detect_sugar_position.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Matlab",
"bytes": "76725"
}
],
"symlink_target": ""
} |
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/reboot.h>
#include "common.h"
#include "daemon.h"
/* the init script path */
#define INIT_SCRIPT_PATH CONF_DIR"/rc.d/rc.sysinit"
/* the shutdown script path */
#define SHUTDOWN_SCRIPT_PATH CONF_DIR"/rc.d/rc.shutdown"
bool _run_script(const char *path, pid_t *pid) {
/* the return value */
bool is_success = false;
/* the process ID */
pid_t parent_pid = (-1);
/* get the process ID */
parent_pid = getpid();
/* create a child process */
*pid = daemon_fork();
switch (*pid) {
case (-1):
goto end;
case 0:
/* in the child process, run the init script */
(void) execl(path, path, (char *) NULL);
/* upon failure, send a signal to the parent process */
(void) kill(parent_pid, SIGTERM);
break;
default:
is_success = true;
break;
}
end:
return is_success;
}
int main() {
/* the process exit code */
int exit_code = EXIT_FAILURE;
/* a signal action */
struct sigaction signal_action = {{0}};
/* a signal mask used for waiting */
sigset_t signal_mask = {{0}};
/* the init script PID */
pid_t script_pid = -1;
/* the signal received */
siginfo_t received_signal = {0};
/* the command passed to reboot() */
int reboot_command = 0;
/* prevent child processes from becoming zombie processes */
signal_action.sa_flags = SA_NOCLDWAIT | SA_NOCLDSTOP;
signal_action.sa_sigaction = NULL;
if (-1 == sigemptyset(&signal_action.sa_mask)) {
goto end;
}
if (-1 == sigaction(SIGCHLD, &signal_action, NULL)) {
goto end;
}
/* block SIGUSR1 and SIGUSR2 signals */
(void) memcpy(&signal_mask, &signal_action.sa_mask, sizeof(signal_mask));
if (-1 == sigaddset(&signal_mask, SIGUSR1)) {
goto end;
}
if (-1 == sigaddset(&signal_mask, SIGUSR2)) {
goto end;
}
if (-1 == sigprocmask(SIG_SETMASK, &signal_mask, NULL)) {
goto end;
}
/* run the init script */
if (false == _run_script(INIT_SCRIPT_PATH, &script_pid)) {
goto end;
}
/* wait until either SIGUSR1 or SIGUSR2 is received */
if (0 == sigwaitinfo(&signal_mask, &received_signal)) {
if (script_pid != received_signal.si_pid) {
exit_code = EXIT_SUCCESS;
}
}
/* ask all processes to terminate */
PRINT("Terminating all processes\n");
if (0 == kill(-1, SIGTERM)) {
/* upon success, give them 2 seconds and kill them brutally */
(void) sleep(2);
(void) kill(-1, SIGKILL);
}
/* disable the SIGCHLD signal handler, to make it possible to wait for the
* shutdown script to terminate */
if (-1 == sigemptyset(&signal_action.sa_mask)) {
goto flush;
}
signal_action.sa_flags = 0;
signal_action.sa_handler = SIG_IGN;
if (-1 == sigaction(SIGCHLD, &signal_action, NULL)) {
goto flush;
}
/* run the shutdown script */
PRINT("Running the shutdown script\n");
if (true == _run_script(SHUTDOWN_SCRIPT_PATH, &script_pid)) {
/* wait for the shutdown script to terminate */
(void) waitpid(script_pid, NULL, 0);
}
flush:
/* flush all file systems */
PRINT("Flushing file system buffers\n");
sync();
/* reboot or shut down the system */
switch (received_signal.si_signo) {
case SIGUSR1:
PRINT("Shutting down\n");
reboot_command = RB_POWER_OFF;
break;
case SIGUSR2:
PRINT("Rebooting\n");
reboot_command = RB_AUTOBOOT;
break;
default:
goto end;
}
(void) reboot(reboot_command);
end:
return exit_code;
}
| {
"content_hash": "47ddc7b0e7ae9dd8e9384e6930ed9336",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 75,
"avg_line_length": 21.860759493670887,
"alnum_prop": 0.6459177764910249,
"repo_name": "dimkr/lazy-utils",
"id": "c8ac93edc3429798dd238cb5252d8224fd4db240",
"size": "3454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "init.c",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "83812"
},
{
"name": "C++",
"bytes": "408"
},
{
"name": "Makefile",
"bytes": "4135"
}
],
"symlink_target": ""
} |
var os = require('os'),
fs = require('fs'),
path = require('path'),
assert = require('assert'),
swintHelper = require('swint-helper'),
buildSVG = require('../lib');
global.swintVar.printLevel = 5;
describe('builder-svg', function() {
it('Error when no callback', function() {
assert.throws(function() {
buildSVG({});
});
});
it('Error when inDir doesn\'t exist', function(done) {
buildSVG({
inDir: '/this-directory-does-not-exist'
}, function(err, res) {
assert.notEqual(err, null);
done();
});
});
it('Simple case', function(done) {
buildSVG({
name: 'Test',
inDir: path.join(__dirname, '../test_case'),
outDir: path.join(os.tmpdir(), 'swint-builder-svg-out')
}, function(err, res) {
assert.deepEqual(
fs.readFileSync(path.join(__dirname, '../test_result/flags.svg')),
fs.readFileSync(path.join(os.tmpdir(), 'swint-builder-svg-out/flags.svg'))
);
assert.deepEqual(
fs.readFileSync(path.join(__dirname, '../test_result/tech.svg')),
fs.readFileSync(path.join(os.tmpdir(), 'swint-builder-svg-out/tech.svg'))
);
done();
});
});
after(function() {
fs.unlinkSync(path.join(os.tmpdir(), 'swint-builder-svg-out/flags.svg'));
fs.unlinkSync(path.join(os.tmpdir(), 'swint-builder-svg-out/tech.svg'));
fs.rmdirSync(path.join(os.tmpdir(), 'swint-builder-svg-out'));
});
});
| {
"content_hash": "5b871fd459cf69e7c85ccced879208e9",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 78,
"avg_line_length": 27.08,
"alnum_prop": 0.6314623338257016,
"repo_name": "KnowRe/swint-builder-svg",
"id": "816a1d17f0758faaf387df30e109efce6c98b25d",
"size": "1354",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "3167"
}
],
"symlink_target": ""
} |
package liquibase.change.core;
import liquibase.change.AbstractChange;
import liquibase.change.DatabaseChange;
import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChangeProperty;
import liquibase.configuration.GlobalConfiguration;
import liquibase.configuration.LiquibaseConfiguration;
import liquibase.database.Database;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;
import liquibase.executor.Executor;
import liquibase.executor.ExecutorService;
import liquibase.executor.LoggingExecutor;
import liquibase.logging.LogFactory;
import liquibase.parser.core.ParsedNode;
import liquibase.parser.core.ParsedNodeException;
import liquibase.resource.ResourceAccessor;
import liquibase.sql.Sql;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.CommentStatement;
import liquibase.statement.core.RuntimeStatement;
import liquibase.util.StringUtils;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Executes a given shell executable.
*/
@DatabaseChange(name = "executeCommand",
description = "Executes a system command. Because this refactoring doesn't generate SQL like most, using LiquiBase commands such as migrateSQL may not work as expected. Therefore, if at all possible use refactorings that generate SQL.",
priority = ChangeMetaData.PRIORITY_DEFAULT)
public class ExecuteShellCommandChange extends AbstractChange {
private String executable;
private List<String> os;
private List<String> args = new ArrayList<String>();
protected List<String> finalCommandArray;
private String timeout;
private static final Pattern TIMEOUT_PATTERN = Pattern.compile("^\\s*(\\d+)\\s*([sSmMhH]?)\\s*$");
private static final Long SECS_IN_MILLIS = 1000L;
private static final Long MIN_IN_MILLIS = SECS_IN_MILLIS * 60;
private static final Long HOUR_IN_MILLIS = MIN_IN_MILLIS * 60;
protected Integer maxStreamGobblerOutput = null;
@Override
public boolean generateStatementsVolatile(Database database) {
return true;
}
@Override
public boolean generateRollbackStatementsVolatile(Database database) {
return true;
}
@DatabaseChangeProperty(description = "Name of the executable to run", exampleValue = "mysqldump", requiredForDatabase = "all")
public String getExecutable() {
return executable;
}
public void setExecutable(String executable) {
this.executable = executable;
}
public void addArg(String arg) {
this.args.add(arg);
}
public List<String> getArgs() {
return Collections.unmodifiableList(args);
}
public void setOs(String os) {
this.os = StringUtils.splitAndTrim(os, ",");
}
@DatabaseChangeProperty(description = "Timeout value for executable to run", exampleValue = "10s")
public String getTimeout() {
return timeout;
}
public void setTimeout(String timeout) {
this.timeout = timeout;
}
@DatabaseChangeProperty(description = "List of operating systems on which to execute the command (taken from the os.name Java system property)", exampleValue = "Windows 7")
public List<String> getOs() {
return os;
}
@Override
public ValidationErrors validate(Database database) {
ValidationErrors validationErrors = new ValidationErrors();
if (!StringUtils.isEmpty(timeout)) {
// check for the timeout values, accept only positive value with one letter unit (s/m/h)
Matcher matcher = TIMEOUT_PATTERN.matcher(timeout);
if (!matcher.matches()) {
validationErrors.addError("Invalid value specified for timeout: " + timeout);
}
}
return validationErrors;
}
@Override
public Warnings warn(Database database) {
return new Warnings();
}
@Override
public SqlStatement[] generateStatements(final Database database) {
boolean shouldRun = true;
if (os != null && os.size() > 0) {
String currentOS = System.getProperty("os.name");
if (!os.contains(currentOS)) {
shouldRun = false;
LogFactory.getLogger().info("Not executing on os " + currentOS + " when " + os + " was specified");
}
}
// check if running under not-executed mode (logging output)
boolean nonExecutedMode = false;
Executor executor = ExecutorService.getInstance().getExecutor(database);
if (executor instanceof LoggingExecutor) {
nonExecutedMode = true;
}
this.finalCommandArray = createFinalCommandArray(database);
if (shouldRun && !nonExecutedMode) {
return new SqlStatement[]{new RuntimeStatement() {
@Override
public Sql[] generate(Database database) {
try {
executeCommand(database);
} catch (Exception e) {
throw new UnexpectedLiquibaseException("Error executing command: " + e.getLocalizedMessage(), e);
}
return null;
}
}};
}
if (nonExecutedMode) {
try {
return new SqlStatement[]{
new CommentStatement(getCommandString())
};
} finally {
nonExecutedCleanup();
}
}
return new SqlStatement[0];
}
protected void nonExecutedCleanup() {
}
protected List<String> createFinalCommandArray(Database database) {
List<String> commandArray = new ArrayList<String>();
commandArray.add(getExecutable());
commandArray.addAll(getArgs());
return commandArray;
}
protected void executeCommand(Database database) throws Exception {
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
ByteArrayOutputStream inputStream = new ByteArrayOutputStream();
ProcessBuilder pb = createProcessBuilder(database);
Process p = pb.start();
int returnCode = 0;
try {
//output both stdout and stderr data from proc to stdout of this process
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), errorStream);
StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), inputStream);
errorGobbler.start();
outputGobbler.start();
// check if timeout is specified
// can't use Process's new api with timeout, so just workaround it for now
long timeoutInMillis = getTimeoutInMillis();
if (timeoutInMillis > 0) {
returnCode = waitForOrKill(p, timeoutInMillis);
} else {
// do default behavior for any value equal to or less than 0
returnCode = p.waitFor();
}
errorGobbler.finish();
outputGobbler.finish();
} catch (InterruptedException e) {
// Restore interrupted state...
Thread.currentThread().interrupt();
}
String errorStreamOut = errorStream.toString(LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
String infoStreamOut = inputStream.toString(LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
if (errorStreamOut != null && !errorStreamOut.isEmpty()) {
LogFactory.getLogger().severe(errorStreamOut);
}
LogFactory.getLogger().info(infoStreamOut);
processResult(returnCode, errorStreamOut, infoStreamOut, database);
}
/**
* Max bytes to copy from output to {@link #processResult(int, String, String, Database)}. If null, process all output.
* @return
*/
protected Integer getMaxStreamGobblerOutput() {
return maxStreamGobblerOutput;
}
/**
* Waits for the process to complete and kills it if the process is not finished after the specified <code>timeoutInMillis</code>.
* <p>
* Creates a scheduled task to destroy the process in given timeout milliseconds.
* This killer task will be cancelled if the process returns before the timeout value.
*
* @param process
* @param timeoutInMillis waits for specified timeoutInMillis before destroying the process.
* It will wait indefinitely if timeoutInMillis is 0.
*/
private int waitForOrKill(final Process process, final long timeoutInMillis) throws ExecutionException, TimeoutException {
int ret = -1;
final AtomicBoolean timedOut = new AtomicBoolean(false);
Timer timer = new Timer();
if (timeoutInMillis > 0) {
timer.schedule(new TimerTask() {
@Override
public void run() {
// timed out
timedOut.set(true);
process.destroy();
}
}, timeoutInMillis);
}
boolean stop = false;
while (!stop) {
try {
ret = process.waitFor();
stop = true;
// if process already returned, then cancel the killer task if it is still running
timer.cancel();
// check if we timed out or not
if (timedOut.get()) {
String timeoutStr = timeout != null ? timeout : timeoutInMillis + " ms";
throw new TimeoutException("Process timed out (" + timeoutStr + ")");
}
} catch (InterruptedException ignore) {
// check again
// Restore interrupted state...
Thread.currentThread().interrupt();
}
}
return ret;
}
/**
* @return the timeout value in millisecond
*/
protected long getTimeoutInMillis() {
if (timeout != null) {
//Matcher matcher = TIMEOUT_PATTERN.matcher("10s");
Matcher matcher = TIMEOUT_PATTERN.matcher(timeout);
if (matcher.find()) {
String val = matcher.group(1);
try {
long valLong = Long.parseLong(val);
String unit = matcher.group(2);
if (StringUtils.isEmpty(unit)) {
return valLong * SECS_IN_MILLIS;
}
char u = unit.toLowerCase().charAt(0);
// only s/m/h possible here
switch (u) {
case 'h':
valLong = valLong * HOUR_IN_MILLIS;
break;
case 'm':
valLong = valLong * MIN_IN_MILLIS;
default:
valLong = valLong * SECS_IN_MILLIS;
}
return valLong;
} catch (NumberFormatException ignore) {
}
}
}
return 0;
}
/**
* Called by {@link #executeCommand(Database)} after running the command. Default implementation throws an error if returnCode != 0
*/
protected void processResult(int returnCode, String errorStreamOut, String infoStreamOut, Database database) {
if (returnCode != 0) {
throw new RuntimeException(getCommandString() + " returned a code of " + returnCode);
}
}
protected ProcessBuilder createProcessBuilder(Database database) {
ProcessBuilder pb = new ProcessBuilder(finalCommandArray);
pb.redirectErrorStream(true);
return pb;
}
@Override
public String getConfirmationMessage() {
return "Shell command '" + getCommandString() + "' executed";
}
protected String getCommandString() {
return getExecutable() + " " + StringUtils.join(args, " ");
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
@Override
protected void customLoadLogic(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException {
ParsedNode argsNode = parsedNode.getChild(null, "args");
if (argsNode == null) {
argsNode = parsedNode;
}
for (ParsedNode arg : argsNode.getChildren(null, "arg")) {
addArg(arg.getChildValue(null, "value", String.class));
}
String passedValue = StringUtils.trimToNull(parsedNode.getChildValue(null, "os", String.class));
if (passedValue == null) {
this.os = new ArrayList<String>();
} else {
List<String> os = StringUtils.splitAndTrim(StringUtils.trimToEmpty(parsedNode.getChildValue(null, "os", String.class)), ",");
if (os.size() == 1 && os.get(0).equals("")) {
this.os = null;
} else if (os.size() > 0) {
this.os = os;
}
}
}
private class StreamGobbler extends Thread {
private final OutputStream outputStream;
private InputStream processStream;
boolean loggedTruncated = false;
long copiedSize = 0;
private StreamGobbler(InputStream processStream, ByteArrayOutputStream outputStream) {
this.processStream = processStream;
this.outputStream = outputStream;
}
public void run() {
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(processStream);
while (processStream != null) {
if (bufferedInputStream.available() > 0) {
copy(bufferedInputStream, outputStream);
}
try {
Thread.sleep(100);
} catch (InterruptedException ignore) {
// Restore interrupted state...
Thread.currentThread().interrupt();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void finish() {
InputStream processStream = this.processStream;
this.processStream = null;
try {
copy(processStream, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
Integer maxToCopy = getMaxStreamGobblerOutput();
byte[] bytes = new byte[1024];
int r = inputStream.read(bytes);
while (r > 0) {
if (maxToCopy != null && copiedSize > maxToCopy) {
if (!loggedTruncated) {
outputStream.write("...[TRUNCATED]...".getBytes());
loggedTruncated = true;
}
} else {
outputStream.write(bytes, 0, r);
}
r = inputStream.read(bytes);
copiedSize += r;
}
}
}
@Override
public String toString() {
return "external process '" + getExecutable() + "' " + getArgs();
}
}
| {
"content_hash": "f7fcb1b40c8b2cec475c6ea420e2de4e",
"timestamp": "",
"source": "github",
"line_count": 435,
"max_line_length": 244,
"avg_line_length": 35.93793103448276,
"alnum_prop": 0.5944476428068829,
"repo_name": "Datical/liquibase",
"id": "52098fc22e1c9eb325da15343ff7eaa69b925385",
"size": "15633",
"binary": false,
"copies": "1",
"ref": "refs/heads/ddb",
"path": "liquibase-core/src/main/java/liquibase/change/core/ExecuteShellCommandChange.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "552"
},
{
"name": "CSS",
"bytes": "1202"
},
{
"name": "Groovy",
"bytes": "579049"
},
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Inno Setup",
"bytes": "2522"
},
{
"name": "Java",
"bytes": "4419959"
},
{
"name": "PLpgSQL",
"bytes": "1184"
},
{
"name": "Puppet",
"bytes": "5196"
},
{
"name": "Roff",
"bytes": "3153"
},
{
"name": "Ruby",
"bytes": "820"
},
{
"name": "SQLPL",
"bytes": "2790"
},
{
"name": "Shell",
"bytes": "4879"
},
{
"name": "TSQL",
"bytes": "24158"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/nowCardStyle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top"
android:orientation="vertical" >
<EditText
android:id="@+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="type to filter"
android:inputType="text"
android:maxLines="1" />
<ListView
android:id="@id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000" />
</LinearLayout> | {
"content_hash": "52d8241bc0eafa0d05411aa738930df3",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 72,
"avg_line_length": 30.541666666666668,
"alnum_prop": 0.6521145975443383,
"repo_name": "pieterverstraete/BeTrains-for-Android",
"id": "ca6558e9dccd9955867ef619d5ea20043dd2e6f8",
"size": "733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BeTrains/src/main/res/layout/fragment_station_picker.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "467141"
}
],
"symlink_target": ""
} |
<!--<div class="element-panel-index"><%= index %></div>-->
<div class="element-index"><%= index %></div>
<div class="element-panel-preview js-show">
<div class="btn-element " data-toggle="tooltip" data-placement="left" title="Open Element">
<% if( thumbnail === "about:blank" && questionText !== "") {%>
<div class="btn-image "><%= questionText %> </div>
<% } else { %>
<div class="btn-image " style='background-image: url("<%= thumbnail %>");'></div>
<% } %>
</div>
</div>
<!--<div class="btn-overlay grey"></div>-->
<!--<div class="index number">
<span class="circle-index index-list-element"><%= index %></span>
</div>-->
<!--<div class="btn-overlay-description">
<p></p>
</div>
<div class="btn-edit">
<a class="btnNav btnDelete js-delete"></a>
</div>-->
<!-- <div class="line"></div>-->
| {
"content_hash": "7931f3cbacedda8b605c8f03a04adf3f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 93,
"avg_line_length": 34.708333333333336,
"alnum_prop": 0.5714285714285714,
"repo_name": "pointable/hitcamp",
"id": "bcc8a67063a39b42c473ab61db1efdb617429590",
"size": "833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/webapp/js/apps/elements/list/templates/elements_panel_item.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "477060"
},
{
"name": "HTML",
"bytes": "686756"
},
{
"name": "JavaScript",
"bytes": "5737745"
},
{
"name": "PHP",
"bytes": "2199"
},
{
"name": "Shell",
"bytes": "321"
}
],
"symlink_target": ""
} |
package org.jfrog.hudson.pipeline.common.types;
import com.google.common.collect.Maps;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.Whitelisted;
import org.jenkinsci.plugins.workflow.cps.CpsScript;
import org.jfrog.hudson.CredentialsConfig;
import org.jfrog.hudson.pipeline.common.Utils;
import org.jfrog.hudson.pipeline.common.types.buildInfo.BuildInfo;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.jfrog.build.extractor.clientConfiguration.util.EditPropertiesHelper.EditPropertiesActionType;
import static org.jfrog.hudson.pipeline.common.Utils.BUILD_INFO;
import static org.jfrog.hudson.pipeline.common.Utils.appendBuildInfo;
/**
* Created by romang on 4/21/16.
*/
public class ArtifactoryServer implements Serializable {
public static final long serialVersionUID = 1L;
public static final String SPEC = "spec";
public static final String SERVER = "server";
public static final String BUILD_NAME = "buildName";
public static final String BUILD_NUMBER = "buildNumber";
public static final String FAIL_NO_OP = "failNoOp";
public static final String PROPERTIES = "props";
public static final String EDIT_PROPERTIES_TYPE = "editType";
private String serverName;
private String url;
private String username;
private String password;
private String credentialsId;
private boolean bypassProxy;
private transient CpsScript cpsScript;
private boolean usesCredentialsId;
private Connection connection = new Connection();
private int deploymentThreads;
public ArtifactoryServer() {
}
public ArtifactoryServer(String artifactoryServerName, String url, int deploymentThreads) {
serverName = artifactoryServerName;
this.url = url;
this.deploymentThreads = deploymentThreads;
}
public ArtifactoryServer(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
public ArtifactoryServer(String url, String credentialsId) {
this.url = url;
this.credentialsId = credentialsId;
this.usesCredentialsId = true;
}
public CredentialsConfig createCredentialsConfig() {
CredentialsConfig credentialsConfig = new CredentialsConfig(this.username, this.password, this.credentialsId, null);
credentialsConfig.setIgnoreCredentialPluginDisabled(usesCredentialsId);
return credentialsConfig;
}
public void setCpsScript(CpsScript cpsScript) {
this.cpsScript = cpsScript;
}
private Map<String, Object> getDownloadUploadObjectMap(Map<String, Object> arguments) {
if (!arguments.containsKey(SPEC)) {
throw new IllegalArgumentException(SPEC + " is a mandatory argument");
}
List<String> keysAsList = Arrays.asList(SPEC, BUILD_INFO, FAIL_NO_OP);
if (!keysAsList.containsAll(arguments.keySet())) {
throw new IllegalArgumentException("Only the following arguments are allowed, " + keysAsList.toString());
}
Map<String, Object> stepVariables = Maps.newLinkedHashMap(arguments);
stepVariables.put(SERVER, this);
return stepVariables;
}
@Whitelisted
public void download(Map<String, Object> downloadArguments) {
Map<String, Object> stepVariables = getDownloadUploadObjectMap(downloadArguments);
appendBuildInfo(cpsScript, stepVariables);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryDownload", stepVariables);
}
@Whitelisted
public void download(String spec) {
download(spec, null, false);
}
@Whitelisted
public void download(String spec, BuildInfo buildInfo) {
download(spec, buildInfo, false);
}
@Whitelisted
public void download(String spec, boolean failNoOp) {
download(spec, null, failNoOp);
}
@Whitelisted
public void download(String spec, BuildInfo buildInfo, boolean failNoOp) {
Map<String, Object> downloadArguments = Maps.newLinkedHashMap();
downloadArguments.put(SPEC, spec);
downloadArguments.put(BUILD_INFO, buildInfo);
downloadArguments.put(FAIL_NO_OP, failNoOp);
download(downloadArguments);
}
@Whitelisted
public void upload(Map<String, Object> uploadArguments) {
Map<String, Object> stepVariables = getDownloadUploadObjectMap(uploadArguments);
appendBuildInfo(cpsScript, stepVariables);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryUpload", stepVariables);
}
@Whitelisted
public void upload(String spec) {
upload(spec, null, false);
}
@Whitelisted
public void upload(String spec, BuildInfo buildInfo) {
upload(spec, buildInfo, false);
}
@Whitelisted
public void upload(String spec, boolean failNoOp) {
upload(spec, null, failNoOp);
}
@Whitelisted
public void upload(String spec, BuildInfo buildInfo, boolean failNoOp) {
Map<String, Object> uploadArguments = Maps.newLinkedHashMap();
uploadArguments.put(SPEC, spec);
uploadArguments.put(BUILD_INFO, buildInfo);
uploadArguments.put(FAIL_NO_OP, failNoOp);
upload(uploadArguments);
}
private Map<String, Object> getPropsObjectMap(Map<String, Object> arguments) {
if (!arguments.containsKey(SPEC) || !arguments.containsKey(PROPERTIES)) {
throw new IllegalArgumentException(SPEC + PROPERTIES + " are mandatory arguments");
}
List<String> keysAsList = Arrays.asList(SPEC, PROPERTIES, FAIL_NO_OP);
if (!keysAsList.containsAll(arguments.keySet())) {
throw new IllegalArgumentException("Only the following arguments are allowed, " + keysAsList.toString());
}
Map<String, Object> stepVariables = Maps.newLinkedHashMap(arguments);
stepVariables.put(SERVER, this);
return stepVariables;
}
@Whitelisted
public void setProps(Map<String, Object> propsArguments) {
Map<String, Object> stepVariables = getPropsObjectMap(propsArguments);
stepVariables.put(EDIT_PROPERTIES_TYPE, EditPropertiesActionType.SET);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryEditProps", stepVariables);
}
@Whitelisted
public void setProps(String spec, String props) {
setProps(spec, props, false);
}
@Whitelisted
public void setProps(String spec, String props, boolean failNoOp) {
Map<String, Object> propsArguments = Maps.newLinkedHashMap();
propsArguments.put(SPEC, spec);
propsArguments.put(PROPERTIES, props);
propsArguments.put(FAIL_NO_OP, failNoOp);
setProps(propsArguments);
}
@Whitelisted
public void deleteProps(Map<String, Object> propsArguments) {
Map<String, Object> stepVariables = getPropsObjectMap(propsArguments);
stepVariables.put(EDIT_PROPERTIES_TYPE, EditPropertiesActionType.DELETE);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryEditProps", stepVariables);
}
@Whitelisted
public void deleteProps(String spec, String props) {
deleteProps(spec, props, false);
}
@Whitelisted
public void deleteProps(String spec, String props, boolean failNoOp) {
Map<String, Object> propsArguments = Maps.newLinkedHashMap();
propsArguments.put(SPEC, spec);
propsArguments.put(PROPERTIES, props);
propsArguments.put(FAIL_NO_OP, failNoOp);
deleteProps(propsArguments);
}
@Whitelisted
public void publishBuildInfo(BuildInfo buildInfo) {
Map<String, Object> stepVariables = Maps.newLinkedHashMap();
stepVariables.put(BUILD_INFO, buildInfo);
stepVariables.put(SERVER, this);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("publishBuildInfo", stepVariables);
}
@Whitelisted
public void promote(Map<String, Object> promotionParams) {
Map<String, Object> stepVariables = Maps.newLinkedHashMap();
stepVariables.put("promotionConfig", Utils.createPromotionConfig(promotionParams, true));
stepVariables.put(SERVER, this);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryPromoteBuild", stepVariables);
}
@Whitelisted
public void distribute(Map<String, Object> distributionParams) {
Map<String, Object> stepVariables = Maps.newLinkedHashMap();
stepVariables.put("distributionConfig", Utils.createDistributionConfig(distributionParams));
stepVariables.put(SERVER, this);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("artifactoryDistributeBuild", stepVariables);
}
@Whitelisted
public void xrayScan(Map<String, Object> xrayScanParams) {
Map<String, Object> stepVariables = Maps.newLinkedHashMap();
stepVariables.put("xrayScanConfig", Utils.createXrayScanConfig(xrayScanParams));
stepVariables.put(SERVER, this);
// Throws CpsCallableInvocation - Must be the last line in this method
cpsScript.invokeMethod("xrayScanBuild", stepVariables);
}
public String getServerName() {
return serverName;
}
@Whitelisted
public String getUrl() {
return url;
}
@Whitelisted
public void setUrl(String url) {
this.url = url;
}
@Whitelisted
public String getUsername() {
return username;
}
@Whitelisted
public void setUsername(String username) {
this.username = username;
this.credentialsId = "";
this.usesCredentialsId = false;
}
@Whitelisted
public void setPassword(String password) {
this.password = password;
this.credentialsId = "";
this.usesCredentialsId = false;
}
public String getPassword() {
return this.password;
}
@Whitelisted
public void setBypassProxy(boolean bypassProxy) {
this.bypassProxy = bypassProxy;
}
@Whitelisted
public boolean isBypassProxy() {
return bypassProxy;
}
@Whitelisted
public String getCredentialsId() {
return credentialsId;
}
@Whitelisted
public void setCredentialsId(String credentialsId) {
this.credentialsId = credentialsId;
this.password = "";
this.username = "";
this.usesCredentialsId = true;
}
@Whitelisted
public Connection getConnection() {
return connection;
}
@Whitelisted
public int getDeploymentThreads() {
return deploymentThreads;
}
@Whitelisted
public void setDeploymentThreads(int deploymentThreads) {
this.deploymentThreads = deploymentThreads;
}
}
| {
"content_hash": "a2af739c56d8bfa87ba92460879cb829",
"timestamp": "",
"source": "github",
"line_count": 335,
"max_line_length": 124,
"avg_line_length": 33.40597014925373,
"alnum_prop": 0.6918952729872219,
"repo_name": "AlexeiVainshtein/jenkins-artifactory-plugin",
"id": "2ab71e8f616a0077c2ab5dad8dcbc218ef408425",
"size": "11191",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/jfrog/hudson/pipeline/common/types/ArtifactoryServer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "119"
},
{
"name": "HTML",
"bytes": "35372"
},
{
"name": "Java",
"bytes": "1133218"
},
{
"name": "JavaScript",
"bytes": "37192"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Detail view of selector.php</title>
<link rel="stylesheet" href="../../sample.css" type="text/css">
<link rel="stylesheet" href="../../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../../';
subdir='tests/simpletest';
filename='selector.php.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h2 class="details-heading"><a href="./index.html">/tests/simpletest/</a> -> <a href="selector.php.source.html">selector.php</a> (summary)</h2>
<div class="details-summary">
<p class="viewlinks">[<a href="selector.php.source.html">Source view</a>]
[<a href="javascript:window.print();">Print</a>]
[<a href="../../_stats.html">Project Stats</a>]</p>
<p><b>Base include file for SimpleTest.</b></p>
<table>
<tr><td align="right">Version: </td><td>$Id: selector.php 1786 2008-04-26 17:32:20Z pp11 $</td></tr>
<tr><td align="right">File Size: </td><td>141 lines (3 kb)</td></tr>
<tr><td align="right">Included or required:</td><td>0 times</td></tr>
<tr><td align="right" valign="top">Referenced: </td><td>0 times</td></tr>
<tr><td align="right" valign="top">Includes or requires: </td><td>0 files</td></tr>
</table>
<h3>Defines 4 classes</h3>
<div class="inset">
<p><b>SimpleByName::</b> (3 methods):<br>
<a href="#__construct">__construct</a>()<br>
<a href="#getname">getName</a>()<br>
<a href="#ismatch">isMatch</a>()<br>
</p>
<p><b>SimpleByLabel::</b> (2 methods):<br>
<a href="#__construct">__construct</a>()<br>
<a href="#ismatch">isMatch</a>()<br>
</p>
<p><b>SimpleById::</b> (2 methods):<br>
<a href="#__construct">__construct</a>()<br>
<a href="#ismatch">isMatch</a>()<br>
</p>
<p><b>SimpleByLabelOrName::</b> (2 methods):<br>
<a href="#__construct">__construct</a>()<br>
<a href="#ismatch">isMatch</a>()<br>
</p>
</div>
</div>
<br><div class="details-funclist">
<div class="details-classinfo">
<p class="details-classtitle">Class: <a name="simplebyname"><b>SimpleByName</b></a> - <a href="../../_classes/simplebyname.html"><small>X-Ref</small></a>
</p>
<b>Used to extract form elements for testing against.<BR>
Searches by name attribute.<BR>
</b><br>
<div class="inset"><table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="__construct" onClick="logFunction('__construct', 'selector.php.source.html#l25')" href="selector.php.source.html#l25">__construct</a>(<a href="../../_variables/name.html">$name</a>)
<a href="../../_functions/__construct.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Stashes the name for later comparison.<BR>
</b><BR><b>param:</b> string $name Name attribute to match.<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="getname" onClick="logFunction('getname', 'selector.php.source.html#l33')" href="selector.php.source.html#l33">getName</a>()
<a href="../../_functions/getname.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Accessor for name.<BR>
</b><BR><b>returns:</b> string $name Name to match.<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="ismatch" onClick="logFunction('ismatch', 'selector.php.source.html#l41')" href="selector.php.source.html#l41">isMatch</a>(<a href="../../_variables/widget.html">$widget</a>)
<a href="../../_functions/ismatch.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Compares with name attribute of widget.<BR>
</b><BR><b>param:</b> SimpleWidget $widget Control to compare.<br>
</td></tr></table>
<br>
</div>
</div>
<div class="details-classinfo">
<p class="details-classtitle">Class: <a name="simplebylabel"><b>SimpleByLabel</b></a> - <a href="../../_classes/simplebylabel.html"><small>X-Ref</small></a>
</p>
<b>Used to extract form elements for testing against.<BR>
Searches by visible label or alt text.<BR>
</b><br>
<div class="inset"><table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="__construct" onClick="logFunction('__construct', 'selector.php.source.html#l60')" href="selector.php.source.html#l60">__construct</a>(<a href="../../_variables/label.html">$label</a>)
<a href="../../_functions/__construct.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Stashes the name for later comparison.<BR>
</b><BR><b>param:</b> string $label Visible text to match.<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="ismatch" onClick="logFunction('ismatch', 'selector.php.source.html#l68')" href="selector.php.source.html#l68">isMatch</a>(<a href="../../_variables/widget.html">$widget</a>)
<a href="../../_functions/ismatch.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Comparison. Compares visible text of widget or<BR>
related label.<BR>
</b><BR><b>param:</b> SimpleWidget $widget Control to compare.<br>
</td></tr></table>
<br>
</div>
</div>
<div class="details-classinfo">
<p class="details-classtitle">Class: <a name="simplebyid"><b>SimpleById</b></a> - <a href="../../_classes/simplebyid.html"><small>X-Ref</small></a>
</p>
<b>Used to extract form elements for testing against.<BR>
Searches dy id attribute.<BR>
</b><br>
<div class="inset"><table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="__construct" onClick="logFunction('__construct', 'selector.php.source.html#l91')" href="selector.php.source.html#l91">__construct</a>(<a href="../../_variables/id.html">$id</a>)
<a href="../../_functions/__construct.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Stashes the name for later comparison.<BR>
</b><BR><b>param:</b> string $id ID atribute to match.<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="ismatch" onClick="logFunction('ismatch', 'selector.php.source.html#l99')" href="selector.php.source.html#l99">isMatch</a>(<a href="../../_variables/widget.html">$widget</a>)
<a href="../../_functions/ismatch.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Comparison. Compares id attribute of widget.<BR>
</b><BR><b>param:</b> SimpleWidget $widget Control to compare.<br>
</td></tr></table>
<br>
</div>
</div>
<div class="details-classinfo">
<p class="details-classtitle">Class: <a name="simplebylabelorname"><b>SimpleByLabelOrName</b></a> - <a href="../../_classes/simplebylabelorname.html"><small>X-Ref</small></a>
</p>
<b>Used to extract form elements for testing against.<BR>
Searches by visible label, name or alt text.<BR>
</b><br>
<div class="inset"><table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="__construct" onClick="logFunction('__construct', 'selector.php.source.html#l118')" href="selector.php.source.html#l118">__construct</a>(<a href="../../_variables/label.html">$label</a>)
<a href="../../_functions/__construct.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Stashes the name/label for later comparison.<BR>
</b><BR><b>param:</b> string $label Visible text to match.<br>
</td></tr></table>
<br>
<table border="0" width="80%" class="funcinfo"><tr class="funcinfo-title"><td>
<a name="ismatch" onClick="logFunction('ismatch', 'selector.php.source.html#l126')" href="selector.php.source.html#l126">isMatch</a>(<a href="../../_variables/widget.html">$widget</a>)
<a href="../../_functions/ismatch.html"><small>X-Ref</small></a>
</td></tr><tr class="funcinfo-body"><td><b>Comparison. Compares visible text of widget or<BR>
related label or name.<BR>
</b><BR><b>param:</b> SimpleWidget $widget Control to compare.<br>
</td></tr></table>
<br>
</div>
</div>
</div>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "761e9370b2a2b8acd9633c17645b26f9",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 253,
"avg_line_length": 52.790393013100434,
"alnum_prop": 0.6620067830258913,
"repo_name": "inputx/code-ref-doc",
"id": "f4df5f30ea7b3c9c769b6e620c2fb15368acc7c3",
"size": "12089",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bonfire/tests/simpletest/selector.php.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_222) on Thu Jan 16 21:49:29 PST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Deprecated List (datasketches-java 1.2.0-incubating API)</title>
<meta name="date" content="2020-01-16">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Deprecated List (datasketches-java 1.2.0-incubating API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Deprecated API" class="title">Deprecated API</h1>
<h2 title="Contents">Contents</h2>
<ul>
<li><a href="#method">Deprecated Methods</a></li>
<li><a href="#constructor">Deprecated Constructors</a></li>
</ul>
</div>
<div class="contentContainer"><a name="method">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Methods table, listing deprecated methods, and an explanation">
<caption><span>Deprecated Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/kll/KllFloatsSketch.html#getNormalizedRankError--">org.apache.datasketches.kll.KllFloatsSketch.getNormalizedRankError()</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/kll/KllFloatsSketch.html#getNormalizedRankError-boolean-"><code>KllFloatsSketch.getNormalizedRankError(boolean)</code></a></span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesSketch.html#getNormalizedRankError--">org.apache.datasketches.quantiles.DoublesSketch.getNormalizedRankError()</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/quantiles/DoublesSketch.html#getNormalizedRankError-boolean-"><code>DoublesSketch.getNormalizedRankError(boolean)</code></a></span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/ItemsSketch.html#getNormalizedRankError--">org.apache.datasketches.quantiles.ItemsSketch.getNormalizedRankError()</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/quantiles/ItemsSketch.html#getNormalizedRankError-boolean-"><code>getNormalizedRankError(boolean)</code></a></span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/kll/KllFloatsSketch.html#getNormalizedRankError-int-">org.apache.datasketches.kll.KllFloatsSketch.getNormalizedRankError(int)</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/kll/KllFloatsSketch.html#getNormalizedRankError-int-boolean-"><code>KllFloatsSketch.getNormalizedRankError(int, boolean)</code></a></span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesSketch.html#getNormalizedRankError-int-">org.apache.datasketches.quantiles.DoublesSketch.getNormalizedRankError(int)</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/quantiles/DoublesSketch.html#getNormalizedRankError-int-boolean-"><code>DoublesSketch.getNormalizedRankError(int, boolean)</code></a></span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/ItemsSketch.html#getNormalizedRankError-int-">org.apache.datasketches.quantiles.ItemsSketch.getNormalizedRankError(int)</a>
<div class="block"><span class="deprecationComment">replaced by <a href="org/apache/datasketches/quantiles/ItemsSketch.html#getNormalizedRankError-int-boolean-"><code>getNormalizedRankError(int, boolean)</code></a></span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesUnionBuilder.html#heapify-org.apache.datasketches.quantiles.DoublesSketch-">org.apache.datasketches.quantiles.DoublesUnionBuilder.heapify(DoublesSketch)</a>
<div class="block"><span class="deprecationComment">moved to DoublesUnion</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesUnionBuilder.html#heapify-org.apache.datasketches.memory.Memory-">org.apache.datasketches.quantiles.DoublesUnionBuilder.heapify(Memory)</a>
<div class="block"><span class="deprecationComment">moved to DoublesUnion</span></div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesUnionBuilder.html#wrap-org.apache.datasketches.memory.Memory-">org.apache.datasketches.quantiles.DoublesUnionBuilder.wrap(Memory)</a>
<div class="block"><span class="deprecationComment">moved to DoublesUnion</span></div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/quantiles/DoublesUnionBuilder.html#wrap-org.apache.datasketches.memory.WritableMemory-">org.apache.datasketches.quantiles.DoublesUnionBuilder.wrap(WritableMemory)</a>
<div class="block"><span class="deprecationComment">moved to DoublesUnion</span></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="constructor">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<table class="deprecatedSummary" border="0" cellpadding="3" cellspacing="0" summary="Deprecated Constructors table, listing deprecated constructors, and an explanation">
<caption><span>Deprecated Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="org/apache/datasketches/tuple/adouble/DoubleSummaryFactory.html#DoubleSummaryFactory--">org.apache.datasketches.tuple.adouble.DoubleSummaryFactory()</a></td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="org/apache/datasketches/tuple/adouble/DoubleSummarySetOperations.html#DoubleSummarySetOperations--">org.apache.datasketches.tuple.adouble.DoubleSummarySetOperations()</a></td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li class="navBarCell1Rev">Deprecated</li>
<li><a href="index-all.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?deprecated-list.html" target="_top">Frames</a></li>
<li><a href="deprecated-list.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015–2020 <a href="https://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "e56c83155450daf0981856d5cce41e1b",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 243,
"avg_line_length": 43.20276497695853,
"alnum_prop": 0.7163733333333333,
"repo_name": "DataSketches/DataSketches.github.io",
"id": "185a0e7cd11f3c5e4ae5958555971f6131cb57cd",
"size": "9375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/java/snapshot/apidocs/deprecated-list.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "64477"
},
{
"name": "HTML",
"bytes": "12421865"
},
{
"name": "Java",
"bytes": "59928"
},
{
"name": "JavaScript",
"bytes": "3308"
},
{
"name": "Ruby",
"bytes": "8155"
}
],
"symlink_target": ""
} |
package ch.scaille.example.gui.model;
import ch.scaille.tcwriter.pilot.swing.ByName;
import ch.scaille.tcwriter.pilot.swing.JTablePilot;
import ch.scaille.tcwriter.pilot.swing.JToggleButtonPilot;
import ch.scaille.tcwriter.pilot.swing.PagePilot;
import ch.scaille.tcwriter.pilot.swing.SwingPilot;
public class ModelExamplePage extends PagePilot {
@ByName("reverseOrder")
public JToggleButtonPilot reverseOrder = null;
@ByName("enableFilter")
public JToggleButtonPilot enableFilter = null;
@ByName("listTable")
public JTablePilot listTable = null;
public ModelExamplePage(SwingPilot pilot) {
super(pilot);
}
}
| {
"content_hash": "b239efccd54445844bc4a50d1886a2c3",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 58,
"avg_line_length": 27.17391304347826,
"alnum_prop": 0.8016,
"repo_name": "sebastiencaille/sky-lib",
"id": "768b7bdce024ed13486ea91030d328c646fcabd2",
"size": "625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "skylib-java/lib-gui-examples/src/test/java/ch/scaille/example/gui/model/ModelExamplePage.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "78806"
},
{
"name": "CSS",
"bytes": "1034"
},
{
"name": "HTML",
"bytes": "1984"
},
{
"name": "Java",
"bytes": "927160"
},
{
"name": "JavaScript",
"bytes": "1430"
},
{
"name": "Makefile",
"bytes": "8699"
},
{
"name": "Shell",
"bytes": "59"
},
{
"name": "TypeScript",
"bytes": "13601"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GX.IO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("GX.IO")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("aac1d9dc-6e82-4eab-94a4-5f03972dd022")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "09b4fb6ff1a29d1c7e53f541f56160ba",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.916666666666664,
"alnum_prop": 0.7444682369735903,
"repo_name": "gongxiancao/open-productivity",
"id": "83ad77f717b61d507371565402840502222e389b",
"size": "1404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "products/framework/GX.IO/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "120739"
}
],
"symlink_target": ""
} |
import { expect } from "chai";
import { parseXSD } from "../../src/util/SAXParser";
describe("SAXParser", function () {
it("basic", function () {
const x = parseXSD(xml);
expect(x).to.exist;
expect(x.root).to.exist;
expect(x.simpleTypes).to.exist;
});
});
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:hpcc="urn:hpccsystems:xsd:appinfo" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="Dataset">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="Row">
<xs:complexType>
<xs:sequence>
<xs:element name="personid" type="xs:nonNegativeInteger" />
<xs:element name="firstname" type="string15" />
<xs:element name="lastname" type="string25" />
<xs:element name="middleinitial" type="string1" />
<xs:element name="gender" type="string1" />
<xs:element name="street" type="string42" />
<xs:element name="city" type="string20" />
<xs:element name="state" type="string2" />
<xs:element name="zip" type="string5" />
<xs:element name="accounts">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="unbounded">
<xs:element name="Row">
<xs:complexType>
<xs:sequence>
<xs:element name="account" type="string20" />
<xs:element name="opendate" type="string8" />
<xs:element name="industrycode" type="string2" />
<xs:element name="accttype" type="string1" />
<xs:element name="acctrate" type="string1" />
<xs:element name="code1" type="xs:nonNegativeInteger" />
<xs:element name="code2" type="xs:nonNegativeInteger" />
<xs:element name="highcredit" type="xs:nonNegativeInteger" />
<xs:element name="balance" type="xs:nonNegativeInteger" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="__fileposition__" type="xs:nonNegativeInteger" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:simpleType name="string15">
<xs:restriction base="xs:string">
<xs:maxLength value="15" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string25">
<xs:restriction base="xs:string">
<xs:maxLength value="25" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string1">
<xs:restriction base="xs:string">
<xs:maxLength value="1" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string42">
<xs:restriction base="xs:string">
<xs:maxLength value="42" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string20">
<xs:restriction base="xs:string">
<xs:maxLength value="20" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string2">
<xs:restriction base="xs:string">
<xs:maxLength value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string5">
<xs:restriction base="xs:string">
<xs:maxLength value="5" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="string8">
<xs:restriction base="xs:string">
<xs:maxLength value="8" />
</xs:restriction>
</xs:simpleType>
</xs:schema>`;
| {
"content_hash": "b03d8ce8f02c0aa58110645ff3bfecb2",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 162,
"avg_line_length": 42.888888888888886,
"alnum_prop": 0.4943476212906265,
"repo_name": "GordonSmith/hpcc-platform-comms",
"id": "81320afe5189d40160194b595b40fb6e751bab3c",
"size": "4246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/util/SAXParser.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "861"
},
{
"name": "JavaScript",
"bytes": "4159"
},
{
"name": "TypeScript",
"bytes": "122446"
}
],
"symlink_target": ""
} |
namespace Meta.ParsingAndPrinting
{
/// <summary>
/// Represents physical directions. Used by rooms to keep track of adjacent/adjoining rooms.
/// </summary>
public enum Direction { north, east, south, west, northeast, southeast, northwest, southwest, up, down };
/// <summary>
/// Indicates whether a given <see cref="Effect"/> changes the property it
/// affects by setting it equal to a new value or by adding to it.
/// </summary>
public enum EffectType { equality, addition };
/// <summary>
/// Indicates whether a given <see cref="Effect"/> lasts indefinately or
/// for a set number of turns.
/// </summary>
public enum EffectDuration { permanent, turns }
public enum ClothingSlot { socks, shoes, tights, underpants, pants, skirt, undershirt, shirt, cincher, jacket, ring, bracelet, necklace, gloves, hat, glasses }
} | {
"content_hash": "82537a98d66ac3c341f2279070c35f52",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 160,
"avg_line_length": 41.095238095238095,
"alnum_prop": 0.694090382387022,
"repo_name": "julia-ford/Game-Engine",
"id": "78c297d739278cf7a14672a81cba4476e9e7191f",
"size": "865",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "GameEngineJuly2013/Meta/ParsingAndPrinting/Enums.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "322870"
}
],
"symlink_target": ""
} |
// Copyright 2015-2020 Espressif Systems (Shanghai) PTE 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.
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "unity.h"
#include "test_utils.h"
#include "test_hcd_common.h"
#define TEST_DEV_ADDR 0
#define NUM_URBS 3
#define TRANSFER_MAX_BYTES 256
#define URB_DATA_BUFF_SIZE (sizeof(usb_setup_packet_t) + TRANSFER_MAX_BYTES) //256 is worst case size for configuration descriptors
/*
Test HCD control pipe URBs (normal completion and early abort)
Purpose:
- Test that a control pipe can be created
- URBs can be created and enqueued to the control pipe
- Control pipe returns HCD_PIPE_EVENT_URB_DONE
- Test that URBs can be aborted when enqueued
Procedure:
- Setup HCD and wait for connection
- Setup default pipe and allocate URBs
- Enqueue URBs
- Expect HCD_PIPE_EVENT_URB_DONE
- Requeue URBs, but abort them immediately
- Expect URB to be USB_TRANSFER_STATUS_CANCELED or USB_TRANSFER_STATUS_COMPLETED
- Teardown
*/
TEST_CASE("Test HCD control pipe URBs", "[hcd][ignore]")
{
hcd_port_handle_t port_hdl = test_hcd_setup(); //Setup the HCD and port
usb_speed_t port_speed = test_hcd_wait_for_conn(port_hdl); //Trigger a connection
vTaskDelay(pdMS_TO_TICKS(100)); //Short delay send of SOF (for FS) or EOPs (for LS)
//Allocate some URBs and initialize their data buffers with control transfers
hcd_pipe_handle_t default_pipe = test_hcd_pipe_alloc(port_hdl, NULL, TEST_DEV_ADDR, port_speed); //Create a default pipe (using a NULL EP descriptor)
urb_t *urb_list[NUM_URBS];
for (int i = 0; i < NUM_URBS; i++) {
urb_list[i] = test_hcd_alloc_urb(0, URB_DATA_BUFF_SIZE);
//Initialize with a "Get Config Descriptor request"
urb_list[i]->transfer.num_bytes = sizeof(usb_setup_packet_t) + TRANSFER_MAX_BYTES;
USB_SETUP_PACKET_INIT_GET_CONFIG_DESC((usb_setup_packet_t *)urb_list[i]->transfer.data_buffer, 0, TRANSFER_MAX_BYTES);
urb_list[i]->transfer.context = URB_CONTEXT_VAL;
}
//Enqueue URBs but immediately suspend the port
printf("Enqueuing URBs\n");
for (int i = 0; i < NUM_URBS; i++) {
TEST_ASSERT_EQUAL(ESP_OK, hcd_urb_enqueue(default_pipe, urb_list[i]));
}
//Wait for each done event of each URB
for (int i = 0; i < NUM_URBS; i++) {
test_hcd_expect_pipe_event(default_pipe, HCD_PIPE_EVENT_URB_DONE);
}
//Dequeue URBs, check, and print
for (int i = 0; i < NUM_URBS; i++) {
urb_t *urb = hcd_urb_dequeue(default_pipe);
TEST_ASSERT_EQUAL(urb_list[i], urb);
TEST_ASSERT_EQUAL(USB_TRANSFER_STATUS_COMPLETED, urb->transfer.status);
TEST_ASSERT_EQUAL(URB_CONTEXT_VAL, urb->transfer.context);
//We must have transmitted at least the setup packet, but device may return less than bytes requested
TEST_ASSERT_GREATER_OR_EQUAL(sizeof(usb_setup_packet_t), urb->transfer.actual_num_bytes);
TEST_ASSERT_LESS_OR_EQUAL(urb->transfer.num_bytes, urb->transfer.actual_num_bytes);
usb_config_desc_t *config_desc = (usb_config_desc_t *)(urb->transfer.data_buffer + sizeof(usb_setup_packet_t));
TEST_ASSERT_EQUAL(USB_B_DESCRIPTOR_TYPE_CONFIGURATION , config_desc->bDescriptorType);
printf("Config Desc wTotalLength %d\n", config_desc->wTotalLength);
}
//Enqueue URBs again but abort them short after
for (int i = 0; i < NUM_URBS; i++) {
TEST_ASSERT_EQUAL(ESP_OK, hcd_urb_enqueue(default_pipe, urb_list[i]));
}
for (int i = 0; i < NUM_URBS; i++) {
TEST_ASSERT_EQUAL(ESP_OK, hcd_urb_abort(urb_list[i]));
}
vTaskDelay(pdMS_TO_TICKS(100)); //Give some time for any inflight transfers to complete
//Wait for the URBs to complete and dequeue them, then check results
//Dequeue URBs
for (int i = 0; i < NUM_URBS; i++) {
urb_t *urb = hcd_urb_dequeue(default_pipe);
//No need to check for URB pointer address as they may be out of order
TEST_ASSERT(urb->transfer.status == USB_TRANSFER_STATUS_COMPLETED || urb->transfer.status == USB_TRANSFER_STATUS_CANCELED);
if (urb->transfer.status == USB_TRANSFER_STATUS_COMPLETED) {
//We must have transmitted at least the setup packet, but device may return less than bytes requested
TEST_ASSERT_GREATER_OR_EQUAL(sizeof(usb_setup_packet_t), urb->transfer.actual_num_bytes);
TEST_ASSERT_LESS_OR_EQUAL(urb->transfer.num_bytes, urb->transfer.actual_num_bytes);
} else {
//A failed transfer should 0 actual number of bytes transmitted
TEST_ASSERT_EQUAL(0, urb->transfer.actual_num_bytes);
}
TEST_ASSERT_EQUAL(urb->transfer.context, URB_CONTEXT_VAL);
}
//Free URB list and pipe
for (int i = 0; i < NUM_URBS; i++) {
test_hcd_free_urb(urb_list[i]);
}
test_hcd_pipe_free(default_pipe);
//Cleanup
test_hcd_wait_for_disconn(port_hdl, false);
test_hcd_teardown(port_hdl);
}
/*
Test HCD control pipe STALL condition, abort, and clear
Purpose:
- Test that a control pipe can react to a STALL (i.e., a HCD_PIPE_EVENT_ERROR_STALL event)
- The HCD_PIPE_CMD_FLUSH can retire all URBs
- Pipe clear command can return the pipe to being active
Procedure:
- Setup HCD and wait for connection
- Setup default pipe and allocate URBs
- Corrupt the first URB so that it will trigger a STALL, then enqueue all the URBs
- Check that a HCD_PIPE_EVENT_ERROR_STALL event is triggered
- Check that all URBs can be retired using HCD_PIPE_CMD_FLUSH, a HCD_PIPE_EVENT_URB_DONE event should be generated
- Check that the STALL can be cleared by using HCD_PIPE_CMD_CLEAR
- Fix the corrupt first URB and retry the URBs
- Dequeue URBs
- Teardown
*/
TEST_CASE("Test HCD control pipe STALL", "[hcd][ignore]")
{
hcd_port_handle_t port_hdl = test_hcd_setup(); //Setup the HCD and port
usb_speed_t port_speed = test_hcd_wait_for_conn(port_hdl); //Trigger a connection
vTaskDelay(pdMS_TO_TICKS(100)); //Short delay send of SOF (for FS) or EOPs (for LS)
//Allocate some URBs and initialize their data buffers with control transfers
hcd_pipe_handle_t default_pipe = test_hcd_pipe_alloc(port_hdl, NULL, TEST_DEV_ADDR, port_speed); //Create a default pipe (using a NULL EP descriptor)
urb_t *urb_list[NUM_URBS];
for (int i = 0; i < NUM_URBS; i++) {
urb_list[i] = test_hcd_alloc_urb(0, URB_DATA_BUFF_SIZE);
//Initialize with a "Get Config Descriptor request"
urb_list[i]->transfer.num_bytes = sizeof(usb_setup_packet_t) + TRANSFER_MAX_BYTES;
USB_SETUP_PACKET_INIT_GET_CONFIG_DESC((usb_setup_packet_t *)urb_list[i]->transfer.data_buffer, 0, TRANSFER_MAX_BYTES);
urb_list[i]->transfer.context = URB_CONTEXT_VAL;
}
//Corrupt the first URB so that it triggers a STALL
((usb_setup_packet_t *)urb_list[0]->transfer.data_buffer)->bRequest = 0xAA;
//Enqueue URBs. A STALL should occur
int num_enqueued = 0;
for (int i = 0; i < NUM_URBS; i++) {
if (hcd_urb_enqueue(default_pipe, urb_list[i]) != ESP_OK) {
//STALL may occur before we are done enqueing
break;
}
num_enqueued++;
}
TEST_ASSERT_GREATER_THAN(0, num_enqueued);
printf("Expecting STALL\n");
test_hcd_expect_pipe_event(default_pipe, HCD_PIPE_EVENT_ERROR_STALL);
TEST_ASSERT_EQUAL(HCD_PIPE_STATE_HALTED, hcd_pipe_get_state(default_pipe));
//Call the pipe abort command to retire all URBs then dequeue them all
TEST_ASSERT_EQUAL(ESP_OK, hcd_pipe_command(default_pipe, HCD_PIPE_CMD_FLUSH));
test_hcd_expect_pipe_event(default_pipe, HCD_PIPE_EVENT_URB_DONE);
for (int i = 0; i < num_enqueued; i++) {
urb_t *urb = hcd_urb_dequeue(default_pipe);
TEST_ASSERT_EQUAL(urb_list[i], urb);
TEST_ASSERT(urb->transfer.status == USB_TRANSFER_STATUS_STALL || urb->transfer.status == USB_TRANSFER_STATUS_CANCELED);
if (urb->transfer.status == USB_TRANSFER_STATUS_COMPLETED) {
//We must have transmitted at least the setup packet, but device may return less than bytes requested
TEST_ASSERT_GREATER_OR_EQUAL(sizeof(usb_setup_packet_t), urb->transfer.actual_num_bytes);
TEST_ASSERT_LESS_OR_EQUAL(urb->transfer.num_bytes, urb->transfer.actual_num_bytes);
} else {
//A failed transfer should 0 actual number of bytes transmitted
TEST_ASSERT_EQUAL(0, urb->transfer.actual_num_bytes);
}
TEST_ASSERT_EQUAL(URB_CONTEXT_VAL, urb->transfer.context);
}
//Call the clear command to un-stall the pipe
TEST_ASSERT_EQUAL(ESP_OK, hcd_pipe_command(default_pipe, HCD_PIPE_CMD_CLEAR));
TEST_ASSERT_EQUAL(HCD_PIPE_STATE_ACTIVE, hcd_pipe_get_state(default_pipe));
printf("Retrying\n");
//Correct first URB then requeue
USB_SETUP_PACKET_INIT_GET_CONFIG_DESC((usb_setup_packet_t *)urb_list[0]->transfer.data_buffer, 0, TRANSFER_MAX_BYTES);
for (int i = 0; i < NUM_URBS; i++) {
TEST_ASSERT_EQUAL(ESP_OK, hcd_urb_enqueue(default_pipe, urb_list[i]));
}
//Wait for each URB to be done, deequeue, and check results
for (int i = 0; i < NUM_URBS; i++) {
test_hcd_expect_pipe_event(default_pipe, HCD_PIPE_EVENT_URB_DONE);
//expect_pipe_event(pipe_evt_queue, default_pipe, HCD_PIPE_EVENT_URB_DONE);
urb_t *urb = hcd_urb_dequeue(default_pipe);
TEST_ASSERT_EQUAL(urb_list[i], urb);
TEST_ASSERT_EQUAL(USB_TRANSFER_STATUS_COMPLETED, urb->transfer.status);
TEST_ASSERT_EQUAL(URB_CONTEXT_VAL, urb->transfer.context);
//We must have transmitted at least the setup packet, but device may return less than bytes requested
TEST_ASSERT_GREATER_OR_EQUAL(sizeof(usb_setup_packet_t), urb->transfer.actual_num_bytes);
TEST_ASSERT_LESS_OR_EQUAL(urb->transfer.num_bytes, urb->transfer.actual_num_bytes);
usb_config_desc_t *config_desc = (usb_config_desc_t *)(urb->transfer.data_buffer + sizeof(usb_setup_packet_t));
TEST_ASSERT_EQUAL(USB_B_DESCRIPTOR_TYPE_CONFIGURATION , config_desc->bDescriptorType);
printf("Config Desc wTotalLength %d\n", config_desc->wTotalLength);
}
//Free URB list and pipe
for (int i = 0; i < NUM_URBS; i++) {
test_hcd_free_urb(urb_list[i]);
}
test_hcd_pipe_free(default_pipe);
//Cleanup
test_hcd_wait_for_disconn(port_hdl, false);
test_hcd_teardown(port_hdl);
}
/*
Test control pipe run-time halt and clear
Purpose:
- Test that a control pipe can be halted with HCD_PIPE_CMD_HALT whilst there are ongoing URBs
- Test that a control pipe can be un-halted with a HCD_PIPE_CMD_CLEAR
- Test that enqueued URBs are resumed when pipe is un-halted
Procedure:
- Setup HCD and wait for connection
- Setup default pipe and allocate URBs
- Enqqueue URBs but execute a HCD_PIPE_CMD_HALT command immediately after.
- Halt command should immediately halt the current URB and generate a HCD_PIPE_EVENT_URB_DONE
- Other pending URBs should be untouched.
- Un-halt the pipe using a HCD_PIPE_CMD_CLEAR command. Enqueued URBs will be resumed
- Check that all URBs have completed successfully
- Dequeue URBs and teardown
*/
TEST_CASE("Test HCD control pipe runtime halt and clear", "[hcd][ignore]")
{
hcd_port_handle_t port_hdl = test_hcd_setup(); //Setup the HCD and port
usb_speed_t port_speed = test_hcd_wait_for_conn(port_hdl); //Trigger a connection
vTaskDelay(pdMS_TO_TICKS(100)); //Short delay send of SOF (for FS) or EOPs (for LS)
//Allocate some URBs and initialize their data buffers with control transfers
hcd_pipe_handle_t default_pipe = test_hcd_pipe_alloc(port_hdl, NULL, TEST_DEV_ADDR, port_speed); //Create a default pipe (using a NULL EP descriptor)
urb_t *urb_list[NUM_URBS];
for (int i = 0; i < NUM_URBS; i++) {
urb_list[i] = test_hcd_alloc_urb(0, URB_DATA_BUFF_SIZE);
//Initialize with a "Get Config Descriptor request"
urb_list[i]->transfer.num_bytes = sizeof(usb_setup_packet_t) + TRANSFER_MAX_BYTES;
USB_SETUP_PACKET_INIT_GET_CONFIG_DESC((usb_setup_packet_t *)urb_list[i]->transfer.data_buffer, 0, TRANSFER_MAX_BYTES);
urb_list[i]->transfer.context = URB_CONTEXT_VAL;
}
//Enqueue URBs but immediately halt the pipe
printf("Enqueuing URBs\n");
for (int i = 0; i < NUM_URBS; i++) {
TEST_ASSERT_EQUAL(ESP_OK, hcd_urb_enqueue(default_pipe, urb_list[i]));
}
TEST_ASSERT_EQUAL(ESP_OK, hcd_pipe_command(default_pipe, HCD_PIPE_CMD_HALT));
test_hcd_expect_pipe_event(default_pipe, HCD_PIPE_EVENT_URB_DONE);
TEST_ASSERT_EQUAL(HCD_PIPE_STATE_HALTED, hcd_pipe_get_state(default_pipe));
printf("Pipe halted\n");
//Un-halt the pipe
TEST_ASSERT_EQUAL(ESP_OK, hcd_pipe_command(default_pipe, HCD_PIPE_CMD_CLEAR));
TEST_ASSERT_EQUAL(HCD_PIPE_STATE_ACTIVE, hcd_pipe_get_state(default_pipe));
printf("Pipe cleared\n");
vTaskDelay(pdMS_TO_TICKS(100)); //Give some time pending for transfers to restart and complete
//Wait for each URB to be done, dequeue, and check results
for (int i = 0; i < NUM_URBS; i++) {
urb_t *urb = hcd_urb_dequeue(default_pipe);
TEST_ASSERT_EQUAL(urb_list[i], urb);
TEST_ASSERT(urb->transfer.status == USB_TRANSFER_STATUS_COMPLETED || urb->transfer.status == USB_TRANSFER_STATUS_CANCELED);
if (urb->transfer.status == USB_TRANSFER_STATUS_COMPLETED) {
//We must have transmitted at least the setup packet, but device may return less than bytes requested
TEST_ASSERT_GREATER_OR_EQUAL(sizeof(usb_setup_packet_t), urb->transfer.actual_num_bytes);
TEST_ASSERT_LESS_OR_EQUAL(urb->transfer.num_bytes, urb->transfer.actual_num_bytes);
usb_config_desc_t *config_desc = (usb_config_desc_t *)(urb->transfer.data_buffer + sizeof(usb_setup_packet_t));
TEST_ASSERT_EQUAL(USB_B_DESCRIPTOR_TYPE_CONFIGURATION , config_desc->bDescriptorType);
printf("Config Desc wTotalLength %d\n", config_desc->wTotalLength);
} else {
//A failed transfer should 0 actual number of bytes transmitted
TEST_ASSERT_EQUAL(0, urb->transfer.actual_num_bytes);
}
TEST_ASSERT_EQUAL(URB_CONTEXT_VAL, urb->transfer.context);
}
//Free URB list and pipe
for (int i = 0; i < NUM_URBS; i++) {
test_hcd_free_urb(urb_list[i]);
}
test_hcd_pipe_free(default_pipe);
//Cleanup
test_hcd_wait_for_disconn(port_hdl, false);
test_hcd_teardown(port_hdl);
}
| {
"content_hash": "2550da7d286b1a9caaee92133950d1ca",
"timestamp": "",
"source": "github",
"line_count": 306,
"max_line_length": 153,
"avg_line_length": 49.754901960784316,
"alnum_prop": 0.6689655172413793,
"repo_name": "espressif/esp-idf",
"id": "678de453cae0469ecd8bc467ffe48f1c62db1cde",
"size": "15225",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/usb/test/hcd/test_hcd_ctrl.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "388440"
},
{
"name": "Batchfile",
"bytes": "5451"
},
{
"name": "C",
"bytes": "69102322"
},
{
"name": "C++",
"bytes": "992772"
},
{
"name": "CMake",
"bytes": "539972"
},
{
"name": "Dockerfile",
"bytes": "3290"
},
{
"name": "Makefile",
"bytes": "23747"
},
{
"name": "Nim",
"bytes": "1005"
},
{
"name": "PowerShell",
"bytes": "4537"
},
{
"name": "Python",
"bytes": "2158180"
},
{
"name": "Roff",
"bytes": "101"
},
{
"name": "Shell",
"bytes": "126143"
}
],
"symlink_target": ""
} |
LeptonThread::LeptonThread() : QThread() { }
LeptonThread::~LeptonThread() { }
void LeptonThread::run() {
left.Open(0);
right.Open(1);
// Note that cv::Mat is a wrapper to the underlying data representation -- we only build these once, and they point to our frame buffers.
leftImage = cv::Mat(ROWS_PER_FRAME, ROW_SIZE_UINT16, CV_16UC1, left.FrameBuffer);
rightImage = cv::Mat(ROWS_PER_FRAME, ROW_SIZE_UINT16, CV_16UC1, right.FrameBuffer);
disparityImage = QImage(80, 60, QImage::Format_RGB888);
// Note that execution is single-threaded; although either SPIReader may be mid-read, its FrameBuffer will always be complete with most-recent frame.
// We alternate between each camera, and rebuild the depth map each time a new frame is available.
while (true) {
if (left.Poll()) {
emit updateLeftImage(left.Image);
generateDepthMap();
}
if (right.Poll()) {
emit updateRightImage(right.Image);
generateDepthMap();
}
}
}
void LeptonThread::generateDepthMap() {
// Ensure we have at least one frame of data available on both sensors before generating the map.
if (!left.FrameBufferReady || !right.FrameBufferReady) return;
// StereoBM::operator() expects 8-bit, single-channel data, not 16-bit. Downsample.
// Allocate off the heap so it's cleaned up when we exit.
cv::Mat l = cv::Mat(ROWS_PER_FRAME, ROW_SIZE_UINT16, CV_8UC1);
cv::Mat r = cv::Mat(ROWS_PER_FRAME, ROW_SIZE_UINT16, CV_8UC1);
// Convert the 14-bit gamut linearly to 8-bit. Low-contrast.
leftImage.convertTo(l, CV_8UC1, 256.0/16384);
rightImage.convertTo(r, CV_8UC1, 256.0/16384);
// normalize(leftImage, l, 0, 255, CV_MINMAX, CV_8UC1);
// normalize(rightImage, r, 0, 255, CV_MINMAX, CV_8UC1);
// cv::StereoSGBM sbm = cv::StereoSGBM();
// sbm.numberOfDisparities = 16;
cv::StereoBM sbm = cv::StereoBM(cv::StereoBM::BASIC_PRESET, 32, 7);
cv::Mat disparityMap = cv::Mat(ROWS_PER_FRAME, ROW_SIZE_UINT16, CV_16UC1);
sbm(l, r, disparityMap); // CV_16SC1
normalize(disparityMap, disparityOutput, 0, 255, CV_MINMAX, CV_8UC1);
for (int y=0; y<disparityOutput.rows; y++) {
const uchar* rowptr = disparityOutput.ptr(y);
for (int x=0; x<disparityOutput.cols; x++) {
disparityImage.setPixel(x, y, qRgb(rowptr[x], rowptr[x], rowptr[x]));
}
}
emit updateCenterImage(disparityImage);
}
void LeptonThread::performFFC() {
lepton_perform_ffc();
}
void LeptonThread::toggleAGC() {
lepton_toggle_agc();
}
| {
"content_hash": "ff7a0b6a671ff349874b68b54c97a7b0",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 151,
"avg_line_length": 36.544117647058826,
"alnum_prop": 0.6865191146881288,
"repo_name": "xolalpay/UNLV-UAV-Controls-jriesen",
"id": "254005a15b7c6bc4bb16d3d23b194de79751cc33",
"size": "2512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lepton3D/LeptonThread.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "225259"
},
{
"name": "C++",
"bytes": "44778"
},
{
"name": "Makefile",
"bytes": "2597"
}
],
"symlink_target": ""
} |
package com.intellij.spellchecker.tokenizer;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import consulo.util.dataholder.Key;
import javax.annotation.Nonnull;
public abstract class EscapeSequenceTokenizer<T extends PsiElement> extends Tokenizer<T>
{
private static final Key<int[]> ESCAPE_OFFSETS = Key.create("escape.tokenizer.offsets");
public static void processTextWithOffsets(PsiElement element, TokenConsumer consumer, StringBuilder unescapedText,
int[] offsets, int startOffset)
{
if(element != null)
{
element.putUserData(ESCAPE_OFFSETS, offsets);
}
final String text = unescapedText.toString();
consumer.consumeToken(element, text, false, startOffset, TextRange.allOf(text), PlainTextSplitter.getInstance());
if(element != null)
{
element.putUserData(ESCAPE_OFFSETS, null);
}
}
@Override
@Nonnull
public TextRange getHighlightingRange(PsiElement element, int offset, TextRange range)
{
final int[] offsets = element.getUserData(ESCAPE_OFFSETS);
if(offsets != null)
{
int start = offsets[range.getStartOffset()];
int end = offsets[range.getEndOffset()];
return new TextRange(offset + start, offset + end);
}
return super.getHighlightingRange(element, offset, range);
}
}
| {
"content_hash": "847926efbb30fbf1940576a0897fcb63",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 115,
"avg_line_length": 32.04761904761905,
"alnum_prop": 0.7578008915304606,
"repo_name": "consulo/consulo-spellchecker",
"id": "dee01df83e09acd31558f1ce3f769ac31b1b98e3",
"size": "1487",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/intellij/spellchecker/tokenizer/EscapeSequenceTokenizer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "307"
},
{
"name": "Java",
"bytes": "221523"
}
],
"symlink_target": ""
} |
namespace blink {
class Document;
class DOMWrapperWorld;
class DummyPageHolder;
class ExecutionContext;
class LocalFrame;
class Page;
class ScriptStateForTesting : public ScriptState {
public:
static PassRefPtr<ScriptStateForTesting> create(v8::Local<v8::Context>,
PassRefPtr<DOMWrapperWorld>);
ExecutionContext* getExecutionContext() const override;
void setExecutionContext(ExecutionContext*) override;
private:
ScriptStateForTesting(v8::Local<v8::Context>, PassRefPtr<DOMWrapperWorld>);
Persistent<ExecutionContext> m_executionContext;
};
class V8TestingScope {
STACK_ALLOCATED();
public:
V8TestingScope();
ScriptState* getScriptState() const;
ExecutionContext* getExecutionContext() const;
v8::Isolate* isolate() const;
v8::Local<v8::Context> context() const;
ExceptionState& getExceptionState();
Page& page();
LocalFrame& frame();
Document& document();
~V8TestingScope();
private:
std::unique_ptr<DummyPageHolder> m_holder;
v8::HandleScope m_handleScope;
v8::Local<v8::Context> m_context;
v8::Context::Scope m_contextScope;
v8::TryCatch m_tryCatch;
DummyExceptionStateForTesting m_exceptionState;
};
} // namespace blink
#endif // V8BindingForTesting_h
| {
"content_hash": "9bf3055409757c8e0272dba66976d7fb",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 79,
"avg_line_length": 26.375,
"alnum_prop": 0.7322274881516587,
"repo_name": "google-ar/WebARonARCore",
"id": "919360003df8f9099e491bc42526f78f5b9b4ea5",
"size": "1653",
"binary": false,
"copies": "2",
"ref": "refs/heads/webarcore_57.0.2987.5",
"path": "third_party/WebKit/Source/bindings/core/v8/V8BindingForTesting.h",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b0145228282d2b112a8dc290465a92f8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "5558c0f7765841afae10ba886c366531b872492b",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Caesalpinia/Caesalpinia intricata/Caesalpinia intricata intricata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.usc.demo.synchronization;
import java.util.Arrays;
import java.util.List;
/**
* 以实例对象为锁对象的话,只要对象不同,就不会有同步锁,如果对象相同,才会有同步锁
*
* @author ShunLi
*/
public class SynchronizationTest2 {
public static void sync(String threadName, User user) {
String msg = threadName + ":" + user + ":";
System.out.println(msg + "sync1 start...");
synchronized (user) {
System.out.println(System.currentTimeMillis() + ":" + msg + "sync1 hit it");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(msg + "sync1 end...");
}
public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
User user3 = new User();
final List<User> users = Arrays.asList(user1, user2, user3);
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
public void run() {
String name = Thread.currentThread().getName();
// System.out.println(name);
sync(name, users.get((int) Thread.currentThread().getId() % 3));
}
}).start();
}
}
static class User {
private String userName;
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
}
| {
"content_hash": "4ee738233b294424b31010698a478a17",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 79,
"avg_line_length": 22.83076923076923,
"alnum_prop": 0.616576819407008,
"repo_name": "usc/demo",
"id": "6da1152e0f96f5ee9ca98be870367d1d2a65a43e",
"size": "1564",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/usc/demo/synchronization/SynchronizationTest2.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "195"
},
{
"name": "FreeMarker",
"bytes": "144"
},
{
"name": "HTML",
"bytes": "145"
},
{
"name": "Java",
"bytes": "964835"
}
],
"symlink_target": ""
} |
import unittest
class Node:
def __init__(self, item, next=None):
self.item = item
self.next = next
@property
def val(self):
return self.item
@val.setter
def val(self, value):
self.item = value
def __repr__(self):
tail = repr(self.next)
return f'Node({self.item!r}, {tail})'
class List:
def __init__(self, items=()):
head = None
prev = None
for item in items:
curr = Node(item)
if head is None:
head = curr
elif prev is None:
prev = head
if prev is not None:
prev.next = curr
prev = curr
self._head = head
@property
def head(self):
return self._head
@head.setter
def head(self, node):
self._head = node
def __len__(self):
length = 0
curr = self._head
while curr is not None:
length += 1
curr = curr.next
return length
def __iter__(self):
curr = self._head
while curr is not None:
yield curr.item
curr = curr.next
def __repr__(self):
contents = repr(list(self))
return f'List({contents})'
class _ListTest(unittest.TestCase):
def test_len(self):
ll = List()
self.assertEqual(0, len(ll))
ll = List(range(10))
self.assertEqual(10, len(ll))
def test_iter(self):
ll = List()
self.assertEqual([], list(ll))
ll = List(range(10))
self.assertEqual(list(range(10)), list(ll))
def test_repr(self):
ll = List()
self.assertEqual('List([])', repr(ll))
ll = List(range(3))
self.assertEqual('List([0, 1, 2])', repr(ll))
ll = List('abc')
self.assertEqual("List(['a', 'b', 'c'])", repr(ll))
| {
"content_hash": "be13a01743a996b6796f7138cefd0a47",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 59,
"avg_line_length": 21.976744186046513,
"alnum_prop": 0.4894179894179894,
"repo_name": "afbarnard/glowing-broccoli",
"id": "dc1c4637e1abec9ae7c71624df928a6cf9234f7f",
"size": "1945",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lc/linked.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "117209"
}
],
"symlink_target": ""
} |
namespace onnxruntime {
namespace cuda {
// kernel builder functions
#define NONZERO_TYPED_KERNEL_WITH_TYPE_NAME(type, type_name) \
ONNX_OPERATOR_VERSIONED_TYPED_KERNEL_EX( \
NonZero, \
kOnnxDomain, \
9, 12, \
type_name, \
kCudaExecutionProvider, \
(*KernelDefBuilder::Create()).TypeConstraint("T", DataTypeImpl::GetTensorType<type>()), \
NonZero<type>) \
ONNX_OPERATOR_TYPED_KERNEL_EX( \
NonZero, \
kOnnxDomain, \
13, \
type_name, \
kCudaExecutionProvider, \
(*KernelDefBuilder::Create()).TypeConstraint("T", DataTypeImpl::GetTensorType<type>()), \
NonZero<type>)
#define NONZERO_TYPED_KERNEL(type) \
NONZERO_TYPED_KERNEL_WITH_TYPE_NAME(type, type)
// start with a subset of types, enable more as needed...
NONZERO_TYPED_KERNEL(bool)
NONZERO_TYPED_KERNEL(uint8_t)
//NONZERO_TYPED_KERNEL(uint16_t)
//NONZERO_TYPED_KERNEL(uint32_t)
//NONZERO_TYPED_KERNEL(uint64_t)
//NONZERO_TYPED_KERNEL(int8_t)
//NONZERO_TYPED_KERNEL(int16_t)
NONZERO_TYPED_KERNEL(int32_t)
NONZERO_TYPED_KERNEL(int64_t)
NONZERO_TYPED_KERNEL(MLFloat16)
//NONZERO_TYPED_KERNEL(BFloat16)
NONZERO_TYPED_KERNEL(float)
//NONZERO_TYPED_KERNEL(double)
//NONZERO_TYPED_KERNEL_WITH_TYPE_NAME(std::string, string)
#undef NONZERO_TYPED_KERNEL
#undef NONZERO_TYPED_KERNEL_WITH_TYPE_NAME
template <typename T>
Status NonZero<T>::ComputeInternal(OpKernelContext* context) const {
static const TensorShape kScalarDims{1};
const auto x = context->Input<Tensor>(0);
int nonzero_elements = 0;
const auto& x_shape = x->Shape();
const int x_rank = x_shape.IsScalar() ? 1 : static_cast<int>(x_shape.NumDimensions());
auto x_dims = (x_shape.IsScalar()) ? kScalarDims.GetDims() : x_shape.GetDims();
const int64_t x_size = x_shape.Size();
if (x_size > 0) {
auto x_data = reinterpret_cast<const typename ToCudaType<T>::MappedType*>(x->Data<T>());
const int number_of_blocks = NonZeroCalcBlockCount(x_size);
auto prefix_buffer = GetScratchBuffer<int>(number_of_blocks);
int* prefix_counts = prefix_buffer.get();
CUDA_RETURN_IF_ERROR(NonZeroCountEachBlock(Stream(), x_data, x_size, prefix_counts));
size_t temp_storage_bytes = 0;
CUDA_RETURN_IF_ERROR(NonZeroCalcPrefixSumTempStorageBytes(Stream(), prefix_counts, number_of_blocks, temp_storage_bytes));
auto temp_buffer = GetScratchBuffer<uint8_t>(temp_storage_bytes);
auto d_temp_storage = temp_buffer.get();
CUDA_RETURN_IF_ERROR(NonZeroInclusivePrefixSum(Stream(), d_temp_storage, temp_storage_bytes, prefix_counts, number_of_blocks));
// cudaMemcpyAsync from device memory to pageable host memory will return only once the copy has completed.
CUDA_RETURN_IF_ERROR(cudaMemcpyAsync(
&nonzero_elements, prefix_counts + number_of_blocks - 1,
sizeof(int), cudaMemcpyDeviceToHost, Stream()));
TArray<fast_divmod> fdm_x_strides(x_rank);
TensorPitches x_strides(x_dims);
for (auto i = 0; i < x_rank; i++) {
fdm_x_strides[i] = fast_divmod(static_cast<int>(x_strides[i]));
}
auto* output_tensor = context->Output(0, {x_rank, nonzero_elements});
ORT_ENFORCE(output_tensor, "failed to get first output!");
CUDA_RETURN_IF_ERROR(NonZeroOutputPositions(
Stream(), x_data, x_size, x_rank, fdm_x_strides,
prefix_counts, nonzero_elements, output_tensor->MutableData<int64_t>()));
} else {
context->Output(0, {x_rank, nonzero_elements});
}
return Status::OK();
}
} // namespace cuda
} // namespace onnxruntime
| {
"content_hash": "22cf1ddb9aa092bd9e3a82a263b5a270",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 131,
"avg_line_length": 48.39784946236559,
"alnum_prop": 0.5449900022217286,
"repo_name": "microsoft/onnxruntime",
"id": "93badb82e20b80f4d36ecf9a1cd685d6f9669773",
"size": "4694",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "onnxruntime/core/providers/cuda/tensor/nonzero_op.cc",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1763425"
},
{
"name": "Batchfile",
"bytes": "17040"
},
{
"name": "C",
"bytes": "955390"
},
{
"name": "C#",
"bytes": "2304597"
},
{
"name": "C++",
"bytes": "39435305"
},
{
"name": "CMake",
"bytes": "514764"
},
{
"name": "CSS",
"bytes": "138431"
},
{
"name": "Cuda",
"bytes": "1104338"
},
{
"name": "Dockerfile",
"bytes": "8089"
},
{
"name": "HLSL",
"bytes": "11234"
},
{
"name": "HTML",
"bytes": "5933"
},
{
"name": "Java",
"bytes": "418665"
},
{
"name": "JavaScript",
"bytes": "212575"
},
{
"name": "Jupyter Notebook",
"bytes": "218327"
},
{
"name": "Kotlin",
"bytes": "4653"
},
{
"name": "Liquid",
"bytes": "5457"
},
{
"name": "NASL",
"bytes": "2628"
},
{
"name": "Objective-C",
"bytes": "151027"
},
{
"name": "Objective-C++",
"bytes": "107084"
},
{
"name": "Pascal",
"bytes": "9597"
},
{
"name": "PowerShell",
"bytes": "16419"
},
{
"name": "Python",
"bytes": "5041661"
},
{
"name": "Roff",
"bytes": "27539"
},
{
"name": "Ruby",
"bytes": "3545"
},
{
"name": "Shell",
"bytes": "116513"
},
{
"name": "Swift",
"bytes": "115"
},
{
"name": "TypeScript",
"bytes": "973087"
}
],
"symlink_target": ""
} |
import { MaintainerCloud } from "./MaintainerCloud";
export { MaintainerCloud };
| {
"content_hash": "eb11121c836ce8bf886a0819e6b862e3",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 52,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.7439024390243902,
"repo_name": "collinbarrett/FilterLists",
"id": "c0c593fa3d32d70afae894bacc30dda0ec3e0975",
"size": "82",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "web/src/components/maintainerCloud/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "8816221"
},
{
"name": "CSS",
"bytes": "796"
},
{
"name": "Dockerfile",
"bytes": "13194"
},
{
"name": "HTML",
"bytes": "25633"
},
{
"name": "JavaScript",
"bytes": "978"
},
{
"name": "Shell",
"bytes": "2724"
},
{
"name": "TypeScript",
"bytes": "51386"
}
],
"symlink_target": ""
} |
<?php
namespace sas\galleryBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* CategoryRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CategoryRepository extends EntityRepository
{
}
| {
"content_hash": "de8eeebc51b0fd68fac3b96ef083ecb9",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 68,
"avg_line_length": 17.666666666666668,
"alnum_prop": 0.7660377358490567,
"repo_name": "ddelor/sas",
"id": "74f45b2499e5c0813704c68b9775a54577348a75",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sas/galleryBundle/Entity/CategoryRepository.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2907"
},
{
"name": "CSS",
"bytes": "16184"
},
{
"name": "HTML",
"bytes": "38297"
},
{
"name": "JavaScript",
"bytes": "21262"
},
{
"name": "PHP",
"bytes": "142939"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "d6a246b6c211ee9585e4a0ed00aaf0cb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "d738c85f679d7920e6fca879d5a4acd352d122e7",
"size": "192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Gentianaceae/Gentianella/Gentianella amarella/ Syn. Gentianella acuta/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/*
basic pager with navigation and pages collection
-----dependencies
tmlib addClass, removeClass
-----parameters
-----instantiation
__.pager = new __.classes.Pager({elmsPages: jQuery('#maincontent .tabpage'), elmsNavigation: jQuery('#maincontent .tab')});
-----html
-----css
*/
/*-------
©Pager
-------- */
__.classes.Pager = function(args){
//--required attributes
//->return
//--optional attributes
this.attrId = args.attrId || 'id';
this.boot = args.boot || {};
this.callbackGetNavigationForID = args.callbackGetNavigationForID || this.defaultCallbackGetNavigationForID;
this.callbackGetPageForID = args.callbackGetPageForID || this.defaultCallbackGetPageForID;
this.classCurrentNavigation = args.classCurrentNavigation || 'current';
this.classCurrentPage = args.classCurrentPage || 'current';
this.doCarousel = (typeof args.doCarousel != 'undefined')? args.doCarousel: true;
this.elmsNavigation = args.elmsNavigation || null;
this.elmsPages = args.elmsPages || null;
this.idInitial = args.idInitial || null;
this.oninit = args.oninit || null;
this.onswitch = args.onswitch || null;
//--derived attributes
this.inProgress = true;
if(this.idInitial !== null){
this.elmNavigationCurrent = this.callbackGetNavigationForID(this.idInitial);
this.elmPageCurrent = this.callbackGetPageForID(this.idInitial);
}else{
if(this.elmsNavigation)
this.elmCurrentNavigation = elmsNavigation.hasClass(this.classCurrentNavigation);
}
if(!this.elmPageCurrent)
this.elmPageCurrent = this.elmsPages.first();
if(!this.elmNavigationCurrent && this.elmsNavigation)
this.elmNavigationCurrent = this.callbackGetNavigationForID(this.elmPageCurrent.id);
this.setClasses();
//--do something
if(this.oninit)
this.oninit.call(this);
}
__.classes.Pager.prototype.setClasses = function(){
if(this.elmsNavigation){
this.elmsNavigation.removeClass(this.classCurrentNavigation);
if(this.elmNavigationCurrent)
this.elmNavigationCurrent.addClass(this.classCurrentNavigation);
}
if(this.elmsPages){
this.elmsPages.removeClass(this.classCurrentPage);
if(this.elmPageCurrent)
this.elmPageCurrent.addClass(this.classCurrentPage);
}
}
__.classes.Pager.prototype.switche = function(args){
var localvars = args|| {};
if(this.onswitch)
this.onswitch.call(this, localvars);
else{
this.elmNavigationCurrent = localvars.elmNavigationNext;
this.elmPageCurrent = localvars.elmPageNext;
this.setClasses();
}
}
__.classes.Pager.prototype.switchToID = function(argId){
var localvars = {};
localvars.elmNavigationNext = this.callbackGetNavigationForID(argId);
localvars.elmPageNext = this.callbackGetPageForID(argId);
this.switche(localvars);
}
__.classes.Pager.prototype.switchToPrevious = function(){
var localvars = {};
localvars.elmPageNext = this.elmPageCurrent.prev();
if(localvars.elmPageNext.length == 0 && this.doCarousel)
localvars.elmPageNext = this.elmsPages.last();
if(localvars.elmPageNext.length > 0){
localvars.elmNavigationNext = this.callbackGetNavigationForID(localvars.elmPageNext.attr(this.attrId));
this.switche(localvars);
return true;
}else
return false;
}
__.classes.Pager.prototype.switchToNext = function(){
var localvars = {};
localvars.elmPageNext = this.elmPageCurrent.next();
if(localvars.elmPageNext.length == 0 && this.doCarousel)
localvars.elmPageNext = this.elmsPages.first();
if(localvars.elmPageNext.length > 0){
localvars.elmNavigationNext = this.callbackGetNavigationForID(localvars.elmPageNext.attr(this.attrId));
this.switche(localvars);
return true;
}else
return false;
}
__.classes.Pager.prototype.defaultCallbackGetNavigationForID = function(argId){
if(this.elmsNavigation){
var fncThis = this;
var fncReturn = jQuery(this.elmsNavigation.filter('[href="#'+__.lib.escapeHash(argId)+'"]'));
return (fncReturn.length > 0)? fncReturn: false;
}
return false;
}
__.classes.Pager.prototype.defaultCallbackGetPageForID = function(argId){
if(this.elmsPages){
if(this.attrId == 'id'){
return document.getElementById(argId);
}else{
var fncReturn = this.elmsPages.filter('['+this.attrId+'='"+argId+'"]');
return (fncReturn.length > 0)? fncReturn: false;
}
}
}
| {
"content_hash": "d3d4b8e9bbd4622d72f4b209a9e4cc4e",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 123,
"avg_line_length": 34.78048780487805,
"alnum_prop": 0.7288452547919588,
"repo_name": "tobymackenzie/Web-ClientBehavior",
"id": "d2e5bdb3fade5335db0382af49815039dcc84c0b",
"size": "4279",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "old/pagers/pager.jq.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "880"
},
{
"name": "HTML",
"bytes": "5685"
},
{
"name": "JavaScript",
"bytes": "477524"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3ddd58b5c064fe069b9739ee0177af8e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "e201d85b7d369a1415b32f8d1fb23d35033f8f86",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Arecales/Arecaceae/Prestoea/Prestoea acuminata/ Syn. Euterpe trichoclada/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Approve.RuleCenter;
using Approve.Common;
using Approve.EntityBase;
using Approve.EntitySys;
public partial class Government_NewAppMain_ManagerEdit : System.Web.UI.Page
{
RCenter rc = new RCenter();
RCenter sh = new RCenter();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string sTemp = "";
Govdept1.fNumber = ComFunction.GetDefaultCityDept();
Govdept1.Dis(1);
this.btnAdd.Attributes.Add("onclick", "if(CheckInfo()){return true;}else{return false;}");
if (Request.QueryString["fid"] != null &&
Request.QueryString["fid"] != "")
{
this.ViewState["MFId"] = Request.QueryString["fid"];
ShowInfo();
}
}
}
protected void govdeptid1_SelectedIndexChanged(object sender, System.EventArgs e)
{
partBindInfo(String.IsNullOrEmpty(Govdept1.FNumber) ? EConvert.ToInt(ComFunction.GetDefaultDept()) : EConvert.ToInt(Govdept1.FNumber));
}
protected void ddlPartType_SelectedIndexChanged(object sender, EventArgs e)
{
comBindInfo();
}
private void partBindInfo(int FParentId)
{
ddlPartType.Items.Clear();
DataTable dt = sh.GetTable("select fname,FNumber from CF_Sys_Department where FParentId='" + FParentId + "' order by fnumber ");
ddlPartType.DataSource = dt;
ddlPartType.DataTextField = "FName";
ddlPartType.DataValueField = "FNumber";
ddlPartType.DataBind();
ddlPartType.Items.Insert(0, new ListItem("", ""));
}
private void comBindInfo()
{
t_FCompany.Items.Clear();
DataTable dt = sh.GetTable("select fname,FNumber from CF_Sys_Department where FParentId='" + ddlPartType.SelectedValue + "' order by fnumber");
t_FCompany.DataSource = dt;
t_FCompany.DataTextField = "FName";
t_FCompany.DataValueField = "FNumber";
t_FCompany.DataBind();
t_FCompany.Items.Insert(0, new ListItem("", ""));
}
private void ShowInfo()
{
pageTool tool = new pageTool(this.Page);
StringBuilder sb = new StringBuilder();
sb.Append("select * from cf_sys_user where fid='" + this.ViewState["MFId"].ToString() + "'");
DataTable dt = rc.GetTable(sb.ToString());
if (dt != null && dt.Rows.Count > 0)
{
tool.fillPageControl(dt.Rows[0]);
this.Govdept1.FNumber = dt.Rows[0]["FManageDeptId"].ToString();
partBindInfo(EConvert.ToInt(Govdept1.fNumber));
tr_Name.Visible = tr_pwd.Visible = btnAdd.Visible = btnAdd.Enabled = (EConvert.ToString(Session["DFUserId"]) == dt.Rows[0]["FId"].ToString());
ddlPartType.SelectedIndex = ddlPartType.Items.IndexOf(ddlPartType.Items.FindByValue(dt.Rows[0]["FDepartmentID"].ToString()));
comBindInfo();
t_FCompany.SelectedValue = dt.Rows[0]["FCompany"].ToString();
if (tr_pwd.Visible)
{
txtFName.Text = dt.Rows[0]["FName"].ToString();
string pwd = dt.Rows[0]["FPassWord"].ToString();
if (!string.IsNullOrEmpty(pwd))
pwd = SecurityEncryption.DESDecrypt(pwd);
txtFPwd.Text = pwd;
}
}
}
bool IsRepeatByName()
{
StringBuilder sb = new StringBuilder();
sb.Append("select count(*) from cf_Sys_User ");
sb.Append("where fName='" + txtFName.Text.Trim() + "' ");
if (this.ViewState["MFId"] != null)
sb.Append("and fid!='" + ViewState["MFId"] + "' ");
return rc.GetSQLCount(sb.ToString()) > 0;
}
private void SaveInfo()
{
StringBuilder sb = new StringBuilder();
pageTool tool = new pageTool(this.Page);
SaveOptionEnum so = SaveOptionEnum.Insert;
string fNumber = Govdept1.fNumber;
Govdept1.fNumber = fNumber;
SortedList sl = tool.getPageValue();
//验证用户名是否重复
if (IsRepeatByName())
{
tool.showMessage("用户名重复,请重新填写!");
return;
}
if (this.ViewState["MFId"] != null)
{
so = SaveOptionEnum.Update;
sl.Add("FID", this.ViewState["MFId"].ToString());
}
sl.Add("FManageDeptId", Govdept1.fNumber);
sl.Add("FDepartmentID", ddlPartType.SelectedValue);
sl.Add("FCompany", t_FCompany.SelectedValue);
if (tr_pwd.Visible)
{
sl.Add("FName", txtFName.Text.Trim());
sl.Add("FPassword", SecurityEncryption.DESEncrypt(txtFPwd.Text.Trim()));
}
if (rc.SaveEBase(EntityTypeEnum.EsUser, sl, "FID", so))
{
tool.showMessageAndRunFunction("保存成功", "window.returnValue='1';");
this.ViewState["MFId"] = sl["FID"].ToString();
}
else
{
tool.showMessage("保存失败");
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
SaveInfo();
}
}
| {
"content_hash": "9b70a141758cb43cd63160987560489a",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 154,
"avg_line_length": 36.0945945945946,
"alnum_prop": 0.5932235117933359,
"repo_name": "coojee2012/pm3",
"id": "e7e2019437cbdcf1802a10525a0950ecef4baaa2",
"size": "5400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SurveyDesign/Government/NewAppMain/ManagerEdit.aspx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "11226984"
},
{
"name": "C#",
"bytes": "13305364"
},
{
"name": "CSS",
"bytes": "170205"
},
{
"name": "HTML",
"bytes": "732666"
},
{
"name": "Java",
"bytes": "3209"
},
{
"name": "JavaScript",
"bytes": "613169"
},
{
"name": "PHP",
"bytes": "4866"
},
{
"name": "PLpgSQL",
"bytes": "1028"
},
{
"name": "SQLPL",
"bytes": "2830"
},
{
"name": "Visual Basic",
"bytes": "67805"
},
{
"name": "XSLT",
"bytes": "4122"
}
],
"symlink_target": ""
} |
package arn
// Threads ...
func (user *User) Threads() []*Thread {
threads := GetThreadsByUser(user)
return threads
}
// // Posts ...
// func (user *User) Posts() []*Post {
// posts, _ := GetPostsByUser(user)
// return posts
// }
// Settings ...
func (user *User) Settings() *Settings {
settings, _ := GetSettings(user.ID)
return settings
}
// Analytics ...
func (user *User) Analytics() *Analytics {
analytics, _ := GetAnalytics(user.ID)
return analytics
}
// AnimeList ...
func (user *User) AnimeList() *AnimeList {
animeList, _ := GetAnimeList(user.ID)
return animeList
}
// PushSubscriptions ...
func (user *User) PushSubscriptions() *PushSubscriptions {
subs, _ := GetPushSubscriptions(user.ID)
return subs
}
// Inventory ...
func (user *User) Inventory() *Inventory {
inventory, _ := GetInventory(user.ID)
return inventory
}
// Follows returns the list of user follows.
func (user *User) Follows() *UserFollows {
follows, _ := GetUserFollows(user.ID)
return follows
}
// Notifications returns the list of user notifications.
func (user *User) Notifications() *UserNotifications {
notifications, _ := GetUserNotifications(user.ID)
return notifications
}
// Followers ...
func (user *User) Followers() []*User {
var followerIDs []string
for list := range StreamUserFollows() {
if list.Contains(user.ID) {
followerIDs = append(followerIDs, list.UserID)
}
}
usersObj := DB.GetMany("User", followerIDs)
users := make([]*User, len(usersObj))
for i, obj := range usersObj {
users[i] = obj.(*User)
}
return users
}
// FollowersCount ...
func (user *User) FollowersCount() int {
count := 0
for list := range StreamUserFollows() {
if list.Contains(user.ID) {
count++
}
}
return count
}
// DraftIndex ...
func (user *User) DraftIndex() *DraftIndex {
draftIndex, _ := GetDraftIndex(user.ID)
return draftIndex
}
// SoundTracks returns the soundtracks posted by the user.
func (user *User) SoundTracks() []*SoundTrack {
tracks := FilterSoundTracks(func(track *SoundTrack) bool {
return !track.IsDraft && len(track.Media) > 0 && track.CreatedBy == user.ID
})
return tracks
}
| {
"content_hash": "255357ac1231be7773abd960bfe96926",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 77,
"avg_line_length": 20.96078431372549,
"alnum_prop": 0.6758652946679139,
"repo_name": "animenotifier/arn",
"id": "1d8504c0c70e040392e50d7fca6bdb1a145193f9",
"size": "2138",
"binary": false,
"copies": "1",
"ref": "refs/heads/go",
"path": "UserJoins.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "364040"
}
],
"symlink_target": ""
} |
namespace nano
{
class block_store;
class transaction;
class rep_weights
{
public:
void representation_add (nano::account const & source_a, nano::uint128_t const & amount_a);
nano::uint128_t representation_get (nano::account const & account_a);
void representation_put (nano::account const & account_a, nano::uint128_union const & representation_a);
std::unordered_map<nano::account, nano::uint128_t> get_rep_amounts ();
private:
std::mutex mutex;
std::unordered_map<nano::account, nano::uint128_t> rep_amounts;
void put (nano::account const & account_a, nano::uint128_union const & representation_a);
nano::uint128_t get (nano::account const & account_a);
friend std::unique_ptr<container_info_component> collect_container_info (rep_weights &, const std::string &);
};
std::unique_ptr<container_info_component> collect_container_info (rep_weights &, const std::string &);
}
| {
"content_hash": "aa249527bfcdd65763e0f9b44c1e57e1",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 110,
"avg_line_length": 37,
"alnum_prop": 0.7364864864864865,
"repo_name": "clemahieu/raiblocks",
"id": "818c5f4e174dd6e686ab4ec76f45e1789e5abaf2",
"size": "1028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nano/lib/rep_weights.hpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "814650"
},
{
"name": "C++",
"bytes": "3918042"
},
{
"name": "CMake",
"bytes": "139423"
},
{
"name": "M4",
"bytes": "19093"
},
{
"name": "Makefile",
"bytes": "17515"
},
{
"name": "Objective-C",
"bytes": "3568875"
},
{
"name": "Objective-C++",
"bytes": "379"
},
{
"name": "PHP",
"bytes": "3641"
},
{
"name": "Python",
"bytes": "271779"
},
{
"name": "Rust",
"bytes": "26178"
},
{
"name": "Shell",
"bytes": "22030"
}
],
"symlink_target": ""
} |
#ifndef IVW_VOLUMESUBSET_H
#define IVW_VOLUMESUBSET_H
#include <modules/base/basemoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/ports/volumeport.h>
#include <inviwo/core/processors/processor.h>
#include <inviwo/core/properties/boolproperty.h>
#include <inviwo/core/properties/minmaxproperty.h>
namespace inviwo {
/** \docpage{org.inviwo.VolumeSubset, Volume Subset}
* 
*
* ...
*
* ### Inports
* * __volume.inport__ ...
*
* ### Outports
* * __volume.outport__ ...
*
* ### Properties
* * __Y Slices__ ...
* * __Enable Operation__ ...
* * __X Slices__ ...
* * __Z Slices__ ...
* * __Adjust Basis and Offset__ ...
*
*/
class IVW_MODULE_BASE_API VolumeSubset : public Processor {
public:
VolumeSubset();
~VolumeSubset();
virtual const ProcessorInfo getProcessorInfo() const override;
static const ProcessorInfo processorInfo_;
protected:
virtual void process() override;
void onVolumeChange();
private:
VolumeInport inport_;
VolumeOutport outport_;
BoolProperty enabled_;
BoolProperty adjustBasisAndOffset_;
IntMinMaxProperty rangeX_;
IntMinMaxProperty rangeY_;
IntMinMaxProperty rangeZ_;
size3_t dims_;
};
}
#endif //IVW_VOLUMESUBSET_H
| {
"content_hash": "7e902998c5169e70b1f327ae7961da63",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 75,
"avg_line_length": 21.580645161290324,
"alnum_prop": 0.672645739910314,
"repo_name": "cgloger/inviwo",
"id": "666e8848e623484542fbe1dec300cc9d92c7b2df",
"size": "2922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/base/processors/volumesubset.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "87832"
},
{
"name": "Batchfile",
"bytes": "11554"
},
{
"name": "C",
"bytes": "15805810"
},
{
"name": "C#",
"bytes": "713601"
},
{
"name": "C++",
"bytes": "25473057"
},
{
"name": "CMake",
"bytes": "1277310"
},
{
"name": "COBOL",
"bytes": "2921725"
},
{
"name": "CSS",
"bytes": "26526"
},
{
"name": "D",
"bytes": "175403"
},
{
"name": "GLSL",
"bytes": "261754"
},
{
"name": "Groff",
"bytes": "6855"
},
{
"name": "HTML",
"bytes": "2691735"
},
{
"name": "Inno Setup",
"bytes": "8416"
},
{
"name": "Java",
"bytes": "287161"
},
{
"name": "JavaScript",
"bytes": "3140"
},
{
"name": "Logos",
"bytes": "2952312"
},
{
"name": "M",
"bytes": "10146"
},
{
"name": "M4",
"bytes": "16806"
},
{
"name": "Makefile",
"bytes": "5057156"
},
{
"name": "Matlab",
"bytes": "1691"
},
{
"name": "Objective-C",
"bytes": "129135"
},
{
"name": "Objective-C++",
"bytes": "29141"
},
{
"name": "Pascal",
"bytes": "13054"
},
{
"name": "Python",
"bytes": "184506"
},
{
"name": "QMake",
"bytes": "1381"
},
{
"name": "Shell",
"bytes": "258309"
},
{
"name": "Smalltalk",
"bytes": "1501"
},
{
"name": "Smarty",
"bytes": "169"
},
{
"name": "Tcl",
"bytes": "1811"
},
{
"name": "UnrealScript",
"bytes": "1273"
},
{
"name": "XSLT",
"bytes": "3925"
}
],
"symlink_target": ""
} |
<?php
namespace liderDeportivo\ExtranetBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Pagerfanta\Pagerfanta;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\View\TwitterBootstrapView;
use liderDeportivo\ExtranetBundle\Entity\Encuentros;
use liderDeportivo\ExtranetBundle\Form\EncuentrosType;
use liderDeportivo\ExtranetBundle\Form\EncuentrosFilterType;
/**
* Encuentros controller.
*
* @Route("/encuentros")
*/
class EncuentrosController extends Controller
{
/**
* Lists all Encuentros entities.
*
* @Route("/", name="encuentros")
* @Method("GET")
* @Template()
*/
public function indexAction()
{
list($filterForm, $queryBuilder) = $this->filter();
list($entities, $pagerHtml) = $this->paginator($queryBuilder);
return array(
'entities' => $entities,
'pagerHtml' => $pagerHtml,
'filterForm' => $filterForm->createView(),
);
}
/**
* Create filter form and process filter request.
*
*/
protected function filter()
{
$request = $this->getRequest();
$session = $request->getSession();
$filterForm = $this->createForm(new EncuentrosFilterType());
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('ExtranetBundle:Encuentros')->createQueryBuilder('e');
// Reset filter
if ($request->get('filter_action') == 'reset') {
$session->remove('EncuentrosControllerFilter');
}
// Filter action
if ($request->get('filter_action') == 'filter') {
// Bind values from the request
$filterForm->bind($request);
if ($filterForm->isValid()) {
// Build the query from the given form object
$this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
// Save filter to session
$filterData = $filterForm->getData();
$session->set('EncuentrosControllerFilter', $filterData);
}
} else {
// Get filter from session
if ($session->has('EncuentrosControllerFilter')) {
$filterData = $session->get('EncuentrosControllerFilter');
$filterForm = $this->createForm(new EncuentrosFilterType(), $filterData);
$this->get('lexik_form_filter.query_builder_updater')->addFilterConditions($filterForm, $queryBuilder);
}
}
return array($filterForm, $queryBuilder);
}
/**
* Get results from paginator and get paginator view.
*
*/
protected function paginator($queryBuilder)
{
// Paginator
$adapter = new DoctrineORMAdapter($queryBuilder);
$pagerfanta = new Pagerfanta($adapter);
$currentPage = $this->getRequest()->get('page', 1);
$pagerfanta->setCurrentPage($currentPage);
$entities = $pagerfanta->getCurrentPageResults();
// Paginator - route generator
$me = $this;
$routeGenerator = function($page) use ($me)
{
return $me->generateUrl('encuentros', array('page' => $page));
};
// Paginator - view
$translator = $this->get('translator');
$view = new TwitterBootstrapView();
$pagerHtml = $view->render($pagerfanta, $routeGenerator, array(
'proximity' => 3,
'prev_message' => $translator->trans('views.index.pagprev', array(), 'JordiLlonchCrudGeneratorBundle'),
'next_message' => $translator->trans('views.index.pagnext', array(), 'JordiLlonchCrudGeneratorBundle'),
));
return array($entities, $pagerHtml);
}
/**
* Creates a new Encuentros entity.
*
* @Route("/", name="encuentros_create")
* @Method("POST")
* @Template("ExtranetBundle:Encuentros:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new Encuentros();
$form = $this->createForm(new EncuentrosType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'flash.create.success');
return $this->redirect($this->generateUrl('encuentros_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Displays a form to create a new Encuentros entity.
*
* @Route("/new", name="encuentros_new")
* @Method("GET")
* @Template()
*/
public function newAction()
{
$entity = new Encuentros();
$form = $this->createForm(new EncuentrosType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a Encuentros entity.
*
* @Route("/{id}", name="encuentros_show")
* @Method("GET")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ExtranetBundle:Encuentros')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Encuentros entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing Encuentros entity.
*
* @Route("/{id}/edit", name="encuentros_edit")
* @Method("GET")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ExtranetBundle:Encuentros')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Encuentros entity.');
}
$editForm = $this->createForm(new EncuentrosType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing Encuentros entity.
*
* @Route("/{id}", name="encuentros_update")
* @Method("PUT")
* @Template("ExtranetBundle:Encuentros:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ExtranetBundle:Encuentros')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Encuentros entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new EncuentrosType(), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'flash.update.success');
return $this->redirect($this->generateUrl('encuentros_edit', array('id' => $id)));
} else {
$this->get('session')->getFlashBag()->add('error', 'flash.update.error');
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Encuentros entity.
*
* @Route("/{id}", name="encuentros_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ExtranetBundle:Encuentros')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Encuentros entity.');
}
$em->remove($entity);
$em->flush();
$this->get('session')->getFlashBag()->add('success', 'flash.delete.success');
} else {
$this->get('session')->getFlashBag()->add('error', 'flash.delete.error');
}
return $this->redirect($this->generateUrl('encuentros'));
}
/**
* Creates a form to delete a Encuentros entity by id.
*
* @param mixed $id The entity id
*
* @return Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
| {
"content_hash": "e53cf28113a59a47ea384b6716577649",
"timestamp": "",
"source": "github",
"line_count": 297,
"max_line_length": 119,
"avg_line_length": 31.14814814814815,
"alnum_prop": 0.5635066479299535,
"repo_name": "ovelasquez/lider",
"id": "7b3a55c7e81c23023dccd5d28072e45748e8bbe9",
"size": "9251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/liderDeportivo/ExtranetBundle/Controller/EncuentrosController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "118273"
},
{
"name": "JavaScript",
"bytes": "679231"
},
{
"name": "PHP",
"bytes": "326117"
}
],
"symlink_target": ""
} |
package com.fishercoder;
import com.fishercoder.solutions._1118;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class _1118Test {
private static _1118.Solution1 solution1;
@Before
public void setupForEachTest() {
solution1 = new _1118.Solution1();
}
@Test
public void test1() {
assertEquals(31, solution1.numberOfDays(1992, 7));
}
@Test
public void test2() {
assertEquals(29, solution1.numberOfDays(2000, 2));
}
@Test
public void test3() {
assertEquals(28, solution1.numberOfDays(1900, 2));
}
@Test
public void test4() {
assertEquals(29, solution1.numberOfDays(1836, 2));
}
} | {
"content_hash": "f1b7272f65a7b9354cd0fafa9f775a0e",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 58,
"avg_line_length": 20.243243243243242,
"alnum_prop": 0.6475300400534045,
"repo_name": "fishercoder1534/Leetcode",
"id": "633a16ab395200c210931009d43ae640d62538e7",
"size": "749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/fishercoder/_1118Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "12363"
},
{
"name": "Java",
"bytes": "3564419"
},
{
"name": "JavaScript",
"bytes": "6306"
},
{
"name": "Python",
"bytes": "408"
},
{
"name": "Shell",
"bytes": "2634"
}
],
"symlink_target": ""
} |
package reactive.week01
/**
* @author mpakhomov
* @since 12/18/15
*/
abstract class JSON
case class JSeq (elems: List[JSON]) extends JSON
case class JObj (bindings: Map[String, JSON]) extends JSON
case class JNum (num: Double) extends JSON
case class JStr (str: String) extends JSON
case class JBool (b: Boolean) extends JSON
case object JNull extends JSON
object TestJson extends App {
def show(json: JSON): String = json match {
case JSeq(elems) =>
"[" + (elems map show mkString ", ") + "]"
case JObj(bindings) =>
val assocs = bindings map {
case (key, value) => "\"" + key + "\": " + show(value)
}
"{" + (assocs mkString ", ") + "}"
case JNum(num) => num.toString
case JStr(str) => '\"' + str + '\"'
case JBool(b) => b.toString
case JNull => "null"
}
val data = JObj(Map(
"firstName" -> JStr("John"),
"lastName" -> JStr("Smith"),
"address" -> JObj(Map(
"streetAddress" -> JStr("21 2nd Street"),
"state" -> JStr("NY"),
"postalCode" -> JNum(10021)
)),
"phoneNumbers" -> JSeq(List(
JObj(Map(
"type" -> JStr("home"), "number" -> JStr("212 555-1234")
)),
JObj(Map(
"type" -> JStr("fax"), "number" -> JStr("646 555-4567")
))))))
println(show(data))
}
| {
"content_hash": "61c81186bdcad66ef8bd38048ffac53d",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 64,
"avg_line_length": 26.16,
"alnum_prop": 0.5596330275229358,
"repo_name": "mpakhomov/scala-progfun-2015",
"id": "4b510e0120a57dc26d4a73ad012c17a151611d1c",
"size": "1308",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/reactive/week01/JSON.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "21430"
}
],
"symlink_target": ""
} |
package com.pchudzik.springmock.mockito;
import com.pchudzik.springmock.infrastructure.MockConstants;
public class MockitoConstants {
public static final String PACKAGE_PREFIX = MockConstants.PACKAGE_PREFIX + "mockito.";
}
| {
"content_hash": "09dcd8a43590f0fe444d051b035eaba3",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 87,
"avg_line_length": 32.285714285714285,
"alnum_prop": 0.8185840707964602,
"repo_name": "pchudzik/springmock",
"id": "9de105adafe29ecb5e12cea5af2bc83ded1b9077",
"size": "226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mockito/src/main/java/com/pchudzik/springmock/mockito/MockitoConstants.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "43174"
},
{
"name": "Java",
"bytes": "333336"
},
{
"name": "Shell",
"bytes": "57"
}
],
"symlink_target": ""
} |
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/type_traits.hpp>
#include <boost/typeof/typeof.hpp>
#include "Driver.hpp"
/**
Set default values of ARD header.
@param pDesc ARD*.
@param pStmt HDRVSTMT.
*/
void _SQLSetARDFieldsDefault(ARD* pDesc, const SQLHSTMT pStmt)
{
// reset all
memset(pDesc, 0, sizeof(ARD));
// set explicit defaults
pDesc->sign = SQL_DESC_ARD;
pDesc->hStmt = (SQLHSTMT)pStmt;
pDesc->allocType = SQL_DESC_ALLOC_AUTO;
pDesc->rowArraySize = 1;
pDesc->bindTypeOrSize = SQL_BIND_BY_COLUMN;
}
/**
Set default values of IRD header.
@param pDesc IRD*.
@param pStmt HDRVSTMT.
*/
void _SQLSetIRDFieldsDefault(IRD* pDesc, const SQLHSTMT pStmt)
{
// reset all
memset(pDesc, 0, sizeof(IRD));
// set explicit defaults
pDesc->sign = SQL_DESC_IRD;
pDesc->hStmt = (SQLHSTMT)pStmt;
}
/**
Set default values of APD header.
@param pDesc APD*.
@param pStmt HDRVSTMT.
*/
void _SQLSetAPDFieldsDefault(APD* pDesc, const SQLHSTMT pStmt)
{
// reset all
memset(pDesc, 0, sizeof(APD));
// set explicit defaults
pDesc->sign = SQL_DESC_APD;
pDesc->hStmt = (SQLHSTMT)pStmt;
pDesc->allocType = SQL_DESC_ALLOC_AUTO;
pDesc->rowArraySize = 1;
pDesc->bindTypeOrSize = SQL_BIND_BY_COLUMN;
}
/**
Set default values of IPD header.
@param pDesc IPD*.
@param pStmt HDRVSTMT.
*/
void _SQLSetIPDFieldsDefault(IPD* pDesc, const SQLHSTMT pStmt)
{
// reset all
memset(pDesc, 0, sizeof(IPD));
// set explicit defaults
pDesc->sign = SQL_DESC_IPD;
pDesc->hStmt = (SQLHSTMT)pStmt;
}
/**
Set default values of ARD item.
@param pDesc ARDItem*.
@param pRecNum Record number (Descriptor records are numbered from 1).
@return True if succeed otherwise false.
*/
bool _SQLSetARDItemFieldsDefault(ARDItem* pDescItem, SQLSMALLINT pRecNum)
{
// reset
memset(pDescItem, 0, sizeof(ARDItem));
// set explicit defaults
pDescItem->colNum = pRecNum;
pDescItem->dataConciseType = SQL_C_DEFAULT;
pDescItem->dataVerboseType = SQL_C_DEFAULT;
return true;
}
/**
Set default values of IRD item.
@param pDesc IRDItem*.
@param pRecNum Record number (Descriptor records are numbered from 1).
@return True if succeed otherwise false.
*/
bool _SQLSetIRDItemFieldsDefault(IRDItem* pDescItem, SQLSMALLINT pRecNum)
{
return true;
}
/**
Set default values of APD item.
@param pDesc APDItem*.
@param pRecNum Record number (Descriptor records are numbered from 1).
@return True if succeed otherwise false.
*/
bool _SQLSetAPDItemFieldsDefault(APDItem* pDescItem, SQLSMALLINT pRecNum)
{
// reset all
memset(pDescItem, 0, sizeof(APDItem));
// set explicit defaults
pDescItem->dataConciseType = SQL_C_DEFAULT;
pDescItem->dataVerboseType = SQL_C_DEFAULT;
return true;
}
/**
Set default values of IPD item.
@param pDesc IPDItem*.
@param pRecNum Record number (Descriptor records are numbered from 1).
@return True if succeed otherwise false.
*/
bool _SQLSetIPDItemFieldsDefault(IPDItem* pDescItem, SQLSMALLINT pRecNum)
{
// reset all
memset(pDescItem, 0, sizeof(IPDItem));
// set explicit defaults
pDescItem->paramType = SQL_PARAM_INPUT;
pDescItem->dataConciseType = SQL_DEFAULT;
pDescItem->dataVerboseType = SQL_DEFAULT;
return true;
}
// http://nealabq.com/blog/2008/09/25/member_object_pointer_traits/
// Declare member_object_pointer_traits but do not
// define a body. The struct will only ever be
// instantiated through specialization.
template<typename DATA_MEMBER_PTR>
struct MemberObjectPointerTraits;
// Specialized member_object_pointer_traits that
// only matches member-object pointers.
template<typename T, typename C>
struct MemberObjectPointerTraits<T(C::*)>
{
typedef C ClassType;
typedef T DataType;
};
/**
Attach a new item to descriptor item list.
@param pDesc Pointer to Descriptor.
@param pDescItem Pointer to descriptor item.
@param ptrToItemList Member pointer to descriptor item list.
@return True if succeed otherwise false.
*/
template<typename T, typename I, typename P>
static bool _AttachItem(T* pDesc, I* pDescItem, P ptrToItemList)
{
// note
// this function also helps in maintaining highest desc number
// precaution
if(pDesc == NULL || pDescItem == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return false;
}
if((pDesc->*ptrToItemList) == NULL)
{
typedef typename boost::remove_pointer<
typename MemberObjectPointerTraits<P>::DataType
>::type PT;
(pDesc->*ptrToItemList) = new PT;
}
(pDesc->*ptrToItemList)->push_back(pDescItem);
return true;
}
template<typename T, typename I, typename P>
static void _DetachItemDescCount(T* pDesc, I* pDescItem, P ptrToItemList,
int ptrToCount)
{
}
template<typename T, typename I, typename P, typename P2>
static void _DetachItemDescCount(T* pDesc, I* pDescItem, P ptrToItemList,
P2 ptrToCount)
{
// maintain highest desc number
if(pDesc->descCount == pDescItem->*ptrToCount)
{
// loop to find the highest number and set that
I& i = *std::max_element(
(pDesc->*ptrToItemList)->begin(), (pDesc->*ptrToItemList)->end(),
boost::lambda::bind(ptrToCount, boost::lambda::_2) >
boost::lambda::bind(ptrToCount, boost::lambda::_1));
// set the highest count to this column
pDesc->descCount = i.*ptrToCount;
}
}
/**
Detach an existing item from descriptor item list.
@param pDesc Pointer to Descriptor.
@param pDescItem Pointer to descriptor item.
@param ptrToItemList Member pointer to descriptor item list.
@param ptrToCount Member pointer to item's member for descriptor's descCount.
@return True if succeed otherwise false.
*/
template<typename T, typename I, typename P, typename P2>
static bool _DetachItem(T* pDesc, I* pDescItem, P ptrToItemList,
P2 ptrToCount)
{
// note
// this function also helps in maintaining highest desc number
// precaution
if(pDesc == NULL || pDescItem == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return false;
}
(pDesc->*ptrToItemList)->erase_if(pDescItem == &boost::lambda::_1);
_DetachItemDescCount(pDesc, pDescItem, ptrToItemList, ptrToCount);
return true;
}
template<typename T, typename I, typename P>
static bool _DetachItem(T* pDesc, I* pDescItem, P ptrToItemList,
int* ptrToCount = NULL)
{
return _DetachItem(pDesc, pDescItem, ptrToItemList,
(int)((std::size_t)ptrToCount));
}
/**
Attach a new item to ARD item list.
@param pDesc ARD*
@param pDescItem ARDItem*
@return True if succeed otherwise false.
*/
bool _SQLAttachARDItem(ARD* pDesc, ARDItem* pDescItem)
{
// maintain highest desc number
if(pDesc->descCount < pDescItem->colNum)
pDesc->descCount = pDescItem->colNum;
return _AttachItem(pDesc, pDescItem, &ARD::bindCols);
}
/**
Attach a new item to IRD item list.
@param pDesc IRD*
@param pDescItem IRDItem*
@return True if succeed otherwise false.
*/
bool _SQLAttachIRDItem(IRD* pDesc, IRDItem* pDescItem)
{
bool ok = _AttachItem(pDesc, pDescItem, &IRD::rowDesc);
// maintain highest desc number
pDesc->descCount = (SQLSMALLINT)pDesc->rowDesc->size();
return ok;
}
/**
Attach a new item to APD item list.
@param pDesc APD*
@param pDescItem APDItem*
@return True if succeed otherwise false.
*/
bool _SQLAttachAPDItem(APD* pDesc, APDItem* pDescItem)
{
// maintain highest desc number
if(pDesc->descCount < pDescItem->paramNum)
pDesc->descCount = pDescItem->paramNum;
return _AttachItem(pDesc, pDescItem, &APD::bindParams);
}
/**
Attach a new item to IPD item list.
@param pDesc IPD*
@param pDescItem IPDItem*
@return True if succeed otherwise false.
*/
bool _SQLAttachIPDItem(IPD* pDesc, IPDItem* pDescItem)
{
// maintain highest desc number
if(pDesc->descCount < pDescItem->paramNum)
pDesc->descCount = pDescItem->paramNum;
return _AttachItem(pDesc, pDescItem, &IPD::bindParams);
}
/**
Detach an existing item from ARD item list.
@param pDesc ARD*
@param pDescItem ARDItem*
@return True if succeed otherwise false.
*/
bool _SQLDetachARDItem(ARD* pDesc, ARDItem* pDescItem)
{
return _DetachItem(pDesc, pDescItem, &ARD::bindCols, &ARDItem::colNum);
}
/**
Detach an existing item from IRD item list.
@param pDesc IRD*
@param pDescItem IRDItem*
@return True if succeed otherwise false.
*/
bool _SQLDetachIRDItem(IRD* pDesc, IRDItem* pDescItem)
{
return _DetachItem(pDesc, pDescItem, &IRD::rowDesc);
}
/**
Detach an existing item from APD item list.
@param pDesc APD*
@param pDescItem APDItem*
@return True if succeed otherwise false.
*/
bool _SQLDetachAPDItem(APD* pDesc, APDItem* pDescItem)
{
return _DetachItem(pDesc, pDescItem, &APD::bindParams);
}
/**
Detach an existing item from IPD item list.
@param pDesc IPD*
@param pDescItem IPDItem*
@return True if succeed otherwise false.
*/
bool _SQLDetachIPDItem(IPD* pDesc, IPDItem* pDescItem)
{
return _DetachItem(pDesc, pDescItem, &IPD::bindParams);
}
template<typename T, typename P>
static void* _GetItemRecNum(T* pDesc, SQLSMALLINT pRecNum, P ptrToItemList,
int ptrToRecNum)
{
if((std::size_t)pRecNum > (pDesc->*ptrToItemList)->size())
return NULL;
return &(pDesc->*ptrToItemList)->at(pRecNum - 1);
}
template<typename T, typename P, typename P2>
static void* _GetItemRecNum(T* pDesc, SQLSMALLINT pRecNum, P ptrToItemList,
P2 ptrToRecNum)
{
typedef BOOST_TYPEOF((pDesc->*ptrToItemList)->begin()) Iterator;
Iterator i = std::find_if(
(pDesc->*ptrToItemList)->begin(), (pDesc->*ptrToItemList)->end(),
boost::lambda::bind(ptrToRecNum, boost::lambda::_1) == pRecNum);
if(i == (pDesc->*ptrToItemList)->end())
return NULL;
else
return &(*i);
}
/**
Get a particular descriptor item.
@param pDesc Pointer to descriptor.
@param pRecNum Record number (Descriptor records are numbered from 1).
@param ptrToItemList Member pointer to descriptor item list.
@param ptrToRecNum Member pointer to item's record number.
@return Pointer to descriptor item.
*/
template<typename T, typename P, typename P2>
static void* _GetItem(T* pDesc, SQLSMALLINT pRecNum, P ptrToItemList,
P2 ptrToRecNum)
{
// check if descriptor is valid
if(pDesc == NULL || pDesc->hStmt == NULL)
return NULL;
if((pDesc->*ptrToItemList) == NULL)
return NULL;
return _GetItemRecNum(pDesc, pRecNum, ptrToItemList, ptrToRecNum);
}
template<typename T, typename P>
static void* _GetItem(T* pDesc, SQLSMALLINT pRecNum, P ptrToItemList,
int* ptrToRecNum = NULL)
{
return _GetItem(pDesc, pRecNum, ptrToItemList,
(int)((std::size_t)ptrToRecNum));
}
/**
Get a particular ARD item.
@param pDesc ARD*
@param pRecNum Record number (Descriptor records are numbered from 1).
@return ARDItem*
*/
ARDItem* _SQLGetARDItem(const ARD* pDesc, SQLSMALLINT pRecNum)
{
// return the ARD item
return (ARDItem*)_GetItem(pDesc, pRecNum, &ARD::bindCols, &ARDItem::colNum);
}
/**
Get a particular IRD item.
@param pDesc IRD*
@param pRecNum Record number (Descriptor records are numbered from 1).
@return IRDItem*
*/
IRDItem* _SQLGetIRDItem(const IRD* pDesc, SQLSMALLINT pRecNum)
{
return (IRDItem*)_GetItem(pDesc, pRecNum, &IRD::rowDesc);
}
/**
Get a particular APD item.
@param pDesc APD*
@param pRecNum Record number (Descriptor records are numbered from 1).
@return APDItem*
*/
APDItem* _SQLGetAPDItem(const APD* pDesc, SQLSMALLINT pRecNum)
{
return (APDItem*)_GetItem(pDesc, pRecNum, &APD::bindParams,
&APDItem::paramNum);
}
/**
Get a particular IPD item.
@param pDesc IPD*
@param pRecNum Record number (Descriptor records are numbered from 1).
@return IPDItem*
*/
IPDItem* _SQLGetIPDItem(const IPD* pDesc, SQLSMALLINT pRecNum)
{
return (IPDItem*)_GetItem(pDesc, pRecNum, &IPD::bindParams,
&IPDItem::paramNum);
}
/**
Get a field value in ARD header.
@param pDesc ARD*.
@param pFldID Field identity.
@param pDataPtr Data pointer.
@param pDataSize Data size.
@param pDataSizePtr A pointer to a buffer in which to return the total number
of bytes.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLGetARDField(const ARD* pDesc, SQLSMALLINT pFldID,
SQLPOINTER pDataPtr,
SQLINTEGER pDataSize, SQLINTEGER* pDataSizePtr)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pDesc: %d, Fld: %d, DataPtr: %d, DataSize: %d, DataSizePtr: %d"),
LOG_FUNCTION_NAME,
pDesc, pFldID, pDataPtr, pDataSize, pDataSizePtr);
// precaution
if(pDesc == NULL || pDataPtr == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return SQL_ERROR;
}
// as per required field
switch(pFldID)
{
case SQL_DESC_ALLOC_TYPE:
*((SQLSMALLINT*)pDataPtr) = pDesc->allocType;
break;
case SQL_DESC_ARRAY_SIZE:
*((SQLUINTEGER*)pDataPtr) = pDesc->rowArraySize;
break;
case SQL_DESC_ARRAY_STATUS_PTR:
*((SQLUSMALLINT**)pDataPtr) = pDesc->arrayStatusPtr;
break;
case SQL_DESC_BIND_OFFSET_PTR:
*((SQLINTEGER**)pDataPtr) = pDesc->bindOffsetPtr;
break;
case SQL_DESC_BIND_TYPE:
*((SQLINTEGER*)pDataPtr) = pDesc->bindTypeOrSize;
break;
case SQL_DESC_COUNT:
*((SQLSMALLINT*)pDataPtr) = pDesc->descCount;
break;
default:
LOG_ERROR_F_FUNC(TEXT("unknown field (%d)."), pFldID);
return SQL_ERROR;
}
return SQL_SUCCESS;
}
/**
Get a field value in IRD header.
@param pDesc IRD*.
@param pFldID Field identity.
@param pDataPtr Data pointer.
@param pDataSize Data size.
@param pDataSizePtr A pointer to a buffer in which to return the total number
of bytes.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLGetIRDField(const IRD* pDesc, SQLSMALLINT pFldID,
SQLPOINTER pDataPtr,
SQLINTEGER pDataSize, SQLINTEGER* pDataSizePtr)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pDesc: %d, Fld: %d, DataPtr: %d, DataSize: %d, DataSizePtr: %d"),
LOG_FUNCTION_NAME,
pDesc, pFldID, pDataPtr, pDataSize, pDataSizePtr);
// precaution
if(pDesc == NULL || pDataPtr == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return SQL_ERROR;
}
// as per required field
switch(pFldID)
{
case SQL_DESC_ALLOC_TYPE:
*((SQLSMALLINT*)pDataPtr) = SQL_DESC_ALLOC_AUTO;
break;
case SQL_DESC_ARRAY_STATUS_PTR:
*((SQLUSMALLINT**)pDataPtr) = pDesc->arrayStatusPtr;
break;
case SQL_DESC_COUNT:
*((SQLSMALLINT*)pDataPtr) = pDesc->descCount;
break;
case SQL_DESC_ROWS_PROCESSED_PTR:
*((SQLULEN**)pDataPtr) = pDesc->rowsProcessedPtr;
break;
default:
LOG_ERROR_F_FUNC(TEXT("unknown field (%d)."), pFldID);
return SQL_ERROR;
}
return SQL_SUCCESS;
}
/**
Set a field value in ARD header.
@param pDesc ARD*.
@param pFldID Field identity.
@param pDataPtr Data pointer.
@param pDataSize Data size.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLSetARDField(ARD* pDesc, SQLSMALLINT pFldID,
const SQLPOINTER pDataPtr, SQLINTEGER pDataSize)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pDesc: %d, Fld: %d, DataPtr: %d, DataSize: %d"),
LOG_FUNCTION_NAME,
pDesc, pFldID, pDataPtr, pDataSize);
// precaution
if(pDesc == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return SQL_ERROR;
}
// as per required field
switch(pFldID)
{
case SQL_DESC_ARRAY_SIZE:
LOG_DEBUG_F_FUNC(TEXT("ARD RowArraySize is set to %d"),
(SQLUINTEGER)((std::size_t)pDataPtr));
pDesc->rowArraySize = (SQLUINTEGER)((std::size_t)pDataPtr);
break;
case SQL_DESC_ARRAY_STATUS_PTR:
pDesc->arrayStatusPtr = (SQLUSMALLINT*)pDataPtr;
break;
case SQL_DESC_BIND_OFFSET_PTR:
pDesc->bindOffsetPtr = (SQLINTEGER*)pDataPtr;
break;
case SQL_DESC_BIND_TYPE:
pDesc->bindTypeOrSize = (SQLINTEGER)((std::size_t)pDataPtr);
break;
case SQL_DESC_COUNT:
// ???? requires that all descriptors which r above the specified
// value are freed
LOG_ERROR_FUNC(TEXT("SQL_DESC_COUNT not implemented."));
return SQL_ERROR;
default:
LOG_ERROR_F_FUNC(TEXT("unknown field (%d)."), pFldID);
return SQL_ERROR;
}
return SQL_SUCCESS;
}
/**
Set a field value in IRD header.
@param pDesc IRD*.
@param pFldID Field identity.
@param pDataPtr Data pointer.
@param pDataSize Data size.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLSetIRDField(IRD* pDesc, SQLSMALLINT pFldID,
const SQLPOINTER pDataPtr, SQLINTEGER pDataSize)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pDesc: %d, Fld: %d, DataPtr: %d, DataSize: %d"),
LOG_FUNCTION_NAME,
pDesc, pFldID, pDataPtr, pDataSize);
// precaution
if(pDesc == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return SQL_ERROR;
}
// as per required field
switch(pFldID)
{
case SQL_DESC_ARRAY_STATUS_PTR:
pDesc->arrayStatusPtr = (SQLUSMALLINT*)pDataPtr;
break;
case SQL_DESC_ROWS_PROCESSED_PTR:
pDesc->rowsProcessedPtr = (SQLULEN*)pDataPtr;
break;
default:
LOG_ERROR_F_FUNC(TEXT("unknown field (%d)."), pFldID);
return SQL_ERROR;
}
return SQL_SUCCESS;
}
/**
Check if the specified type is a valid SQL data type.
@param pDataType Data type.
@return True if succeed otherwise false.
*/
static bool _SQLCheckDataType(SQLSMALLINT pDataType)
{
switch(pDataType)
{
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_WCHAR:
case SQL_WVARCHAR:
case SQL_C_SSHORT:
case SQL_C_USHORT:
case SQL_SMALLINT:
case SQL_C_SLONG:
case SQL_C_ULONG:
case SQL_INTEGER:
case SQL_NUMERIC:
case SQL_DECIMAL:
case SQL_FLOAT:
case SQL_REAL:
case SQL_DOUBLE:
case SQL_TYPE_DATE:
case SQL_TYPE_TIME:
case SQL_TYPE_TIMESTAMP:
case SQL_BIT:
case SQL_DEFAULT:
case SQL_C_SBIGINT:
case SQL_C_UBIGINT:
case SQL_C_TINYINT:
case SQL_C_STINYINT:
case SQL_C_UTINYINT:
return true;
default:
LOG_ERROR_F_FUNC(TEXT("Unknown data type: %d"), pDataType);
return false;
}
}
/**
Check if the specified type is a valid interval code.
@param pIntervalCode Interval code.
@return True if succeed otherwise false.
*/
static bool _SQLCheckIntervalCode(SQLSMALLINT pIntervalCode)
{
// can check the interval code
return true;
}
/**
Set the value of data type and interval codes in descriptors.
@param pFldID Field identity.
@param pFldValue Field value.
@param pVerboseDataType Verbose data type.
@param pConciseDataType Concise data type.
@param pDateTimeIntervalCode Date time interval code.
@return True if succeed otherwise false.
*/
static bool _SQLSetDataType(SQLSMALLINT pFldID, SQLSMALLINT pFldValue,
SQLSMALLINT* pVerboseDataType,
SQLSMALLINT* pConciseDataType,
SQLSMALLINT* pDateTimeIntervalCode)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pFldID:%d, pFldValue:%d"),
LOG_FUNCTION_NAME,
pFldID, pFldValue);
// note
// the data type, concise data type, datetime interval code r interdependent
// setting one of these changes the other.
SQLSMALLINT conciseType;
SQLSMALLINT verboseType;
SQLSMALLINT datetimeInterval;
// initial values
conciseType = pConciseDataType ? *pConciseDataType : 0;
verboseType = pVerboseDataType ? *pVerboseDataType : 0;
datetimeInterval = pDateTimeIntervalCode ? *pDateTimeIntervalCode : 0;
// check if concise type has been specified
if(pFldID == SQL_DESC_CONCISE_TYPE)
{
// set the concise type itself first
conciseType = pFldValue;
// based on concise type set the verbose type and datetime interval
switch(conciseType)
{
case SQL_TYPE_DATE:
//case SQL_C_TYPE_DATE:
verboseType = SQL_DATETIME;
datetimeInterval = SQL_CODE_DATE;
break;
case SQL_TYPE_TIME:
//case SQL_C_TYPE_TIME:
verboseType = SQL_DATETIME;
datetimeInterval = SQL_CODE_TIME;
break;
case SQL_TYPE_TIMESTAMP:
//case SQL_C_TYPE_TIMESTAMP:
verboseType = SQL_DATETIME;
datetimeInterval = SQL_CODE_TIMESTAMP;
break;
case SQL_INTERVAL_MONTH:
//case SQL_C_INTERVAL_MONTH:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_MONTH;
break;
case SQL_INTERVAL_YEAR:
//case SQL_C_INTERVAL_YEAR:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_YEAR;
break;
case SQL_INTERVAL_YEAR_TO_MONTH:
//case SQL_C_INTERVAL_YEAR_TO_MONTH:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_YEAR_TO_MONTH;
break;
case SQL_INTERVAL_DAY:
//case SQL_C_INTERVAL_DAY:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_DAY;
break;
case SQL_INTERVAL_HOUR:
//case SQL_C_INTERVAL_HOUR:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_HOUR;
break;
case SQL_INTERVAL_MINUTE:
//case SQL_C_INTERVAL_MINUTE:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_MINUTE;
break;
case SQL_INTERVAL_SECOND:
//case SQL_C_INTERVAL_SECOND:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_SECOND;
break;
case SQL_INTERVAL_DAY_TO_HOUR:
//case SQL_C_INTERVAL_DAY_TOHOUR:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_DAY_TO_HOUR;
break;
case SQL_INTERVAL_DAY_TO_MINUTE:
//case SQL_C_INTERVAL_DAY_TO_MINUTE:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_DAY_TO_MINUTE;
break;
case SQL_INTERVAL_DAY_TO_SECOND:
//case SQL_C_INTERVAL_DAY_TO_SECOND:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_DAY_TO_SECOND;
break;
case SQL_INTERVAL_HOUR_TO_MINUTE:
//case SQL_C_INTERVAL_HOUR_TO_MINUTE:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_HOUR_TO_MINUTE;
break;
case SQL_INTERVAL_HOUR_TO_SECOND:
//case SQL_C_INTERVAL_HOUR_TO_SECOND:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_HOUR_TO_SECOND;
break;
case SQL_INTERVAL_MINUTE_TO_SECOND:
//case SQL_C_INTERVAL_MINUTE_TO_SECOND:
verboseType = SQL_INTERVAL;
datetimeInterval = SQL_CODE_MINUTE_TO_SECOND;
break;
default:
// check if data type if valid
if(_SQLCheckDataType(conciseType) != true)
return false;
// concise type does not relate to datetime or interval
// hence both concise and verbose type r equal
verboseType = conciseType;
datetimeInterval = 0;
}
}
// check if verbose data type is being set
else if(pFldID == SQL_DESC_TYPE)
{
// set the verbose type itself first
verboseType = pFldValue;
// based on verbose type & datetime interval code determine concise type
switch(verboseType)
{
case SQL_INTERVAL:
switch(datetimeInterval)
{
case SQL_CODE_DATE:
conciseType = SQL_TYPE_DATE;
break;
case SQL_CODE_TIME:
conciseType = SQL_TYPE_TIME;
break;
case SQL_CODE_TIMESTAMP:
conciseType = SQL_TYPE_TIMESTAMP;
break;
default:
// interval should have been set
LOG_ERROR_FUNC(TEXT("Interval code not yet set for SQL_INTERVAL"));
return false;
}
break;
case SQL_DATETIME:
switch(datetimeInterval)
{
case SQL_CODE_MONTH:
conciseType = SQL_INTERVAL_MONTH;
break;
case SQL_CODE_YEAR:
conciseType = SQL_INTERVAL_YEAR;
break;
case SQL_CODE_YEAR_TO_MONTH:
conciseType = SQL_INTERVAL_YEAR_TO_MONTH;
break;
case SQL_CODE_DAY:
conciseType = SQL_INTERVAL_DAY;
break;
case SQL_CODE_HOUR:
conciseType = SQL_INTERVAL_HOUR;
break;
case SQL_CODE_MINUTE:
conciseType = SQL_INTERVAL_MINUTE;
break;
case SQL_CODE_SECOND:
conciseType = SQL_INTERVAL_SECOND;
break;
case SQL_CODE_DAY_TO_HOUR:
conciseType = SQL_INTERVAL_DAY_TO_HOUR;
break;
case SQL_CODE_DAY_TO_MINUTE:
conciseType = SQL_INTERVAL_DAY_TO_MINUTE;
break;
case SQL_CODE_DAY_TO_SECOND:
conciseType = SQL_INTERVAL_DAY_TO_SECOND;
break;
case SQL_CODE_HOUR_TO_MINUTE:
conciseType = SQL_INTERVAL_HOUR_TO_MINUTE;
break;
case SQL_CODE_HOUR_TO_SECOND:
conciseType = SQL_INTERVAL_HOUR_TO_SECOND;
break;
case SQL_CODE_MINUTE_TO_SECOND:
conciseType = SQL_INTERVAL_MINUTE_TO_SECOND;
break;
default:
// interval should have been set
LOG_ERROR_FUNC(TEXT("Interval code not yet set for SQL_DATETIME"));
return false;
}
break;
default:
// check if data type if valid
if(_SQLCheckDataType(verboseType) != true)
return false;
// verbose type does not relate to datetime or interval
// hence both concise and verbose type r equal
conciseType = verboseType;
datetimeInterval = 0;
break;
}
}
else if(pFldID == SQL_DESC_DATETIME_INTERVAL_CODE)
{
// check if date interval code is valid
if(_SQLCheckIntervalCode(pFldValue) != true)
return false;
// set the datetime interval code, autonomously
datetimeInterval = pFldValue;
}
// unknown field to set
else
{
LOG_ERROR_FUNC(TEXT("Unknown field type"));
return false;
}
// pass back values to caller
if(pVerboseDataType)
*pVerboseDataType = verboseType;
if(pConciseDataType)
*pConciseDataType = conciseType;
if(pDateTimeIntervalCode)
*pDateTimeIntervalCode = datetimeInterval;
return true;
}
/**
Set a field value in ARD item.
@param pDesc ARD*
@param pDescItem ARDItem*
@param pFldID Field identity.
@param pDataPtr Data pointer.
@param pDataSize Data size.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLSetARDItemField(ARD* pDesc, ARDItem* pDescItem,
SQLSMALLINT pRecNum, SQLSMALLINT pFldID,
const SQLPOINTER pDataPtr, SQLINTEGER pDataSize)
{
LOG_DEBUG_F_FUNC(
TEXT("%s: pDesc: %d, pDescItem: %d, Recnum: %d, Fld: %d, ")
TEXT("DataPtr: %d, DataSize: %d"),
LOG_FUNCTION_NAME,
pDesc, pDescItem, pRecNum, pFldID, pDataPtr, pDataSize);
ARDItem* item;
// precaution
if(pDesc == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid params"));
return SQL_ERROR;
}
// check if item has not been specified directly
if(pDescItem == NULL)
{
// get item from ARD
item = _SQLGetARDItem(pDesc, pRecNum);
// check if item located
if(item == NULL)
{
LOG_ERROR_FUNC(TEXT("Invalid item"));
return SQL_ERROR;
}
}
else
{
item = pDescItem;
}
// as per required field
switch(pFldID)
{
case SQL_DESC_CONCISE_TYPE:
_SQLSetDataType(SQL_DESC_CONCISE_TYPE,
(SQLSMALLINT)((std::size_t)pDataPtr),
&(item->dataVerboseType), &(item->dataConciseType),
&(item->dateTimeIntervalCode));
break;
case SQL_DESC_DATA_PTR:
item->dataPtr = pDataPtr;
break;
case SQL_DESC_DATETIME_INTERVAL_CODE:
_SQLSetDataType(SQL_DESC_DATETIME_INTERVAL_CODE,
(SQLSMALLINT)((std::size_t)pDataPtr),
&(item->dataVerboseType), &(item->dataConciseType),
&(item->dateTimeIntervalCode));
break;
case SQL_DESC_DATETIME_INTERVAL_PRECISION:
item->dateTimeIntervalPrec = (SQLSMALLINT)((std::size_t)pDataPtr);
break;
case SQL_DESC_INDICATOR_PTR:
item->sizeIndPtr = (SQLINTEGER*)((std::size_t)pDataPtr);
break;
case SQL_DESC_LENGTH:
case SQL_DESC_OCTET_LENGTH:
item->dataSize = (SQLINTEGER)((std::size_t)pDataPtr);
break;
case SQL_DESC_NUM_PREC_RADIX:
item->numPrecRadix = (SQLINTEGER)((std::size_t)pDataPtr);
break;
case SQL_DESC_OCTET_LENGTH_PTR: // 1004
item->sizePtr = (SQLINTEGER*)((std::size_t)pDataPtr);
break;
case SQL_DESC_PRECISION:
// bytes required for numeric type
item->dataSize = (SQLSMALLINT)((std::size_t)pDataPtr);
break;
case SQL_DESC_SCALE:
item->scale = (SQLSMALLINT)((std::size_t)pDataPtr);
break;
case SQL_DESC_TYPE:
_SQLSetDataType(SQL_DESC_TYPE,
(SQLSMALLINT)((std::size_t)pDataPtr),
&(item->dataVerboseType), &(item->dataConciseType),
&(item->dateTimeIntervalCode));
break;
default:
LOG_ERROR_F_FUNC(TEXT("unknown field (%d)."), pFldID);
return SQL_ERROR;
}
return SQL_SUCCESS;
}
/**
Free/release the content of descriptor.
@param pDesc Pointer to descriptor.
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
template<typename T, typename I>
static RETCODE _FreeContent(T* pDesc, I*& itemList)
{
if(itemList)
{
delete itemList;
itemList = NULL;
}
// reset the highest descriptor count
pDesc->descCount = 0;
return SQL_SUCCESS;
}
/**
Free/release the content of ARD.
@param pDesc ARD*
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLFreeARDContent(ARD* pDesc)
{
return _FreeContent(pDesc, pDesc->bindCols);
}
/**
Free/release the content of IRD.
@param pDesc IRD*
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLFreeIRDContent(IRD* pDesc)
{
/* COLUMN HDRS */
if(pDesc->rowDesc)
{
IRDItemList::iterator i = pDesc->rowDesc->begin();
IRDItemList::iterator iEnd = pDesc->rowDesc->end();
for(; i != iEnd; ++i)
{
IRDItem* columnHeader = &(*i);
if(columnHeader->pszSQL_DESC_BASE_COLUMN_NAME)
free(columnHeader->pszSQL_DESC_BASE_COLUMN_NAME);
if(columnHeader->pszSQL_DESC_BASE_TABLE_NAME)
free(columnHeader->pszSQL_DESC_BASE_TABLE_NAME);
if(columnHeader->pszSQL_DESC_CATALOG_NAME)
free(columnHeader->pszSQL_DESC_CATALOG_NAME);
if(columnHeader->pszSQL_DESC_LABEL)
free(columnHeader->pszSQL_DESC_LABEL);
if(columnHeader->pszSQL_DESC_LITERAL_PREFIX)
free(columnHeader->pszSQL_DESC_LITERAL_PREFIX);
if(columnHeader->pszSQL_DESC_LITERAL_SUFFIX)
free(columnHeader->pszSQL_DESC_LITERAL_SUFFIX);
if(columnHeader->pszSQL_DESC_LOCAL_TYPE_NAME)
free(columnHeader->pszSQL_DESC_LOCAL_TYPE_NAME);
if(columnHeader->pszSQL_DESC_NAME)
free(columnHeader->pszSQL_DESC_NAME);
if(columnHeader->pszSQL_DESC_SCHEMA_NAME)
free(columnHeader->pszSQL_DESC_SCHEMA_NAME);
if(columnHeader->pszSQL_DESC_TABLE_NAME)
free(columnHeader->pszSQL_DESC_TABLE_NAME);
if(columnHeader->pszSQL_DESC_TYPE_NAME)
free(columnHeader->pszSQL_DESC_TYPE_NAME);
}
}
return _FreeContent(pDesc, pDesc->rowDesc);
}
/**
Free/release the content of APD.
@param pDesc APD*
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLFreeAPDContent(APD* pDesc)
{
// since params have not been implemented
// it assumes that no params have been allocated
return _FreeContent(pDesc, pDesc->bindParams);
}
/**
Free/release the content of IPD.
@param pDesc IPD*
@return SQL_SUCCESS if OK otherwise SQL_ERROR.
*/
RETCODE _SQLFreeIPDContent(IPD* pDesc)
{
// since params have not been implemented
// it assumes that no params have been allocated
return _FreeContent(pDesc, pDesc->bindParams);
}
| {
"content_hash": "9507af18d941d57f9a942759595f4e4a",
"timestamp": "",
"source": "github",
"line_count": 1257,
"max_line_length": 77,
"avg_line_length": 24.184566428003183,
"alnum_prop": 0.6911513157894736,
"repo_name": "yichenghuang/BigObject-ODBC",
"id": "c50ad27336afc71394b1847f24941a7ecf0a60f7",
"size": "31190",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/Driver/API/_Descriptor.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1440"
},
{
"name": "C",
"bytes": "3820"
},
{
"name": "C++",
"bytes": "547464"
}
],
"symlink_target": ""
} |
package com.verizon.bda.trapezium.dal.lucene
import com.verizon.bda.trapezium.dal.exceptions.LuceneDAOException
import org.apache.spark.sql.Row
import org.apache.spark.sql.types._
import org.slf4j.LoggerFactory
/**
* @author debasish83 on 12/22/16.
* Supports primitives for extracting doc value fields
*/
class DocValueExtractor(leafReaders: Seq[LuceneReader],
converter: OLAPConverter) extends Serializable {
private val logger = LoggerFactory.getLogger(this.getClass)
val schema = converter.schema
val dimensions = converter.dimensions
val storedDimensions = converter.storedDimensions
val measures = converter.measures
val ser = converter.ser
private val dvMap: Map[String, DocValueAccessor] = if (leafReaders.length > 0) {
val fields = schema.filter(field => {
storedDimensions.contains(field.name) || measures.contains(field.name)
})
fields.map { case (field) =>
val fieldName = field.name
val fieldMultiValued = (field.dataType.isInstanceOf[ArrayType])
// Dimensions have gone through DictionaryEncoding and uses sorted-setnumeric storage
val accessor = if (storedDimensions.contains(fieldName)) {
DocValueAccessor(leafReaders, fieldName, IntegerType, true, ser)
} else {
DocValueAccessor(leafReaders, fieldName, field.dataType, fieldMultiValued, ser)
}
fieldName -> accessor
}.toMap
} else {
Map.empty[String, DocValueAccessor]
}
private def extractStored(docID: Int, column: String): Any = {
val offset = dvMap(column).getOffset(docID)
if (offset <= 0) return null
//multi-value dimension/measure
if (offset > 1) Seq((0 until offset).map(dvMap(column).extract(docID, _)): _*)
else dvMap(column).extract(docID, 0)
}
// only storedDimensions and measures can be extracted
def extract(columns: Seq[String], docID: Int): Row = {
if (dvMap.size > 0) {
val sqlFields = columns.map((column) => {
if (storedDimensions.contains(column) || measures.contains(column))
extractStored(docID, column)
else throw new LuceneDAOException(s"unsupported ${column} in doc value extraction")
})
Row.fromSeq(sqlFields)
} else {
Row.empty
}
}
def getOffset(column: String, docID: Int): Int = {
dvMap(column).getOffset(docID)
}
def extract(column: String, docID: Int, offset: Int): Any = {
dvMap(column).extract(docID, offset)
}
}
object DocValueExtractor {
def apply(leafReaders: Seq[LuceneReader],
converter: OLAPConverter): DocValueExtractor = {
new DocValueExtractor(leafReaders, converter)
}
}
| {
"content_hash": "ec2dc6048429c49e0ba5b150ff1303c7",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 91,
"avg_line_length": 34.07692307692308,
"alnum_prop": 0.6914973664409331,
"repo_name": "Verizon/trapezium",
"id": "25e942115b53b0f0084630673500925b8543ed7b",
"size": "2658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dal/src/main/scala/com/verizon/bda/trapezium/dal/lucene/DocValueExtractor.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9549"
},
{
"name": "Scala",
"bytes": "804859"
},
{
"name": "Shell",
"bytes": "2312"
}
],
"symlink_target": ""
} |
/**
* Created by Administrator on 2016/6/15.
*/
$(document).ready(function(){
$("#btn").on("click",function(){
$.get("Server.php",{name:$("#namevalue").val()},function(data){
$("#result").text(data);
})
})
}); | {
"content_hash": "4b3159af52185db2bbe02385bc007445",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 70,
"avg_line_length": 24.2,
"alnum_prop": 0.512396694214876,
"repo_name": "wangyongtan/H5",
"id": "9a7fb746afa9507f8e8568c7dde1d026e2d21167",
"size": "242",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/0615-JQuery AJAX/AJAX-1.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1234078"
},
{
"name": "CoffeeScript",
"bytes": "47898"
},
{
"name": "HTML",
"bytes": "2003454"
},
{
"name": "JavaScript",
"bytes": "5897063"
},
{
"name": "PHP",
"bytes": "44117"
},
{
"name": "Smarty",
"bytes": "17587"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51a.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-51a.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sink: w32_execvp
* BadSink : execute command with wexecvp
* Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT L"cmd.exe"
#define COMMAND_ARG1 L"/c"
#define COMMAND_ARG2 L"dir"
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH L"/bin/sh"
#define COMMAND_INT L"sh"
#define COMMAND_ARG1 L"ls"
#define COMMAND_ARG2 L"-la"
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#include <process.h>
#define EXECVP _wexecvp
#ifndef OMITBAD
/* bad function declaration */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51b_badSink(wchar_t * data);
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51_bad()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51b_badSink(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51b_goodG2BSink(wchar_t * data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t dataBuffer[100] = L"";
data = dataBuffer;
/* FIX: Append a fixed string to data (not user / external input) */
wcscat(data, L"*.*");
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51b_goodG2BSink(data);
}
void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "5200013b8d94ef3a833666c84737111b",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 112,
"avg_line_length": 29.079601990049753,
"alnum_prop": 0.5837467921300257,
"repo_name": "maurer/tiamat",
"id": "2dc700f1bdee48a53eb2acbf5c66f7e70ac87142",
"size": "5845",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE78_OS_Command_Injection/s08/CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execvp_51a.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php
namespace StackGuru\Commands\Scanner;
use StackGuru\Core\Command\AbstractCommand;
use StackGuru\Core\Command\CommandContext;
use React\Promise\Promise as Promise;
use React\Promise\Deferred as Deferred;
use StackGuru\Core\Utils\Response as Response;
class RemoveRole extends AbstractCommand
{
protected static $name = "removerole";
protected static $description = "Removes a role from all users.";
protected static $default = ""; // default sub-command
public function process(string $query, CommandContext $ctx): Promise
{
if (!(strpos($query, "<@&") !== false)) {
return "Did you mention a role?";
}
var_dump($query);
$output = null;
preg_match('~<@&(.*?)>~', $query, $output);
if (2 != sizeof($output)) {
return "Did you mention more than one role? Try to `!scanner giveusersrole @random` where random is a legit role.";
}
$roleid = $output[1];
if (!isset($ctx->guild->roles[$roleid])) {
return "Role given does not exist in this guild. Talk to bot engineers..";
}
$role = $ctx->guild->roles[$roleid];
foreach($ctx->guild->members as $member) {
$member->removeRole($role);
$ctx->guild->members->save($member);
}
$res = "Successfully removed role `{$role->name}` from every user.";
return Response::sendMessage($res, $ctx->message);
}
}
| {
"content_hash": "5263c8225d919525809a2847986975e8",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 127,
"avg_line_length": 29.857142857142858,
"alnum_prop": 0.608339029391661,
"repo_name": "sciencefyll/stack-guru",
"id": "e7f2b7a6443e0e7344f6e0cd88bab5e6d79410e8",
"size": "1463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Commands/Scanner/RemoveRole.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "68"
},
{
"name": "PHP",
"bytes": "175039"
},
{
"name": "Shell",
"bytes": "4277"
}
],
"symlink_target": ""
} |
<?php
/**
* Extended Identical validator. Added recursive context search.
*
* @category Modern
* @package Modern_Validate
* @author Rafał Gałka <rafal@modernweb.pl>
* @copyright Copyright (c) 2007-2012 ModernWeb (http://www.modernweb.pl)
*/
class Modern_Validate_Identical extends Zend_Validate_Identical
{
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if a token has been set and the provided value
* matches that token.
*
* @param mixed $value
* @param array $context
* @return boolean
*/
public function isValid($value, $context = null)
{
$this->_setValue((string) $value);
if (is_array($context)) {
$token = $this->_searchInContext($context, $this->getToken());
} else {
$token = $this->getToken();
}
if ($token === null) {
$this->_error(self::MISSING_TOKEN);
return false;
}
$strict = $this->getStrict();
if (($strict && ($value !== $token)) || (!$strict && ($value != $token))) {
$this->_error(self::NOT_SAME);
return false;
}
return true;
}
/**
* @param array $context
* @param string $key
* @return mixed
*/
protected function _searchInContext(array &$context, $key)
{
foreach ($context as $k => $value) {
if ($k == $key) {
return $value;
}
// recursive search in hash arrays
if (is_array($value) && !is_int(key($value))) {
$value = $this->_searchInContext($value, $key);
if (null !== $value) {
return $value;
}
}
}
return null;
}
}
| {
"content_hash": "82cf5554f1085fdd30eb7b7bdb3cb6df",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 83,
"avg_line_length": 24.876712328767123,
"alnum_prop": 0.5,
"repo_name": "Hagith/zf1-lib",
"id": "082a1ad1c6dfa8fcdb30509c34ed041aba8cef22",
"size": "2533",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "library/Modern/Validate/Identical.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "550659"
}
],
"symlink_target": ""
} |
<?php
namespace gexo\image\transformer;
/**
* Must be implemented by all cropper transformers
*
* @copyright 2014 Stefan Oswald
* @link https://github.com/gexo/GexoImage
* @author Stefan Oswald <github@gexo.de>
*/
interface iCropper extends iTransformer {
/**
*
* @return integer
*/
public function getStartX();
/**
*
* @param integer $startX
* @return iCropper
*/
public function setStartX($startX);
/**
*
* @return integer
*/
public function getStartY();
/**
*
* @param integer $startY
* @return iCropper
*/
public function setStartY($startY);
/**
*
* @return integer
*/
public function getWidth();
/**
*
* @param integer $width
* @return iCropper
*/
public function setWidth($width);
/**
*
* @return integer
*/
public function getHeight();
/**
*
* @param integer $height
* @return iCropper
*/
public function setHeight($height);
}
| {
"content_hash": "d9245b070a6be2fd47fb09f0bd465997",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 50,
"avg_line_length": 14.82089552238806,
"alnum_prop": 0.5830815709969789,
"repo_name": "gexo/GexoImage",
"id": "b7a352241fc5cb0ecfabcce299c544e6fc748304",
"size": "2214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/transformer/iCropper.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "73966"
}
],
"symlink_target": ""
} |
import Tapable = require('tapable');
class DllPlugin {
apply(compiler: Compiler) {
compiler.plugin('doSomething', function (...args: string[]) {
console.log(args);
});
compiler.plugin(['doSomething', 'doNothing'], function (...args: string[]) {
console.log(args);
});
}
}
class Compiler extends Tapable {
constructor(){
super()
}
}
const compiler = new Compiler();
let callback: Tapable.CallbackFunction = function () {
};
compiler.apply(new DllPlugin());
compiler.applyPlugins('doSomething', 'a', 'b');
compiler.applyPluginsWaterfall('doSomething', 'a', 'b');
compiler.applyPluginsWaterfall0('doSomething', 'a');
compiler.applyPluginsBailResult('doSomething', 'a', 'b');
compiler.applyPluginsBailResult1('doSomething', ['a', 'b']);
compiler.applyPluginsAsync('doSomething', 'a', 'b');
compiler.applyPluginsAsyncSeries('doSomething', 'a', 'b');
compiler.applyPluginsAsyncSeriesBailResult('doSomething', 'a', 'b');
compiler.applyPluginsAsyncSeriesBailResult1('doSomething', 'a', callback);
compiler.applyPluginsAsyncWaterfall('doSomething', 'a', callback);
compiler.applyPluginsParallel('doSomething', 'a', 'b');
compiler.applyPluginsParallelBailResult('doSomething', 'a', 'b');
compiler.applyPluginsParallelBailResult1('doSomething', 'a', callback);
| {
"content_hash": "b6ba5b5095391c5b29e370173d5df417",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 84,
"avg_line_length": 32.63414634146341,
"alnum_prop": 0.6920777279521674,
"repo_name": "schmuli/DefinitelyTyped",
"id": "eca641655c5ecdd6b2f55ca99d30361f59c3a21c",
"size": "1375",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tapable/tapable-tests.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "308"
},
{
"name": "JavaScript",
"bytes": "5135"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "23857859"
}
],
"symlink_target": ""
} |
<?php
// Set timezone so tests run consistently independent of machine's timezone
date_default_timezone_set('GMT');
require __DIR__ . '/../vendor/autoload.php';
| {
"content_hash": "42b656bb65e632d6284a22bba57b9c94",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 75,
"avg_line_length": 27.166666666666668,
"alnum_prop": 0.7177914110429447,
"repo_name": "gajus/bugger",
"id": "56277e0937b5e20231191040cdc02018833518e6",
"size": "163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/bootstrap.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "233701"
},
{
"name": "JavaScript",
"bytes": "34135"
},
{
"name": "PHP",
"bytes": "14880"
},
{
"name": "Ruby",
"bytes": "578"
},
{
"name": "Shell",
"bytes": "245"
}
],
"symlink_target": ""
} |
from lib import wphttp
from lib import wpprint
from generic import wpgeneric
from plugins import wpplugin
from themes import wptheme
from users import wpusers
class wpall:
def run(self,agent,proxy,redirect,url):
wpgeneric.wpgeneric().run(agent,proxy,redirect,url)
wptheme.wptheme(agent,proxy,redirect,url).run()
wpplugin.wpplugin(agent,proxy,redirect,url).run()
wpusers.wpusers(agent,proxy,redirect,url).run() | {
"content_hash": "f56a9ac5878a7d530891ba4ddc8d915d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 53,
"avg_line_length": 32.38461538461539,
"alnum_prop": 0.7933491686460807,
"repo_name": "Yukinoshita47/Yuki-Chan-The-Auto-Pentest",
"id": "2770cf3df279fee39c0af675e3d99d3214d51c77",
"size": "1215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Module/WPSeku/modules/discovery/wpall.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "36211"
},
{
"name": "JavaScript",
"bytes": "3038"
},
{
"name": "Makefile",
"bytes": "1360"
},
{
"name": "Perl",
"bytes": "108876"
},
{
"name": "Python",
"bytes": "3034585"
},
{
"name": "Roff",
"bytes": "6738"
},
{
"name": "Ruby",
"bytes": "2693582"
},
{
"name": "Shell",
"bytes": "53755"
},
{
"name": "XSLT",
"bytes": "5475"
}
],
"symlink_target": ""
} |
MQTT-Stage
==========
This utility trigger actions based on MQTT messages. To trigger the script simply put in a file path coresponding to the topic you want to trigger it on.
MQTT Stage produces and acts on MQTT messages by running a number of user defined or predefined python scripts.
The scipts are divided into two types, actors and reactors. An actor script runns continously and produces MQTT messages based om some hardware or webresource that it is connected to. An reactor is triggered to run each time a specific event is recieved.
In the MQTT stage directory there are three directories. One the actors directory the reactors directory and the topics directory. Whenever a new topic is recived over MQTT a folder path matching the topic is created inside topics.
To trigger a scrit place it inside the topic path or create a sympolic link into the path. The script will be started on the first message with the topic maching the script path.
Example of link
> ln -s ~/MQTT-Stage/reactors/writeDB.py /MQTT-Stage/topics/myhome/livingroom/temp/updatedatabase.react.py
This will cause the script writeDB to be run whenever we recive a message with the topic: /myhome/livingroom/temp
Scripts needs to be exeutable in order to run.
A reactor script
________________
The script need to be named NAME.react.py to be run as a reactor script. The script will be called with the same parameter set as the mosquitto_pub command.
An actor script
________________
Should be named NAME.actor.py
The actor scripts are started immediatly if they are linked or placed in the actor/run-always folder.
The are otherwise started on the first message mathching the path.
The project is a work in progress state. Estimated alfa release is 24 of april.
| {
"content_hash": "ae327c08eb5310d82e275b6a447f98de",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 255,
"avg_line_length": 53.54545454545455,
"alnum_prop": 0.7753254102999434,
"repo_name": "Anton04/MQTT-Stage",
"id": "0639f7a7bba89986913660cd170a30357ff5765d",
"size": "1767",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "21694"
},
{
"name": "Shell",
"bytes": "4965"
}
],
"symlink_target": ""
} |
package com.byteslounge.slickrepo.test.derby
import com.byteslounge.slickrepo.test.{DerbyConfig, LongInstantVersionedRepositoryTest}
class DerbyLongInstantVersionedRepositoryTest extends LongInstantVersionedRepositoryTest(DerbyConfig.config)
| {
"content_hash": "6b76e179d75b41ff1e75c2b58c672cd0",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 108,
"avg_line_length": 35.142857142857146,
"alnum_prop": 0.8902439024390244,
"repo_name": "gonmarques/slick-repo",
"id": "3a4ab90be493005f359ab3c0cad8210cd3e3c2b4",
"size": "1384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/scala/com/byteslounge/slickrepo/test/derby/DerbyLongInstantVersionedRepositoryTest.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Scala",
"bytes": "327161"
},
{
"name": "Shell",
"bytes": "1211"
}
],
"symlink_target": ""
} |
rust-tiled
==========
A library for the Tiled editor format, written in Rust
| {
"content_hash": "bdd8e3456ba0d870a583afd2c640ca1b",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 54,
"avg_line_length": 19.5,
"alnum_prop": 0.6794871794871795,
"repo_name": "Denommus/rust-tiled",
"id": "e029f3d08403caf8e8db93e1bba9296f64e6c068",
"size": "78",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "71"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pts: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.2 / pts - 8.10.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
pts
<small>
8.10.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-22 01:18:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-22 01:18:02 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/pts"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/PTS"]
depends: [
"camlp5"
"ocaml"
"coq" {>= "8.10" & < "8.11~"}
]
tags: [
"keyword: pure type systems"
"keyword: metatheory"
"category: Computer Science/Lambda Calculi"
"date: 2007-03"
]
authors: [
"Bruno Barras"
]
bug-reports: "https://github.com/coq-contribs/pts/issues"
dev-repo: "git+https://github.com/coq-contribs/pts.git"
synopsis: "A formalisation of Pure Type Systems"
description: """
This contrib is a formalization of Pure Type Systems. It includes most
of the basic metatheoretical properties: weakening, substitution,
subject-reduction, decidability of type-checking (for strongly normalizing
PTSs). Strengtheningis not proven here.
The kernel of a very simple proof checker is automatically generated from
the proofs. A small interface allows interacting with this kernel, making
up a standalone proof system.
The Makefile has a special target "html" that produces html files from the
sources and main.html that gives a short overview."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/pts/archive/v8.10.0.tar.gz"
checksum: "md5=2bb2bf48ad239d3d6cc535c3b3a581b2"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-pts.8.10.0 coq.8.8.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.2).
The following dependencies couldn't be met:
- coq-pts -> coq >= 8.10 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-pts.8.10.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "cff35e5a579558ef12cb0533860e0ea3",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 159,
"avg_line_length": 41.110497237569064,
"alnum_prop": 0.5562424405321865,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "74429b936a8fad1b5321b3811da8b12141cc46f6",
"size": "7466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.2/pts/8.10.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<?php // Vars: $articlePager
use_helper('Date');
echo $articlePager->renderNavigationTop();
echo _open('ul.elements');
foreach ($articlePager as $article)
{
echo _open('li.element');
// wrap the article link into a H2 tag with the t_medium CSS class
echo _tag('h2.t_medium', _link($article));
// show the article extract, processed with markdown
echo markdown($article->extract, '.extract');
// in a P tag, we put some infos about the article
echo _tag('p.article_infos',
// creation date of the article, formatted with a symfony helper
_tag('span', format_date($article->createdAt, 'D')).
' | '.
// article author
_tag('span', $article->Author).
' | '.
// another link to the article, with the "Read more" translated text
_link($article)->text(__('Read more...'))
);
echo _close('li');
}
echo _close('ul');
echo $articlePager->renderNavigationBottom(); | {
"content_hash": "1aa4cbcd201bfa3765b319332510e6ba",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 76,
"avg_line_length": 27.027027027027028,
"alnum_prop": 0.591,
"repo_name": "carechimba/diem",
"id": "7857ac69723399959cff36fb65fe46ce8a028b66",
"size": "1000",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Acme/apps/front/modules/article/templates/_list.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1447883"
},
{
"name": "PHP",
"bytes": "6562230"
},
{
"name": "Shell",
"bytes": "5570"
}
],
"symlink_target": ""
} |
<?php
namespace Dog2puppy\LoadScreen;
use pocketmine\command\Command;
use pocketmine\command\CommandSender;
use pocketmine\event\Listener;
use pocketmine\network\protocol\ChangeDimensionPacket;
use pocketmine\plugin\PluginBase;
class Main extends PluginBase implements Listener
{
public function onEnable()
{
$this->getServer()->getPluginManager()->registerEvents($this, $this);
}
public function onCommand(Command $command, CommandSender $sender, $label, array $args)
{
if ($command->getName() == 'loadscreen') {
$x = $sender->getX();
$y = $sender->getY();
$z = $sender->getZ();
$pk = new ChangeDimensionPacket();
$pk->dimension = 1; //1 is the nether; 0 is the overworld
$pk->x = (int) $x; //define X
$pk->y = (int) $y; //define Y
$pk->z = (int) $z; //define Z
$sender->dataPacket($pk); //$player must be an instance of a pocketmine/Player
$pk = new ChangeDimensionPacket();
$pk->dimension = 0; //1 is the nether; 0 is the overworld
$pk->x = (int) $x; //define X
$pk->y = (int) $y; //define Y
$pk->z = (int) $z; //define Z
$sender->dataPacket($pk); //$player must be an instance of a pocketmine/Player
if ($args[0] == 'message') {
$player->sendMessage('[LoadScreen] Showed the loading screen');
}
}
}
}
| {
"content_hash": "9a3e31f30ff5ce7a18fbe3956fa04070",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 91,
"avg_line_length": 34.5609756097561,
"alnum_prop": 0.5899788285109386,
"repo_name": "Dog2puppy/LoadScreen",
"id": "b8308e1699aa49192653ca7f28ad79a58c40db5f",
"size": "1417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Dog2puppy/LoadScreen/Main.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1417"
}
],
"symlink_target": ""
} |
title: Customizing the Quick Access Menu
page_title: Customizing the Quick Access Menu - RadRibbonBar
description: Quick Access Toolbar is an area of RadRibbonBar above the tabs.
slug: winforms/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu
tags: customizing,the,quick,access,menu
published: True
position: 5
previous_url: ribbonbar-programming-radribbonbar-customizing-the-quick-access-menu
---
# Customizing the Quick Access Menu
__Quick Access Toolbar__ is an area of __RadRibbonBar__ above the tabs.
>caption Figure 1: Quick Access Toolbar

__Quick Access Toolbar__ can contain the same elements as __RadMenu.__
## Adding Items to Quick Access Toolbar
Add items to __Quick Access Toolbar__ through __RadRibbonBar.QuickAccessToolBarItems__ collection.
This example adds two items. The first is a __RadMenuItem__. The __RadMenuItem__ will not change its display when the user hovers the mouse over it. If you would like that effect, use the custom item, __RadButtonElement__, instead. The second item added to the __Quick Access Toolbar__ is a __RadButtonElement__.
In order to capture the click event of the items, add an event handler for another method. In the example, the __NewFile__ method will be run when the user clicks on the __RadMenuItem__. A method called __QuickPrint__ will be run when the user clicks on the __RadButtonElement__.
#### Adding items to QuickAccessToolbar
{{source=..\SamplesCS\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheQuickAccessMenu.cs region=addingItemsToQuickAccessToolBar}}
{{source=..\SamplesVB\RibbonBar\ProgrammingRadRibbonBar\CustomizingTheQuickAccessMenu.vb region=addingItemsToQuickAccessToolBar}}
````C#
RadMenuItem mnuQANew = new RadMenuItem();
mnuQANew.Click += new EventHandler(NewFile);
mnuQANew.Text = "Menu item: New File";
radRibbonBar1.QuickAccessToolBarItems.Add(mnuQANew);
RadButtonElement mnuQAPrint = new RadButtonElement();
mnuQAPrint.Click += new EventHandler(QuickPrint);
mnuQAPrint.Text = "Menu item: Quick Print";
radRibbonBar1.QuickAccessToolBarItems.Add(mnuQAPrint);
````
````VB.NET
Dim mnuQANew As New RadMenuItem
AddHandler mnuQANew.Click, AddressOf NewFile
mnuQANew.Text = "Menu item: New File"
RadRibbonBar1.QuickAccessToolBarItems.Add(mnuQANew)
Dim mnuQAPrint As New RadButtonElement
AddHandler mnuQAPrint.Click, AddressOf QuickPrint
mnuQAPrint.Text = "Menu item: Print"
RadRibbonBar1.QuickAccessToolBarItems.Add(mnuQAPrint)
````
{{endregion}}
>note The **RadQuickAccessToolBar** exposes the **SetItemVisibility** method which can be used at run-time to toggle the visible state of its items.
## Relocating the Quick Access Toolbar
The Quick Access Toolbar can be positioned below the ribbon bar setting the value of __RadRibbonBar1.QuickAccessToolbarBelowRibbon__ to *true*.
__Quick Access ToolBar__ supports mnemonics.
## See Also
* [Design Time]({%slug winforms/ribbonbar/design-time%})
* [Structure]({%slug winforms/ribbonbar/structure%})
* [Getting Started]({%slug winforms/ribbonbar/getting-started%})
* [Backstage View]({%slug winforms/ribbonbar/backstage-view/overview%})
* [Themes]({%slug winforms/ribbonbar/customizing-appearance/themes%})
| {
"content_hash": "59c54fe56d84eefd720d148313cfb528",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 314,
"avg_line_length": 47.27777777777778,
"alnum_prop": 0.7732079905992949,
"repo_name": "telerik/winforms-docs",
"id": "49f5940c5ae7d774a2d4838f40f6a023211cfdef",
"size": "3418",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controls/ribbonbar/programming-radribbonbar/customizing-the-quick-access-menu.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "96"
},
{
"name": "CSS",
"bytes": "2296"
},
{
"name": "HTML",
"bytes": "1629"
},
{
"name": "JavaScript",
"bytes": "42129"
},
{
"name": "Ruby",
"bytes": "882"
}
],
"symlink_target": ""
} |
using System;
using Newtonsoft.Json;
namespace VkNet.Model.RequestParams;
/// <summary>
/// Places Add Params
/// </summary>
[Serializable]
public class PlacesAddParams
{
/// <summary>
/// Название нового места
/// </summary>
[JsonProperty(propertyName: "title")]
public string Title { get; set; }
/// <summary>
/// Географическая широта нового места, заданная в градусах (от -90 до 90)
/// </summary>
[JsonProperty(propertyName: "latitude")]
public decimal Latitude { get; set; }
/// <summary>
/// Географическая долгота нового места, заданная в градусах (от -180 до 180)
/// </summary>
[JsonProperty(propertyName: "longitude")]
public decimal Longitude { get; set; }
/// <summary>
/// Строка с адресом нового места (например, Невский просп. 1)
/// </summary>
[JsonProperty(propertyName: "address")]
public string Address { get; set; }
/// <summary>
/// Идентификатор типа нового места, полученный методом places.getTypes
/// </summary>
[JsonProperty(propertyName: "type")]
public ulong Type { get; set; }
/// <summary>
/// Идентификатор страны нового места, полученный методом places.getCountries
/// </summary>
[JsonProperty(propertyName: "country")]
public ulong Country { get; set; }
/// <summary>
/// Идентификатор города нового места, полученный методом places.getCities
/// </summary>
[JsonProperty(propertyName: "city")]
public ulong City { get; set; }
} | {
"content_hash": "89a3e84bfc419ce20014d46fc9628398",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 78,
"avg_line_length": 26.547169811320753,
"alnum_prop": 0.6922530206112296,
"repo_name": "vknet/vk",
"id": "926586b35c8087819e1a12bef981332943a29e61",
"size": "1717",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "VkNet/Model/RequestParams/Places/PlacesAddParams.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3715513"
},
{
"name": "Dockerfile",
"bytes": "345"
},
{
"name": "HTML",
"bytes": "90930"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Class Larislackers\BinanceApi\Exception\BinanceApiException</title>
<link rel="stylesheet" href="resources/style.css?c2f33731c1948fbed7c333554678bfa68d4817da">
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li class="active">
<a href="namespace-Larislackers.html">
Larislackers<span></span>
</a>
<ul>
<li class="active">
<a href="namespace-Larislackers.BinanceApi.html">
BinanceApi<span></span>
</a>
<ul>
<li>
<a href="namespace-Larislackers.BinanceApi.Enums.html">
Enums </a>
</li>
<li class="active">
<a href="namespace-Larislackers.BinanceApi.Exception.html">
Exception </a>
</li>
</ul></li></ul></li>
</ul>
</div>
<hr>
<div id="elements">
<h3>Exceptions</h3>
<ul>
<li class="active"><a href="class-Larislackers.BinanceApi.Exception.BinanceApiException.html">BinanceApiException</a></li>
<li><a href="class-Larislackers.BinanceApi.Exception.LarislackersException.html">LarislackersException</a></li>
</ul>
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="">
<input type="hidden" name="ie" value="UTF-8">
<input type="text" name="q" class="text" placeholder="Search">
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li>
<a href="namespace-Larislackers.BinanceApi.Exception.html" title="Summary of Larislackers\BinanceApi\Exception"><span>Namespace</span></a>
</li>
<li class="active">
<span>Class</span> </li>
</ul>
<ul>
</ul>
<ul>
</ul>
</div>
<div id="content" class="class">
<h1>Class BinanceApiException</h1>
<div class="description">
<p>Class BinanceApiException</p>
</div>
<dl class="tree">
<dd style="padding-left:0px">
Exception
implements
<span>Throwable</span>
</dd>
<dd style="padding-left:30px">
<img src="resources/inherit.png" alt="Extended by">
<b><span>Larislackers\BinanceApi\Exception\BinanceApiException</span></b>
</dd>
</dl>
<div class="info">
<b>Namespace:</b> <a href="namespace-Larislackers.html">Larislackers</a>\<a href="namespace-Larislackers.BinanceApi.html">BinanceApi</a>\<a href="namespace-Larislackers.BinanceApi.Exception.html">Exception</a><br>
<b>Package:</b> \Larislackers\BinanceApi\Exception<br>
<b>Located at</b> <a href="source-class-Larislackers.BinanceApi.Exception.BinanceApiException.html#5-60" title="Go to source code">Exception/BinanceApiException.php</a>
<br>
</div>
<table class="summary methods" id="methods">
<caption>Methods summary</caption>
<tr data-order="__construct" id="___construct">
<td class="attributes"><code>
public
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#___construct">#</a>
<code><a href="source-class-Larislackers.BinanceApi.Exception.BinanceApiException.html#26-37" title="Go to source code">__construct</a>( <span>string <var>$message</var></span>, <span>integer <var>$code</var> = <span class="php-num">0</span></span>, <span>Exception <var>$previous</var> = <span class="php-keyword1">null</span></span> )</code>
<div class="description short">
<p>BinanceApiException constructor.</p>
</div>
<div class="description detailed hidden">
<p>BinanceApiException constructor.</p>
<h4>Parameters</h4>
<div class="list"><dl>
<dt><var>$message</var></dt>
<dd>The exception message.</dd>
<dt><var>$code</var></dt>
<dd>The exception code.</dd>
<dt><var>$previous</var></dt>
<dd>The previous exceptions.</dd>
</dl></div>
<h4>Overrides</h4>
<div class="list"><code>Exception::__construct()</code></div>
</div>
</div></td>
</tr>
<tr data-order="__toString" id="___toString">
<td class="attributes"><code>
public
string
</code>
</td>
<td class="name"><div>
<a class="anchor" href="#___toString">#</a>
<code><a href="source-class-Larislackers.BinanceApi.Exception.BinanceApiException.html#39-47" title="Go to source code">__toString</a>( )</code>
<div class="description short">
<p>String representation of the exception.</p>
</div>
<div class="description detailed hidden">
<p>String representation of the exception.</p>
<h4>Returns</h4>
<div class="list">
string
</div>
<h4>Overrides</h4>
<div class="list"><code>Exception::__toString()</code></div>
</div>
</div></td>
</tr>
</table>
<table class="summary inherited">
<caption>Methods inherited from Exception</caption>
<tr>
<td><code>
__wakeup(),
getCode(),
getFile(),
getLine(),
getMessage(),
getPrevious(),
getTrace(),
getTraceAsString()
</code></td>
</tr>
</table>
<table class="summary properties" id="properties">
<caption>Properties summary</caption>
<tr data-order="code" id="$code">
<td class="attributes"><code>
protected
integer
</code></td>
<td class="name">
<a href="source-class-Larislackers.BinanceApi.Exception.BinanceApiException.html#12-17" title="Go to source code"><var>$code</var></a>
<div class="description short">
<p>Error code.</p>
</div>
<div class="description detailed hidden">
<p>Error code.</p>
</div>
</td>
<td class="value">
<div>
<a href="#$code" class="anchor">#</a>
<code></code>
</div>
</td>
</tr>
<tr data-order="message" id="$message">
<td class="attributes"><code>
protected
string
</code></td>
<td class="name">
<a href="source-class-Larislackers.BinanceApi.Exception.BinanceApiException.html#19-24" title="Go to source code"><var>$message</var></a>
<div class="description short">
<p>Error message.</p>
</div>
<div class="description detailed hidden">
<p>Error message.</p>
</div>
</td>
<td class="value">
<div>
<a href="#$message" class="anchor">#</a>
<code></code>
</div>
</td>
</tr>
</table>
<table class="summary inherited">
<caption>Properties inherited from Exception</caption>
<tr>
<td><code>
<var>$file</var>,
<var>$line</var>
</code></td>
</tr>
</table>
</div>
<div id="footer">
API documentation generated by <a href="http://apigen.org">ApiGen</a>
</div>
</div>
</div>
<script src="resources/combined.js"></script>
<script src="elementlist.js"></script>
</body>
</html>
| {
"content_hash": "b21eb50926889d8ef8b44846a014f9eb",
"timestamp": "",
"source": "github",
"line_count": 320,
"max_line_length": 345,
"avg_line_length": 20.75625,
"alnum_prop": 0.626317374284854,
"repo_name": "larislackers/php-binance",
"id": "f80f48733a220ee904d8430dd519a820c1a688f3",
"size": "6642",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/class-Larislackers.BinanceApi.Exception.BinanceApiException.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "32020"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Coffeescript-UI Documentation</title>
<script src='../../javascript/application.js'></script>
<script src='../../javascript/search.js'></script>
<link rel='stylesheet' href='../../stylesheets/application.css' type='text/css'>
</head>
<body>
<div id='base' data-path='../../'></div>
<div id='header'>
<div id='menu'>
<a href='../../alphabetical_index.html' title='Index'>
Index
</a>
»
<span class='title'>CUI</span>
»
<span class='title'>DataFieldProxy</span>
</div>
</div>
<div id='content'>
<h1>
Class:
CUI.DataFieldProxy
</h1>
<table class='box'>
<tr>
<td>Defined in:</td>
<td>base/DataField/DataFieldProxy.coffee</td>
</tr>
<tr>
<td>Inherits:</td>
<td>
<a href='../../class/CUI/DataField.html'>CUI.DataField</a>
</td>
</tr>
</table>
<h2>Variables Summary</h2>
<h3 class='inherited'>
Variable inherited from
<a href='../../class/CUI/DataField.html'>CUI.DataField</a>
</h3>
<p class='inherited'>
<a href='../../class/CUI/DataField.html#changed_marker_css_class-variable'>changed_marker_css_class</a>
<a href='../../class/CUI/DataField.html#defaults-variable'>defaults</a>
<a href='../../class/CUI/Element.html#uniqueId-variable'>uniqueId</a>
</p>
<h2>Instance Method Summary</h2>
<ul class='summary'>
<li>
<span class='signature'>
<a href='#readOpts-dynamic'>
#
(void)
<b>readOpts</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#initOpts-dynamic'>
#
(void)
<b>initOpts</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#getFields-dynamic'>
#
(void)
<b>getFields</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#remove-dynamic'>
#
(void)
<b>remove</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#__detach-dynamic'>
#
(void)
<b>__detach</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#destroy-dynamic'>
#
(void)
<b>destroy</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#render-dynamic'>
#
(void)
<b>render</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#setCheckChangedValue-dynamic'>
#
(void)
<b>setCheckChangedValue</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
<li>
<span class='signature'>
<a href='#initData-dynamic'>
#
(void)
<b>initData</b><span>()</span>
</a>
</span>
<span class='desc'>
</span>
</li>
</ul>
<h2>
<small>Inherited Method Summary</small>
<h3 class='inherited'>
Methods inherited from
<a href='../../class/CUI/DataField.html'>CUI.DataField</a>
</h3>
<p class='inherited'>
<a href='../../class/CUI/DataField.html#initOpts-dynamic'>#initOpts</a>
<a href='../../class/CUI/DataField.html#readOpts-dynamic'>#readOpts</a>
<a href='../../class/CUI/DataField.html#maximizeAddClasses-dynamic'>#maximizeAddClasses</a>
<a href='../../class/CUI/DataField.html#getUniqueIdForLabel-dynamic'>#getUniqueIdForLabel</a>
<a href='../../class/CUI/DataField.html#initTemplate-dynamic'>#initTemplate</a>
<a href='../../class/CUI/DataField.html#getTemplate-dynamic'>#getTemplate</a>
<a href='../../class/CUI/DataField.html#isResizable-dynamic'>#isResizable</a>
<a href='../../class/CUI/DataField.html#init-dynamic'>#init</a>
<a href='../../class/CUI/DataField.html#debug-dynamic'>#debug</a>
<a href='../../class/CUI/DataField.html#reload-dynamic'>#reload</a>
<a href='../../class/CUI/DataField.html#remove-dynamic'>#remove</a>
<a href='../../class/CUI/DataField.html#getNameOpt-dynamic'>#getNameOpt</a>
<a href='../../class/CUI/DataField.html#registerLabel-dynamic'>#registerLabel</a>
<a href='../../class/CUI/DataField.html#getLabel-dynamic'>#getLabel</a>
<a href='../../class/CUI/DataField.html#setForm-dynamic'>#setForm</a>
<a href='../../class/CUI/DataField.html#getFormDepth-dynamic'>#getFormDepth</a>
<a href='../../class/CUI/DataField.html#setFormDepth-dynamic'>#setFormDepth</a>
<a href='../../class/CUI/DataField.html#getFormPath-dynamic'>#getFormPath</a>
<a href='../../class/CUI/DataField.html#getForm-dynamic'>#getForm</a>
<a href='../../class/CUI/DataField.html#getOtherField-dynamic'>#getOtherField</a>
<a href='../../class/CUI/DataField.html#getRootForm-dynamic'>#getRootForm</a>
<a href='../../class/CUI/DataField.html#__initDisabled-dynamic'>#__initDisabled</a>
<a href='../../class/CUI/DataField.html#enable-dynamic'>#enable</a>
<a href='../../class/CUI/DataField.html#disable-dynamic'>#disable</a>
<a href='../../class/CUI/DataField.html#isDisabled-dynamic'>#isDisabled</a>
<a href='../../class/CUI/DataField.html#isHidden-dynamic'>#isHidden</a>
<a href='../../class/CUI/DataField.html#isShown-dynamic'>#isShown</a>
<a href='../../class/CUI/DataField.html#updateData-dynamic'>#updateData</a>
<a href='../../class/CUI/DataField.html#setData-dynamic'>#setData</a>
<a href='../../class/CUI/DataField.html#setDataOnOthers-dynamic'>#setDataOnOthers</a>
<a href='../../class/CUI/DataField.html#hide-dynamic'>#hide</a>
<a href='../../class/CUI/DataField.html#show-dynamic'>#show</a>
<a href='../../class/CUI/DataField.html#isRendered-dynamic'>#isRendered</a>
<a href='../../class/CUI/DataField.html#render-dynamic'>#render</a>
<a href='../../class/CUI/DataField.html#displayValue-dynamic'>#displayValue</a>
<a href='../../class/CUI/DataField.html#start-dynamic'>#start</a>
<a href='../../class/CUI/DataField.html#getAllDataFields-dynamic'>#getAllDataFields</a>
<a href='../../class/CUI/DataField.html#getDataFields-dynamic'>#getDataFields</a>
<a href='../../class/CUI/DataField.html#renderAsBlock-dynamic'>#renderAsBlock</a>
<a href='../../class/CUI/DataField.html#isDataField-dynamic'>#isDataField</a>
<a href='../../class/CUI/DataField.html#callOnOthers-dynamic'>#callOnOthers</a>
<a href='../../class/CUI/DataField.html#getData-dynamic'>#getData</a>
<a href='../../class/CUI/DataField.html#hasData-dynamic'>#hasData</a>
<a href='../../class/CUI/DataField.html#hasUserData-dynamic'>#hasUserData</a>
<a href='../../class/CUI/DataField.html#getArrayFromOpt-dynamic'>#getArrayFromOpt</a>
<a href='../../class/CUI/DataField.html#getName-dynamic'>#getName</a>
<a href='../../class/CUI/DataField.html#getDefaultValue-dynamic'>#getDefaultValue</a>
<a href='../../class/CUI/DataField.html#getValue-dynamic'>#getValue</a>
<a href='../../class/CUI/DataField.html#checkValue-dynamic'>#checkValue</a>
<a href='../../class/CUI/DataField.html#setValue-dynamic'>#setValue</a>
<a href='../../class/CUI/DataField.html#getInitValue-dynamic'>#getInitValue</a>
<a href='../../class/CUI/DataField.html#getLastValue-dynamic'>#getLastValue</a>
<a href='../../class/CUI/DataField.html#reset-dynamic'>#reset</a>
<a href='../../class/CUI/DataField.html#undo-dynamic'>#undo</a>
<a href='../../class/CUI/DataField.html#redo-dynamic'>#redo</a>
<a href='../../class/CUI/DataField.html#goto-dynamic'>#goto</a>
<a href='../../class/CUI/DataField.html#initData-dynamic'>#initData</a>
<a href='../../class/CUI/DataField.html#initValue-dynamic'>#initValue</a>
<a href='../../class/CUI/DataField.html#setCheckChangedValue-dynamic'>#setCheckChangedValue</a>
<a href='../../class/CUI/DataField.html#getCheckChangedValue-dynamic'>#getCheckChangedValue</a>
<a href='../../class/CUI/DataField.html#getUndo-dynamic'>#getUndo</a>
<a href='../../class/CUI/DataField.html#storeValue-dynamic'>#storeValue</a>
<a href='../../class/CUI/DataField.html#triggerDataChanged-dynamic'>#triggerDataChanged</a>
<a href='../../class/CUI/DataField.html#isChanged-dynamic'>#isChanged</a>
<a href='../../class/CUI/DataField.html#checkChanged-dynamic'>#checkChanged</a>
<a href='../../class/CUI/DataField.html#getChangedMarker-dynamic'>#getChangedMarker</a>
<a href='../../class/CUI/DataField.html#destroy-dynamic'>#destroy</a>
<a href='../../class/CUI/DataField.html#new-static'>.new</a>
<a href='../../class/CUI/DOMElement.html#registerTemplate-dynamic'>#registerTemplate</a>
<a href='../../class/CUI/DOMElement.html#getDOMElementClasses-dynamic'>#getDOMElementClasses</a>
<a href='../../class/CUI/DOMElement.html#registerDOMElement-dynamic'>#registerDOMElement</a>
<a href='../../class/CUI/DOMElement.html#getElementForLayer-dynamic'>#getElementForLayer</a>
<a href='../../class/CUI/DOMElement.html#unregisterDOMElement-dynamic'>#unregisterDOMElement</a>
<a href='../../class/CUI/DOMElement.html#__assertDOMElement-dynamic'>#__assertDOMElement</a>
<a href='../../class/CUI/DOMElement.html#__assertTemplateElement-dynamic'>#__assertTemplateElement</a>
<a href='../../class/CUI/DOMElement.html#addClass-dynamic'>#addClass</a>
<a href='../../class/CUI/DOMElement.html#setAria-dynamic'>#setAria</a>
<a href='../../class/CUI/DOMElement.html#removeClass-dynamic'>#removeClass</a>
<a href='../../class/CUI/DOMElement.html#hasClass-dynamic'>#hasClass</a>
<a href='../../class/CUI/DOMElement.html#isDestroyed-dynamic'>#isDestroyed</a>
<a href='../../class/CUI/DOMElement.html#empty-dynamic'>#empty</a>
<a href='../../class/CUI/DOMElement.html#replace-dynamic'>#replace</a>
<a href='../../class/CUI/DOMElement.html#append-dynamic'>#append</a>
<a href='../../class/CUI/DOMElement.html#prepend-dynamic'>#prepend</a>
<a href='../../class/CUI/DOMElement.html#text-dynamic'>#text</a>
<a href='../../class/CUI/DOMElement.html#get-dynamic'>#get</a>
<a href='../../class/CUI/DOMElement.html#getFlexHandle-dynamic'>#getFlexHandle</a>
<a href='../../class/CUI/Element.html#getElementClass-dynamic'>#getElementClass</a>
<a href='../../class/CUI/Element.html#getUniqueId-dynamic'>#getUniqueId</a>
<a href='../../class/CUI/Element.html#getOpts-dynamic'>#getOpts</a>
<a href='../../class/CUI/Element.html#getOpt-dynamic'>#getOpt</a>
<a href='../../class/CUI/Element.html#hasOpt-dynamic'>#hasOpt</a>
<a href='../../class/CUI/Element.html#getSetOpt-dynamic'>#getSetOpt</a>
<a href='../../class/CUI/Element.html#hasSetOpt-dynamic'>#hasSetOpt</a>
<a href='../../class/CUI/Element.html#copy-dynamic'>#copy</a>
<a href='../../class/CUI/Element.html#mergeOpt-dynamic'>#mergeOpt</a>
<a href='../../class/CUI/Element.html#removeOpt-dynamic'>#removeOpt</a>
<a href='../../class/CUI/Element.html#addOpt-dynamic'>#addOpt</a>
<a href='../../class/CUI/Element.html#addOpts-dynamic'>#addOpts</a>
<a href='../../class/CUI/Element.html#mergeOpts-dynamic'>#mergeOpts</a>
<a href='../../class/CUI/Element.html#__getCheckMap-dynamic'>#__getCheckMap</a>
<a href='../../class/CUI/Element.html#readOptsFromAttr-dynamic'>#readOptsFromAttr</a>
<a href='../../class/CUI/Element.html#proxy-dynamic'>#proxy</a>
<a href='../../class/CUI/Element.html#getOptKeys-static'>.getOptKeys</a>
</p>
</h2>
<h2>Instance Method Details</h2>
<div class='methods'>
<div class='method_details'>
<p class='signature' id='readOpts-dynamic'>
#
(void)
<b>readOpts</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='initOpts-dynamic'>
#
(void)
<b>initOpts</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='getFields-dynamic'>
#
(void)
<b>getFields</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='remove-dynamic'>
#
(void)
<b>remove</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='__detach-dynamic'>
#
(void)
<b>__detach</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='destroy-dynamic'>
#
(void)
<b>destroy</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='render-dynamic'>
#
(void)
<b>render</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='setCheckChangedValue-dynamic'>
#
(void)
<b>setCheckChangedValue</b><span>()</span>
<br>
</p>
</div>
<div class='method_details'>
<p class='signature' id='initData-dynamic'>
#
(void)
<b>initData</b><span>()</span>
<br>
</p>
</div>
</div>
</div>
<div id='footer'>
By
<a href='https://github.com/coffeedoc/codo' title='CoffeeScript API documentation generator'>
Codo
</a>
2.1.2
✲
Press H to see the keyboard shortcuts
✲
<a href='http://twitter.com/netzpirat' target='_parent'>@netzpirat</a>
✲
<a href='http://twitter.com/_inossidabile' target='_parent'>@_inossidabile</a>
</div>
<iframe id='search_frame'></iframe>
<div id='fuzzySearch'>
<input type='text'>
<ol></ol>
</div>
<div id='help'>
<p>
Quickly fuzzy find classes, mixins, methods, file:
</p>
<ul>
<li>
<span>T</span>
Open fuzzy finder dialog
</li>
</ul>
<p>
Control the navigation frame:
</p>
<ul>
<li>
<span>L</span>
Toggle list view
</li>
<li>
<span>C</span>
Show class list
</li>
<li>
<span>I</span>
Show mixin list
</li>
<li>
<span>F</span>
Show file list
</li>
<li>
<span>M</span>
Show method list
</li>
<li>
<span>E</span>
Show extras list
</li>
</ul>
<p>
You can focus and blur the search input:
</p>
<ul>
<li>
<span>S</span>
Focus search input
</li>
<li>
<span>Esc</span>
Blur search input
</li>
</ul>
</div>
</body>
</html> | {
"content_hash": "b55fb113cb7bc58171834140d019da75",
"timestamp": "",
"source": "github",
"line_count": 423,
"max_line_length": 112,
"avg_line_length": 36.16548463356974,
"alnum_prop": 0.5785723624003137,
"repo_name": "programmfabrik/coffeescript-ui",
"id": "715576d659f107ce3857d904446b6d8ad9197fa5",
"size": "15298",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/class/CUI/DataFieldProxy.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2299"
},
{
"name": "CoffeeScript",
"bytes": "817447"
},
{
"name": "HTML",
"bytes": "24008"
},
{
"name": "JavaScript",
"bytes": "125011"
},
{
"name": "Makefile",
"bytes": "123"
},
{
"name": "PHP",
"bytes": "3534"
},
{
"name": "SCSS",
"bytes": "369014"
},
{
"name": "Shell",
"bytes": "53"
}
],
"symlink_target": ""
} |
<?php
namespace Oro\Bundle\SearchBundle\Tests\Unit\Engine;
use Doctrine\DBAL\DBALException;
use Oro\Bundle\EntityBundle\ORM\DatabaseDriverInterface;
use Oro\Bundle\SearchBundle\Engine\FulltextIndexManager;
use Oro\Bundle\SearchBundle\Engine\Orm\PdoMysql;
class FulltextIndexManagerTest extends \PHPUnit\Framework\TestCase
{
const TABLE_NAME = 'oro_test_table';
const INDEX_NAME = 'oro_test_table_value_idx';
/**
* @var \PHPUnit\Framework\MockObject\MockObject
*/
protected $connection;
/**
* @var FulltextIndexManager
*/
protected $indexManager;
protected function setUp()
{
$this->connection = $this
->getMockBuilder('Doctrine\DBAL\Connection')
->disableOriginalConstructor()
->getMock();
$config = [
DatabaseDriverInterface::DRIVER_MYSQL => 'Oro\Bundle\SearchBundle\Engine\Orm\PdoMysql'
];
$this->indexManager = new FulltextIndexManager($this->connection, $config, self::TABLE_NAME, self::INDEX_NAME);
}
public function testCreateIndexes()
{
$this->connection
->expects($this->once())
->method('getParams')
->will(
$this->returnValue(
['driver' => DatabaseDriverInterface::DRIVER_MYSQL]
)
);
$this->connection
->expects($this->once())
->method('query')
->with(PdoMysql::getPlainSql(self::TABLE_NAME, self::INDEX_NAME));
$this->assertTrue($this->indexManager->createIndexes());
}
public function testCreateIndexWithError()
{
$this->connection
->expects($this->once())
->method('getParams')
->will(
$this->returnValue(
['driver' => DatabaseDriverInterface::DRIVER_MYSQL]
)
);
$this->connection
->expects($this->once())
->method('query')
->willThrowException(new DBALException());
$this->assertFalse($this->indexManager->createIndexes());
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Driver "pdo_pgsql" not found
*/
public function testGetQueryForUnknownDriver()
{
$this->connection
->expects($this->once())
->method('getParams')
->will(
$this->returnValue(
['driver' => DatabaseDriverInterface::DRIVER_POSTGRESQL]
)
);
$this->indexManager->getQuery();
}
}
| {
"content_hash": "25857ec6975b9969e6764a592d08f1c8",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 119,
"avg_line_length": 27.9468085106383,
"alnum_prop": 0.5668062428625809,
"repo_name": "orocrm/platform",
"id": "e3a0a2ee53e8a1cac1293039f193a896554c3de7",
"size": "2627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Oro/Bundle/SearchBundle/Tests/Unit/Engine/FulltextIndexManagerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "618485"
},
{
"name": "Gherkin",
"bytes": "158217"
},
{
"name": "HTML",
"bytes": "1648915"
},
{
"name": "JavaScript",
"bytes": "3326127"
},
{
"name": "PHP",
"bytes": "37828618"
}
],
"symlink_target": ""
} |
package io.codearcs.candlestack.aws;
import io.codearcs.candlestack.CandlestackException;
public class CandlestackAWSException extends CandlestackException {
private static final long serialVersionUID = 1L;
public CandlestackAWSException( String msg ) {
super( msg );
}
public CandlestackAWSException( String msg, Throwable error ) {
super( msg, error );
}
}
| {
"content_hash": "7ff72046aa57a142f8bff9b39ddb0762",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 67,
"avg_line_length": 18.85,
"alnum_prop": 0.7692307692307693,
"repo_name": "CodeArcsInc/candlestack",
"id": "6b4cf3f52bbd6074e59ef0a2bc839029f4cc1686",
"size": "377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/codearcs/candlestack/aws/CandlestackAWSException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1210"
},
{
"name": "Java",
"bytes": "207581"
},
{
"name": "Shell",
"bytes": "200513"
}
],
"symlink_target": ""
} |
namespace QA.Core.Exceptions
{
using System;
using System.Text;
using OpenQA.Selenium;
public class NoSuchElementException : ApplicationException
{
public NoSuchElementException()
{
}
public NoSuchElementException(By by, BaseWebDriverTest ext, Exception ex)
{
string message = this.BuildNotFoundElementExceptionText(by, ext);
throw new ApplicationException(message, ex);
}
public NoSuchElementException(By by, BaseWebDriverTest ext)
{
string message = this.BuildNotFoundElementExceptionText(by, ext);
throw new ApplicationException(message);
}
private string BuildNotFoundElementExceptionText(By by, BaseWebDriverTest ext)
{
var stringBuilder = new StringBuilder();
string customLoggingMessage = string.Format("#### The element with the location strategy: {0} ####\n ####NOT FOUND!####", by.ToString());
stringBuilder.AppendLine(customLoggingMessage);
string cuurentUrlMessage = string.Format("The URL when the test failed was: {0}", ext.Browser.Url);
stringBuilder.AppendLine(cuurentUrlMessage);
return stringBuilder.ToString();
}
}
} | {
"content_hash": "7c3cec43be1fb1836a337d9236646fd6",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 150,
"avg_line_length": 31.365853658536587,
"alnum_prop": 0.6423017107309487,
"repo_name": "phristov/QA.SeleniumWebDriver.CSharp",
"id": "0354a536589d713559b89a6ea5923192adbafd30",
"size": "1286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/QA.Core/Exceptions/NoSuchElementException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "28784"
},
{
"name": "JavaScript",
"bytes": "11048"
}
],
"symlink_target": ""
} |
<?php
namespace Zf2ClientMoysklad;
require_once __DIR__.'/_config.php';
use Zf2ClientMoysklad\Entity\Good;
use Zf2ClientMoysklad\Entity\PurchaseOrder;
use Zf2ClientMoysklad\Repository\BasicRepository;
global $sm;
/* @var $entityManager EntityManager */
$entityManager = $sm->get('zf2clientmoysklad_entity_manager');
/*====================== Method for Create purchase orders ==========================*/
$entityToOrder = '1e474a24-5cd7-11e3-00e2-7054d21a8d1e';
/* @var $goodEntity Good */
$goodEntity = $entityManager->find('Zf2ClientMoysklad\Entity\Good', $entityToOrder);
$purchaseOrder = new PurchaseOrder();
$purchaseOrderPosition = new PurchaseOrder\Position();
$entityManager->persist($purchaseOrder);
//Dealer id
$purchaseOrder->setSourceAgentUuid('2678f502-5cc9-11e3-320b-7054d21a8d1e');
//Your organisation id
$purchaseOrder->setTargetAgentUuid('266ce37b-5cc9-11e3-92f6-7054d21a8d1e');
$purchaseOrderPosition->setGoodsUuid($goodEntity->getUuid());
$purchaseOrderPosition->setPriceSum($goodEntity->getPrice());
$purchaseOrderPosition->setPriceSumInCurrency($goodEntity->getPrice());
$purchaseOrderPosition->setQuantity(1000);
$purchaseOrderPosition->setReserve(10);
$purchaseOrder->addOrderPosition($purchaseOrderPosition);
$purchaseOrderPosition = new PurchaseOrder\Position();
$purchaseOrderPosition->setGoodsUuid($goodEntity->getUuid());
$purchaseOrderPosition->setPriceSum($goodEntity->getPrice());
$purchaseOrderPosition->setPriceSumInCurrency($goodEntity->getPrice());
$purchaseOrderPosition->setQuantity(10);
$purchaseOrderPosition->setReserve(1);
$purchaseOrder->addOrderPosition($purchaseOrderPosition);
$entityManager->flush();
/*---------------------------------------------------------------------------------*/
| {
"content_hash": "5bad3f3d85216eb7f3074d3fae2272dd",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 87,
"avg_line_length": 33.65384615384615,
"alnum_prop": 0.7348571428571429,
"repo_name": "spalax/MoySkladClient",
"id": "de54977da047b3cde74e69d3364405bbfc1d479f",
"size": "1750",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/CreatePurchaseOrders.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "121126"
}
],
"symlink_target": ""
} |
<ns0:eml xmlns:ns0="eml://ecoinformatics.org/eml-2.1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packageId="knb-lter-europe-deims.13466.14905" system="knb-lter-europe-deims" xsi:schemaLocation="eml://ecoinformatics.org/eml-2.1.1 https://code.ecoinformatics.org/code/eml/tags/RELEASE_EML_2_1_1/eml.xsd">
<access authSystem="knb" order="allowFirst" scope="document">
<allow>
<principal>uid=Italy,o=LTER-Europe,dc=ecoinformatics,dc=org</principal>
<permission>all</permission>
</allow>
<allow>
<principal>public</principal>
<permission>read</permission>
</allow>
</access>
<dataset id="knb-lter-europe-deims.13466.14905" system="knb-lter-europe-deims">
<alternateIdentifier>f2cf33f0-cdfd-11e2-a655-005056ab003f</alternateIdentifier>
<title>IT_SI001243_Gulf of Trieste_15052013_Downwelling_PAR</title>
<creator>
<individualName>
<surName>Italy</surName>
</individualName>
</creator>
<pubDate>2013-05-16</pubDate>
<language>eng</language><abstract>
<section>
<para> Vertical profiles of underwater photosynthetic active radiation (PAR) are collected on a monthly basis in the Gulf of Trieste – time series station (station C1). The site is part of the LTER-North Adriatic site.Data are used to characterize the light field and light extinction in the coastal Long Term Ecosystem Research station of the Gulf of Trieste, in the northernmost part of the Adriatic Sea and of the Mediterranean basin. General information can be found at: http://nettuno.ogs.trieste.it/ilter/BIO/index.html </para>
</section>
</abstract>
<keywordSet>
<keyword>parameter</keyword>
<keyword>data product</keyword>
<keywordThesaurus>EnvEurope Thesaurus;2012-08-13;version 3.0;http://vocabs.lter-europe.net/EnvThes3.html</keywordThesaurus>
</keywordSet>
<additionalInfo>
<section>
<title>Metadata date</title>
<para>2013-06-05 00:00:00</para>
</section>
<section>
<title>Dataset access and use constraints</title>
<para>Principal:Research has granted a permission of type:Free for access and use upon request</para>
<para>Principal:EnvEurope (LTER-Europe) has granted a permission of type:Free for access and use upon request</para>
<para>Principal:Education has granted a permission of type:Free for access and use upon request</para>
<para>Principal:Administration has granted a permission of type:Free access and use</para>
</section>
</additionalInfo>
<intellectualRights>
<section>
<para>Formal acknowledgement of the dataset providers</para>
</section>
<section>
<para>The opportunity to review the results based on the dataset</para>
</section>
</intellectualRights>
<distribution>
<online>
<onlineDescription>NODC-OGS</onlineDescription>
<url function="information">http://nodc.ogs.trieste.it/nodc/homepage</url>
</online>
</distribution>
<coverage>
<temporalCoverage>
<rangeOfDates>
<beginDate>
<calendarDate>2012-01-01</calendarDate>
</beginDate>
<endDate>
<calendarDate>2012-12-31</calendarDate>
</endDate>
</rangeOfDates>
</temporalCoverage>
</coverage>
<contact>
<individualName>
<surName>Italy</surName>
</individualName>
</contact>
<methods>
<methodStep>
<description>
<section>
<para>
<literalLayout>Profiling Natural Fluorometer PNF-300A (Biospherical Instruments Inc., San Diego, CA, USA) </literalLayout>
</para>
</section>
</description>
<instrumentation>CTD probe (Idronaut Ocean Seven 316 and SeaBird 19 Plus)</instrumentation>
</methodStep>
</methods>
</dataset>
</ns0:eml> | {
"content_hash": "38ae9f87f2ca18340b804735600bb217",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 554,
"avg_line_length": 38.46067415730337,
"alnum_prop": 0.773298276365761,
"repo_name": "NCEAS/metadig",
"id": "7a4eab6dc2e1d37319f9fd53a957365e73f20031",
"size": "3423",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "results/LTER_EUROPE/Ecological_Metadata_Language_version_2.1.1/xml/03749-metadata.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2361"
},
{
"name": "Python",
"bytes": "42696"
},
{
"name": "Shell",
"bytes": "5798"
},
{
"name": "XSLT",
"bytes": "207495"
}
],
"symlink_target": ""
} |
package com.sentenial.ws.client.usermgmnt;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CancelDirectDebitReasonCode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CancelDirectDebitReasonCode">
* <restriction base="{http://www.w3.org/2001/XMLSchema}token">
* <enumeration value="AGNT"/>
* <enumeration value="CURR"/>
* <enumeration value="CUST"/>
* <enumeration value="CUTA"/>
* <enumeration value="DUPL"/>
* <enumeration value="UPAY"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CancelDirectDebitReasonCode", namespace = "urn:com:sentenial:origix:ws:common:types")
@XmlEnum
public enum CancelDirectDebitReasonCode {
AGNT,
CURR,
CUST,
CUTA,
DUPL,
UPAY;
public String value() {
return name();
}
public static CancelDirectDebitReasonCode fromValue(String v) {
return valueOf(v);
}
}
| {
"content_hash": "233e2b24a2bd6ce1c52995fd7227d390",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 102,
"avg_line_length": 23.717391304347824,
"alnum_prop": 0.6626947754353804,
"repo_name": "whelanp/sentenial-ws-client",
"id": "d7782a8aba56f24f765d723933598c0d78e57576",
"size": "1091",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/sentenial/ws/client/usermgmnt/CancelDirectDebitReasonCode.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "793008"
}
],
"symlink_target": ""
} |
package armdelegatednetwork_test
import (
"context"
"log"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/delegatednetwork/armdelegatednetwork"
)
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnc/resource-manager/Microsoft.DelegatedNetwork/stable/2021-03-15/examples/getController.json
func ExampleControllerClient_GetDetails() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client, err := armdelegatednetwork.NewControllerClient("613192d7-503f-477a-9cfe-4efc3ee2bd60", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := client.GetDetails(ctx,
"TestRG",
"testcontroller",
nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// TODO: use response item
_ = res
}
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnc/resource-manager/Microsoft.DelegatedNetwork/stable/2021-03-15/examples/putController.json
func ExampleControllerClient_BeginCreate() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client, err := armdelegatednetwork.NewControllerClient("613192d7-503f-477a-9cfe-4efc3ee2bd60", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := client.BeginCreate(ctx,
"TestRG",
"testcontroller",
armdelegatednetwork.DelegatedController{
Location: to.Ptr("West US"),
},
nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
res, err := poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
// TODO: use response item
_ = res
}
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnc/resource-manager/Microsoft.DelegatedNetwork/stable/2021-03-15/examples/deleteController.json
func ExampleControllerClient_BeginDelete() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client, err := armdelegatednetwork.NewControllerClient("613192d7-503f-477a-9cfe-4efc3ee2bd60", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
poller, err := client.BeginDelete(ctx,
"TestRG",
"testcontroller",
nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
_, err = poller.PollUntilDone(ctx, nil)
if err != nil {
log.Fatalf("failed to pull the result: %v", err)
}
}
// Generated from example definition: https://github.com/Azure/azure-rest-api-specs/tree/main/specification/dnc/resource-manager/Microsoft.DelegatedNetwork/stable/2021-03-15/examples/patchController.json
func ExampleControllerClient_Patch() {
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
ctx := context.Background()
client, err := armdelegatednetwork.NewControllerClient("613192d7-503f-477a-9cfe-4efc3ee2bd60", cred, nil)
if err != nil {
log.Fatalf("failed to create client: %v", err)
}
res, err := client.Patch(ctx,
"TestRG",
"testcontroller",
armdelegatednetwork.ControllerResourceUpdateParameters{
Tags: map[string]*string{
"key": to.Ptr("value"),
},
},
nil)
if err != nil {
log.Fatalf("failed to finish the request: %v", err)
}
// TODO: use response item
_ = res
}
| {
"content_hash": "710b35aba02cdc4b6bee4281c8463c00",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 204,
"avg_line_length": 33.44642857142857,
"alnum_prop": 0.7229044313934864,
"repo_name": "Azure/azure-sdk-for-go",
"id": "60b96c6ebb7b17e270ce5e160fe712d11ac33c1b",
"size": "4085",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/resourcemanager/delegatednetwork/armdelegatednetwork/ze_generated_example_controller_client_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1629"
},
{
"name": "Bicep",
"bytes": "8394"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "1435"
},
{
"name": "Go",
"bytes": "5463500"
},
{
"name": "HTML",
"bytes": "8933"
},
{
"name": "JavaScript",
"bytes": "8137"
},
{
"name": "PowerShell",
"bytes": "504494"
},
{
"name": "Shell",
"bytes": "3893"
},
{
"name": "Smarty",
"bytes": "1723"
}
],
"symlink_target": ""
} |
/* 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.flowable.engine.impl.bpmn.behavior;
import java.util.Collections;
import org.flowable.bpmn.model.FlowNode;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.common.engine.impl.context.Context;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.history.DeleteReason;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
/**
* @author Joram Barrez
*/
public class BoundaryEventActivityBehavior extends FlowNodeActivityBehavior {
private static final long serialVersionUID = 1L;
protected boolean interrupting;
public BoundaryEventActivityBehavior() {
}
public BoundaryEventActivityBehavior(boolean interrupting) {
this.interrupting = interrupting;
}
@Override
public void execute(DelegateExecution execution) {
// Overridden by subclasses
}
@Override
public void trigger(DelegateExecution execution, String triggerName, Object triggerData) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
CommandContext commandContext = Context.getCommandContext();
if (interrupting) {
executeInterruptingBehavior(executionEntity, commandContext);
} else {
executeNonInterruptingBehavior(executionEntity, commandContext);
}
}
protected void executeInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) {
// The destroy scope operation will look for the parent execution and
// destroy the whole scope, and leave the boundary event using this parent execution.
//
// The take outgoing seq flows operation below (the non-interrupting else clause) on the other hand uses the
// child execution to leave, which keeps the scope alive.
// Which is what we need here.
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
ExecutionEntity attachedRefScopeExecution = executionEntityManager.findById(executionEntity.getParentId());
ExecutionEntity parentScopeExecution = null;
ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(attachedRefScopeExecution.getParentId());
while (currentlyExaminedExecution != null && parentScopeExecution == null) {
if (currentlyExaminedExecution.isScope()) {
parentScopeExecution = currentlyExaminedExecution;
} else {
currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
}
}
if (parentScopeExecution == null) {
throw new FlowableException("Programmatic error: no parent scope execution found for boundary event");
}
deleteChildExecutions(attachedRefScopeExecution, executionEntity, commandContext);
// set new parent for boundary event execution
executionEntity.setParent(parentScopeExecution);
// TakeOutgoingSequenceFlow will not set history correct when no outgoing sequence flow for boundary event
// (This is a theoretical case ... shouldn't use a boundary event without outgoing sequence flow ...)
if (executionEntity.getCurrentFlowElement() instanceof FlowNode
&& ((FlowNode) executionEntity.getCurrentFlowElement()).getOutgoingFlows().isEmpty()) {
CommandContextUtil.getHistoryManager(commandContext).recordActivityEnd(executionEntity, null);
}
CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation(executionEntity, true);
}
protected void executeNonInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) {
// Non-interrupting: the current execution is given the first parent
// scope (which isn't its direct parent)
//
// Why? Because this execution does NOT have anything to do with
// the current parent execution (the one where the boundary event is on): when it is deleted or whatever,
// this does not impact this new execution at all, it is completely independent in that regard.
// Note: if the parent of the parent does not exists, this becomes a concurrent execution in the process instance!
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
ExecutionEntity parentExecutionEntity = executionEntityManager.findById(executionEntity.getParentId());
ExecutionEntity scopeExecution = null;
ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(parentExecutionEntity.getParentId());
while (currentlyExaminedExecution != null && scopeExecution == null) {
if (currentlyExaminedExecution.isScope()) {
scopeExecution = currentlyExaminedExecution;
} else {
currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
}
}
if (scopeExecution == null) {
throw new FlowableException("Programmatic error: no parent scope execution found for boundary event");
}
CommandContextUtil.getHistoryManager(commandContext).recordActivityEnd(executionEntity, null);
ExecutionEntity nonInterruptingExecution = executionEntityManager.createChildExecution(scopeExecution);
nonInterruptingExecution.setActive(false);
nonInterruptingExecution.setCurrentFlowElement(executionEntity.getCurrentFlowElement());
CommandContextUtil.getAgenda(commandContext).planTakeOutgoingSequenceFlowsOperation(nonInterruptingExecution, true);
}
protected void deleteChildExecutions(ExecutionEntity parentExecution, ExecutionEntity outgoingExecutionEntity, CommandContext commandContext) {
ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext);
String deleteReason = DeleteReason.BOUNDARY_EVENT_INTERRUPTING + " (" + outgoingExecutionEntity.getCurrentActivityId() + ")";
executionEntityManager.deleteChildExecutions(parentExecution, Collections.singletonList(outgoingExecutionEntity.getId()), null,
deleteReason, true, outgoingExecutionEntity.getCurrentFlowElement());
executionEntityManager.deleteExecutionAndRelatedData(parentExecution, deleteReason, true, outgoingExecutionEntity.getCurrentFlowElement());
}
public boolean isInterrupting() {
return interrupting;
}
public void setInterrupting(boolean interrupting) {
this.interrupting = interrupting;
}
}
| {
"content_hash": "51394e1b8d4b2e451d88a6e979561b7c",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 147,
"avg_line_length": 47.132075471698116,
"alnum_prop": 0.7452628769682412,
"repo_name": "lsmall/flowable-engine",
"id": "1b7f1293aa8ea9ef14abca226325469f31435b0a",
"size": "7494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/flowable-engine/src/main/java/org/flowable/engine/impl/bpmn/behavior/BoundaryEventActivityBehavior.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "166"
},
{
"name": "CSS",
"bytes": "688913"
},
{
"name": "Dockerfile",
"bytes": "6367"
},
{
"name": "Groovy",
"bytes": "482"
},
{
"name": "HTML",
"bytes": "1117510"
},
{
"name": "Java",
"bytes": "33771201"
},
{
"name": "JavaScript",
"bytes": "12402628"
},
{
"name": "PLSQL",
"bytes": "109354"
},
{
"name": "PLpgSQL",
"bytes": "11691"
},
{
"name": "SQLPL",
"bytes": "1265"
},
{
"name": "Shell",
"bytes": "19145"
}
],
"symlink_target": ""
} |
jquery-responsive-image
=======================
A very simple jQuery plugin to force images to truly responsive. I wrote jquery plugin primarily this because WYSIWYG editors can add inline width/height styles or width/height attributes to images which can override some CSS approaches. When using a CMS with non technical content writers this plugin can come in handy.
| {
"content_hash": "ab74dd011b547be789774d9f7c58a959",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 321,
"avg_line_length": 92.75,
"alnum_prop": 0.77088948787062,
"repo_name": "troylutton/jquery-responsive-image",
"id": "9089f78b10d1765fbd3f1df794ff630278d6d1ce",
"size": "371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "875"
}
],
"symlink_target": ""
} |
//-----------------------------------------------------------------------
// <copyright file="BusyAnimation.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>User control that displays busy animation</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Csla.Windows
{
/// <summary>
/// User control that displays busy animation
/// </summary>
[ToolboxItem(true), ToolboxBitmap(typeof(BusyAnimation), "Csla.Windows.BusyAnimation")]
public partial class BusyAnimation : UserControl
{
/// <summary>
/// new instance busy animation
/// </summary>
public BusyAnimation()
{
InitializeComponent();
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BusyProgressBar.GetType().GetMethod("SetStyle", System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).Invoke(this.BusyProgressBar, new object[] { ControlStyles.SupportsTransparentBackColor, true });
if (!IsInDesignMode)
this.BusyProgressBar.BackColor = _progressBarBackColor;
}
private Color _progressBarForeColor = System.Drawing.Color.LawnGreen;
/// <summary>
/// Set or get foreground color for busy animation's progress bar
/// </summary>
[Category("Csla")]
[Description("Foreground color for busy animation's progress bar.")]
[DefaultValue(typeof(System.Drawing.Color), "LawnGreen")]
[Browsable(true)]
public Color ProgressBarForeColor
{
get
{
return _progressBarForeColor;
}
set
{
_progressBarForeColor = value;
this.BusyProgressBar.ForeColor = _progressBarForeColor;
}
}
private Color _progressBarBackColor = System.Drawing.Color.White;
/// <summary>
/// Set or get background color for busy animation's progress bar
/// </summary>
[Category("Csla")]
[Description("Background color for busy animation's progress bar.")]
[DefaultValue(typeof(System.Drawing.Color), "White")]
[Browsable(true)]
public Color ProgressBarBackColor
{
get
{
return _progressBarBackColor;
}
set
{
_progressBarBackColor = value;
this.BusyProgressBar.BackColor = _progressBarBackColor;
}
}
private bool _isRunning = false;
/// <summary>
/// Indicates if animation needs to be shown. Set to true to start
/// progress bar animation
/// </summary>
[Category("Csla")]
[Description("Indicates if animation needs to be shown. Set to true to start progress bar animation")]
[DefaultValue(false)]
[Bindable(true)]
[Browsable(true)]
public bool IsRunning
{
get
{
return _isRunning;
}
set
{
_isRunning = value;
Run(_isRunning);
}
}
private void Run(bool run)
{
if (!IsInDesignMode)
{
this.Visible = run;
this.BusyProgressBar.Visible = run;
this.ProgressTimer.Enabled = run;
}
}
private void ProgressTimer_Tick(object sender, EventArgs e)
{
if (_isRunning)
{
int newValue = this.BusyProgressBar.Value + this.BusyProgressBar.Step;
if (newValue > this.BusyProgressBar.Maximum)
{
this.BusyProgressBar.Value = 0;
}
else
{
this.BusyProgressBar.Value = newValue;
}
}
}
private bool IsInDesignMode
{
get
{
if (this.GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null)
return true;
else
return false;
}
}
private void BusyAnimation_Load(object sender, EventArgs e)
{
if (IsInDesignMode)
{
this.BusyProgressBar.Value = (int)(this.BusyProgressBar.Maximum / 2);
this.BusyProgressBar.Visible = true;
}
}
}
} | {
"content_hash": "adf6eddb2021483dd2d1babd621a6e6a",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 373,
"avg_line_length": 28.602649006622517,
"alnum_prop": 0.6191247974068071,
"repo_name": "BrettJaner/csla",
"id": "5ab51d3a8b60377f0adbe196d94184501f8ffb60",
"size": "4321",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/Csla.Windows.Shared/BusyAnimation.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "13295"
},
{
"name": "Batchfile",
"bytes": "1434"
},
{
"name": "C#",
"bytes": "4395424"
},
{
"name": "HTML",
"bytes": "52832"
},
{
"name": "PowerShell",
"bytes": "25361"
},
{
"name": "Shell",
"bytes": "533"
},
{
"name": "Visual Basic",
"bytes": "42440"
}
],
"symlink_target": ""
} |
.class public final Landroid/media/TimedText$Karaoke;
.super Ljava/lang/Object;
.source "TimedText.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/media/TimedText;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x19
name = "Karaoke"
.end annotation
# instance fields
.field public final endChar:I
.field public final endTimeMs:I
.field public final startChar:I
.field public final startTimeMs:I
# direct methods
.method public constructor <init>(IIII)V
.locals 0
.param p1, "startTimeMs" # I
.param p2, "endTimeMs" # I
.param p3, "startChar" # I
.param p4, "endChar" # I
.prologue
.line 351
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 352
iput p1, p0, Landroid/media/TimedText$Karaoke;->startTimeMs:I
.line 353
iput p2, p0, Landroid/media/TimedText$Karaoke;->endTimeMs:I
.line 354
iput p3, p0, Landroid/media/TimedText$Karaoke;->startChar:I
.line 355
iput p4, p0, Landroid/media/TimedText$Karaoke;->endChar:I
.line 356
return-void
.end method
| {
"content_hash": "46f0005c3c5fa7c2b191e5ddb695c593",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 65,
"avg_line_length": 21.566037735849058,
"alnum_prop": 0.6937882764654418,
"repo_name": "shumxin/FlymeOS_A5DUG",
"id": "f4b67f2fc35069d78a40ba5dbfb8d2826d1ced1f",
"size": "1143",
"binary": false,
"copies": "1",
"ref": "refs/heads/lollipop-5.0",
"path": "framework.jar.out/smali_classes2/android/media/TimedText$Karaoke.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "96769"
},
{
"name": "Makefile",
"bytes": "13678"
},
{
"name": "Shell",
"bytes": "103420"
},
{
"name": "Smali",
"bytes": "189389087"
}
],
"symlink_target": ""
} |
from rdflib.store import Store, VALID_STORE, NO_STORE
from rdflib.term import URIRef
from rdflib.py3compat import b
def bb(u):
return u.encode('utf-8')
try:
from bsddb import db
has_bsddb = True
except ImportError:
try:
from bsddb3 import db
has_bsddb = True
except ImportError:
has_bsddb = False
from os import mkdir
from os.path import exists, abspath
from urllib.request import pathname2url
from threading import Thread
if has_bsddb:
# These are passed to bsddb when creating DBs
# passed to db.DBEnv.set_flags
ENVSETFLAGS = db.DB_CDB_ALLDB
# passed to db.DBEnv.open
ENVFLAGS = db.DB_INIT_MPOOL | db.DB_INIT_CDB | db.DB_THREAD
CACHESIZE = 1024 * 1024 * 50
# passed to db.DB.Open()
DBOPENFLAGS = db.DB_THREAD
import logging
logger = logging.getLogger(__name__)
__all__ = ['Sleepycat']
class Sleepycat(Store):
context_aware = True
formula_aware = True
transaction_aware = False
graph_aware = True
db_env = None
def __init__(self, configuration=None, identifier=None):
if not has_bsddb:
raise ImportError(
"Unable to import bsddb/bsddb3, store is unusable.")
self.__open = False
self.__identifier = identifier
super(Sleepycat, self).__init__(configuration)
self._loads = self.node_pickler.loads
self._dumps = self.node_pickler.dumps
def __get_identifier(self):
return self.__identifier
identifier = property(__get_identifier)
def _init_db_environment(self, homeDir, create=True):
if not exists(homeDir):
if create is True:
mkdir(homeDir)
# TODO: implement create method and refactor this to it
self.create(homeDir)
else:
return NO_STORE
db_env = db.DBEnv()
db_env.set_cachesize(0, CACHESIZE) # TODO
# db_env.set_lg_max(1024*1024)
db_env.set_flags(ENVSETFLAGS, 1)
db_env.open(homeDir, ENVFLAGS | db.DB_CREATE)
return db_env
def is_open(self):
return self.__open
def open(self, path, create=True):
if not has_bsddb:
return NO_STORE
homeDir = path
if self.__identifier is None:
self.__identifier = URIRef(pathname2url(abspath(homeDir)))
db_env = self._init_db_environment(homeDir, create)
if db_env == NO_STORE:
return NO_STORE
self.db_env = db_env
self.__open = True
dbname = None
dbtype = db.DB_BTREE
# auto-commit ensures that the open-call commits when transactions
# are enabled
dbopenflags = DBOPENFLAGS
if self.transaction_aware is True:
dbopenflags |= db.DB_AUTO_COMMIT
if create:
dbopenflags |= db.DB_CREATE
dbmode = 0o660
dbsetflags = 0
# create and open the DBs
self.__indicies = [None, ] * 3
self.__indicies_info = [None, ] * 3
for i in range(0, 3):
index_name = to_key_func(
i)((b("s"), b("p"), b("o")), b("c")).decode()
index = db.DB(db_env)
index.set_flags(dbsetflags)
index.open(index_name, dbname, dbtype, dbopenflags, dbmode)
self.__indicies[i] = index
self.__indicies_info[i] = (index, to_key_func(i), from_key_func(i))
lookup = {}
for i in range(0, 8):
results = []
for start in range(0, 3):
score = 1
len = 0
for j in range(start, start + 3):
if i & (1 << (j % 3)):
score = score << 1
len += 1
else:
break
tie_break = 2 - start
results.append(((score, tie_break), start, len))
results.sort()
score, start, len = results[-1]
def get_prefix_func(start, end):
def get_prefix(triple, context):
if context is None:
yield ""
else:
yield context
i = start
while i < end:
yield triple[i % 3]
i += 1
yield ""
return get_prefix
lookup[i] = (
self.__indicies[start],
get_prefix_func(start, start + len),
from_key_func(start),
results_from_key_func(start, self._from_string))
self.__lookup_dict = lookup
self.__contexts = db.DB(db_env)
self.__contexts.set_flags(dbsetflags)
self.__contexts.open("contexts", dbname, dbtype, dbopenflags, dbmode)
self.__namespace = db.DB(db_env)
self.__namespace.set_flags(dbsetflags)
self.__namespace.open("namespace", dbname, dbtype, dbopenflags, dbmode)
self.__prefix = db.DB(db_env)
self.__prefix.set_flags(dbsetflags)
self.__prefix.open("prefix", dbname, dbtype, dbopenflags, dbmode)
self.__k2i = db.DB(db_env)
self.__k2i.set_flags(dbsetflags)
self.__k2i.open("k2i", dbname, db.DB_HASH, dbopenflags, dbmode)
self.__i2k = db.DB(db_env)
self.__i2k.set_flags(dbsetflags)
self.__i2k.open("i2k", dbname, db.DB_RECNO, dbopenflags, dbmode)
self.__needs_sync = False
t = Thread(target=self.__sync_run)
t.setDaemon(True)
t.start()
self.__sync_thread = t
return VALID_STORE
def __sync_run(self):
from time import sleep, time
try:
min_seconds, max_seconds = 10, 300
while self.__open:
if self.__needs_sync:
t0 = t1 = time()
self.__needs_sync = False
while self.__open:
sleep(.1)
if self.__needs_sync:
t1 = time()
self.__needs_sync = False
if time() - t1 > min_seconds \
or time() - t0 > max_seconds:
self.__needs_sync = False
logger.debug("sync")
self.sync()
break
else:
sleep(1)
except Exception as e:
logger.exception(e)
def sync(self):
if self.__open:
for i in self.__indicies:
i.sync()
self.__contexts.sync()
self.__namespace.sync()
self.__prefix.sync()
self.__i2k.sync()
self.__k2i.sync()
def close(self, commit_pending_transaction=False):
self.__open = False
self.__sync_thread.join()
for i in self.__indicies:
i.close()
self.__contexts.close()
self.__namespace.close()
self.__prefix.close()
self.__i2k.close()
self.__k2i.close()
self.db_env.close()
def add(self, triple, context, quoted=False, txn=None):
"""\
Add a triple to the store of triples.
"""
(subject, predicate, object) = triple
assert self.__open, "The Store must be open."
assert context != self, "Can not add triple directly to store"
Store.add(self, (subject, predicate, object), context, quoted)
_to_string = self._to_string
s = _to_string(subject, txn=txn)
p = _to_string(predicate, txn=txn)
o = _to_string(object, txn=txn)
c = _to_string(context, txn=txn)
cspo, cpos, cosp = self.__indicies
value = cspo.get(bb("%s^%s^%s^%s^" % (c, s, p, o)), txn=txn)
if value is None:
self.__contexts.put(bb(c), "", txn=txn)
contexts_value = cspo.get(
bb("%s^%s^%s^%s^" % ("", s, p, o)), txn=txn) or b("")
contexts = set(contexts_value.split(b("^")))
contexts.add(bb(c))
contexts_value = b("^").join(contexts)
assert contexts_value is not None
cspo.put(bb("%s^%s^%s^%s^" % (c, s, p, o)), "", txn=txn)
cpos.put(bb("%s^%s^%s^%s^" % (c, p, o, s)), "", txn=txn)
cosp.put(bb("%s^%s^%s^%s^" % (c, o, s, p)), "", txn=txn)
if not quoted:
cspo.put(bb(
"%s^%s^%s^%s^" % ("", s, p, o)), contexts_value, txn=txn)
cpos.put(bb(
"%s^%s^%s^%s^" % ("", p, o, s)), contexts_value, txn=txn)
cosp.put(bb(
"%s^%s^%s^%s^" % ("", o, s, p)), contexts_value, txn=txn)
self.__needs_sync = True
def __remove(self, xxx_todo_changeme, c, quoted=False, txn=None):
(s, p, o) = xxx_todo_changeme
cspo, cpos, cosp = self.__indicies
contexts_value = cspo.get(
b("^").join([b(""), s, p, o, b("")]), txn=txn) or b("")
contexts = set(contexts_value.split(b("^")))
contexts.discard(c)
contexts_value = b("^").join(contexts)
for i, _to_key, _from_key in self.__indicies_info:
i.delete(_to_key((s, p, o), c), txn=txn)
if not quoted:
if contexts_value:
for i, _to_key, _from_key in self.__indicies_info:
i.put(_to_key((s, p, o), b("")), contexts_value, txn=txn)
else:
for i, _to_key, _from_key in self.__indicies_info:
try:
i.delete(_to_key((s, p, o), b("")), txn=txn)
except db.DBNotFoundError:
pass # TODO: is it okay to ignore these?
def remove(self, xxx_todo_changeme1, context, txn=None):
(subject, predicate, object) = xxx_todo_changeme1
assert self.__open, "The Store must be open."
Store.remove(self, (subject, predicate, object), context)
_to_string = self._to_string
if context is not None:
if context == self:
context = None
if subject is not None \
and predicate is not None \
and object is not None \
and context is not None:
s = _to_string(subject, txn=txn)
p = _to_string(predicate, txn=txn)
o = _to_string(object, txn=txn)
c = _to_string(context, txn=txn)
value = self.__indicies[0].get(bb("%s^%s^%s^%s^" %
(c, s, p, o)), txn=txn)
if value is not None:
self.__remove((bb(s), bb(p), bb(o)), bb(c), txn=txn)
self.__needs_sync = True
else:
cspo, cpos, cosp = self.__indicies
index, prefix, from_key, results_from_key = self.__lookup(
(subject, predicate, object), context, txn=txn)
cursor = index.cursor(txn=txn)
try:
current = cursor.set_range(prefix)
needs_sync = True
except db.DBNotFoundError:
current = None
needs_sync = False
cursor.close()
while current:
key, value = current
cursor = index.cursor(txn=txn)
try:
cursor.set_range(key)
# Hack to stop 2to3 converting this to next(cursor)
current = getattr(cursor, 'next')()
except db.DBNotFoundError:
current = None
cursor.close()
if key.startswith(prefix):
c, s, p, o = from_key(key)
if context is None:
contexts_value = index.get(key, txn=txn) or b("")
# remove triple from all non quoted contexts
contexts = set(contexts_value.split(b("^")))
# and from the conjunctive index
contexts.add(b(""))
for c in contexts:
for i, _to_key, _ in self.__indicies_info:
i.delete(_to_key((s, p, o), c), txn=txn)
else:
self.__remove((s, p, o), c, txn=txn)
else:
break
if context is not None:
if subject is None and predicate is None and object is None:
# TODO: also if context becomes empty and not just on
# remove((None, None, None), c)
try:
self.__contexts.delete(
bb(_to_string(context, txn=txn)), txn=txn)
except db.DBNotFoundError:
pass
self.__needs_sync = needs_sync
def triples(self, xxx_todo_changeme2, context=None, txn=None):
"""A generator over all the triples matching """
(subject, predicate, object) = xxx_todo_changeme2
assert self.__open, "The Store must be open."
if context is not None:
if context == self:
context = None
# _from_string = self._from_string ## UNUSED
index, prefix, from_key, results_from_key = self.__lookup(
(subject, predicate, object), context, txn=txn)
cursor = index.cursor(txn=txn)
try:
current = cursor.set_range(prefix)
except db.DBNotFoundError:
current = None
cursor.close()
while current:
key, value = current
cursor = index.cursor(txn=txn)
try:
cursor.set_range(key)
# Cheap hack so 2to3 doesn't convert to next(cursor)
current = getattr(cursor, 'next')()
except db.DBNotFoundError:
current = None
cursor.close()
if key and key.startswith(prefix):
contexts_value = index.get(key, txn=txn)
yield results_from_key(
key, subject, predicate, object, contexts_value)
else:
break
def __len__(self, context=None):
assert self.__open, "The Store must be open."
if context is not None:
if context == self:
context = None
if context is None:
prefix = b("^")
else:
prefix = bb("%s^" % self._to_string(context))
index = self.__indicies[0]
cursor = index.cursor()
current = cursor.set_range(prefix)
count = 0
while current:
key, value = current
if key.startswith(prefix):
count += 1
# Hack to stop 2to3 converting this to next(cursor)
current = getattr(cursor, 'next')()
else:
break
cursor.close()
return count
def bind(self, prefix, namespace):
prefix = prefix.encode("utf-8")
namespace = namespace.encode("utf-8")
bound_prefix = self.__prefix.get(namespace)
if bound_prefix:
self.__namespace.delete(bound_prefix)
self.__prefix[namespace] = prefix
self.__namespace[prefix] = namespace
def namespace(self, prefix):
prefix = prefix.encode("utf-8")
ns = self.__namespace.get(prefix, None)
if ns is not None:
return URIRef(ns.decode('utf-8'))
return None
def prefix(self, namespace):
namespace = namespace.encode("utf-8")
prefix = self.__prefix.get(namespace, None)
if prefix is not None:
return prefix.decode('utf-8')
return None
def namespaces(self):
cursor = self.__namespace.cursor()
results = []
current = cursor.first()
while current:
prefix, namespace = current
results.append((prefix.decode('utf-8'), namespace.decode('utf-8')))
# Hack to stop 2to3 converting this to next(cursor)
current = getattr(cursor, 'next')()
cursor.close()
for prefix, namespace in results:
yield prefix, URIRef(namespace)
def contexts(self, triple=None):
_from_string = self._from_string
_to_string = self._to_string
if triple:
s, p, o = triple
s = _to_string(s)
p = _to_string(p)
o = _to_string(o)
contexts = self.__indicies[0].get(bb(
"%s^%s^%s^%s^" % ("", s, p, o)))
if contexts:
for c in contexts.split(b("^")):
if c:
yield _from_string(c)
else:
index = self.__contexts
cursor = index.cursor()
current = cursor.first()
cursor.close()
while current:
key, value = current
context = _from_string(key)
yield context
cursor = index.cursor()
try:
cursor.set_range(key)
# Hack to stop 2to3 converting this to next(cursor)
current = getattr(cursor, 'next')()
except db.DBNotFoundError:
current = None
cursor.close()
def add_graph(self, graph):
self.__contexts.put(bb(self._to_string(graph)), "")
def remove_graph(self, graph):
self.remove((None, None, None), graph)
def _from_string(self, i):
k = self.__i2k.get(int(i))
return self._loads(k)
def _to_string(self, term, txn=None):
k = self._dumps(term)
i = self.__k2i.get(k, txn=txn)
if i is None:
# weird behavoir from bsddb not taking a txn as a keyword argument
# for append
if self.transaction_aware:
i = "%s" % self.__i2k.append(k, txn)
else:
i = "%s" % self.__i2k.append(k)
self.__k2i.put(k, i, txn=txn)
else:
i = i.decode()
return i
def __lookup(self, xxx_todo_changeme3, context, txn=None):
(subject, predicate, object) = xxx_todo_changeme3
_to_string = self._to_string
if context is not None:
context = _to_string(context, txn=txn)
i = 0
if subject is not None:
i += 1
subject = _to_string(subject, txn=txn)
if predicate is not None:
i += 2
predicate = _to_string(predicate, txn=txn)
if object is not None:
i += 4
object = _to_string(object, txn=txn)
index, prefix_func, from_key, results_from_key = self.__lookup_dict[i]
# print (subject, predicate, object), context, prefix_func, index
# #DEBUG
prefix = bb(
"^".join(prefix_func((subject, predicate, object), context)))
return index, prefix, from_key, results_from_key
def to_key_func(i):
def to_key(triple, context):
"Takes a string; returns key"
return b("^").join(
(context,
triple[i % 3],
triple[(i + 1) % 3],
triple[(i + 2) % 3], b(""))) # "" to tac on the trailing ^
return to_key
def from_key_func(i):
def from_key(key):
"Takes a key; returns string"
parts = key.split(b("^"))
return \
parts[0], \
parts[(3 - i + 0) % 3 + 1], \
parts[(3 - i + 1) % 3 + 1], \
parts[(3 - i + 2) % 3 + 1]
return from_key
def results_from_key_func(i, from_string):
def from_key(key, subject, predicate, object, contexts_value):
"Takes a key and subject, predicate, object; returns tuple for yield"
parts = key.split(b("^"))
if subject is None:
# TODO: i & 1: # dis assemble and/or measure to see which is faster
# subject is None or i & 1
s = from_string(parts[(3 - i + 0) % 3 + 1])
else:
s = subject
if predicate is None: # i & 2:
p = from_string(parts[(3 - i + 1) % 3 + 1])
else:
p = predicate
if object is None: # i & 4:
o = from_string(parts[(3 - i + 2) % 3 + 1])
else:
o = object
return (s, p, o), (
from_string(c) for c in contexts_value.split(b("^")) if c)
return from_key
def readable_index(i):
s, p, o = "?" * 3
if i & 1:
s = "s"
if i & 2:
p = "p"
if i & 4:
o = "o"
return "%s,%s,%s" % (s, p, o)
| {
"content_hash": "39f2fab5e3c031169531150b99897471",
"timestamp": "",
"source": "github",
"line_count": 605,
"max_line_length": 79,
"avg_line_length": 34.27603305785124,
"alnum_prop": 0.48782369677388243,
"repo_name": "hwroitzsch/DayLikeTodayClone",
"id": "1424f29149aaa230075f6f2c781d42926990e5b6",
"size": "20737",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "venv/lib/python3.5/site-packages/rdflib/plugins/sleepycat.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5939"
},
{
"name": "CSS",
"bytes": "8860"
},
{
"name": "HTML",
"bytes": "449"
},
{
"name": "JavaScript",
"bytes": "402138"
},
{
"name": "PigLatin",
"bytes": "1401"
},
{
"name": "Python",
"bytes": "4694103"
},
{
"name": "Shell",
"bytes": "3823"
}
],
"symlink_target": ""
} |
namespace XPlat.Device.Geolocation
{
using System;
/// <summary>
/// Defines an exception for an error in the <see cref="IGeolocator"/>.
/// </summary>
public class GeolocatorException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="GeolocatorException"/> class.
/// </summary>
public GeolocatorException()
: this(string.Empty)
{
}
/// <summary>Initializes a new instance of the <see cref="GeolocatorException"/> class with a specified error message.</summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public GeolocatorException(string message)
: this(message, null)
{
}
/// <summary>Initializes a new instance of the <see cref="GeolocatorException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.</summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param>
public GeolocatorException(string message, Exception innerException)
: base(message, innerException)
{
}
}
} | {
"content_hash": "70f0e79b3551466b12720dd2e3174f56",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 211,
"avg_line_length": 43.84848484848485,
"alnum_prop": 0.650310988251555,
"repo_name": "jamesmcroft/XPlat-Windows-APIs",
"id": "dc5870f7b007be288ff1eb068077b8d998142c36",
"size": "1577",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/add-v2-config-file",
"path": "src/XPlat.Device.Geolocation/GeolocatorException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "955283"
}
],
"symlink_target": ""
} |
.port, .ip {
font-family: monospace;
}
/* Field errors */
.fielderror {
color: #c0392b;
}
/* Flashes */
.flash-message {
margin-top:20px;
}
.online {
color:#7f8c8d;
}
footer {
margin-bottom: 20px !important;
color:#7f8c8d !important;
}
#donate {
margin-bottom: 10px !important;
}
#refresh, #info, #show, #hide {
color: #337ab7 !important;
text-decoration: none !important;
}
#refresh:hover, #info:hover, #show:hover, #hide:hover {
text-decoration: underline !important;
cursor: pointer !important;
}
#export-content {
font-family: monospace;
word-wrap:break-word !important;
}
#bc-address:hover {
color:#28a4c9;
} | {
"content_hash": "6a8e25df8a9d8285d606d982f3172a07",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 55,
"avg_line_length": 15.066666666666666,
"alnum_prop": 0.6342182890855457,
"repo_name": "FredrikAugust/Aether-Nodes",
"id": "1a27f703301020bdb1af6fcb64cd00a69a9f0ac3",
"size": "678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/static/site.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "678"
},
{
"name": "HTML",
"bytes": "3840"
},
{
"name": "JavaScript",
"bytes": "3007"
},
{
"name": "Python",
"bytes": "5943"
}
],
"symlink_target": ""
} |
FLEX (Flipboard Explorer) is a set of in-app debugging and exploration tools for iOS development. When presented, FLEX shows a toolbar that lives in a window above your application. From this toolbar, you can view and modify nearly every piece of state in your running application.

## Give Yourself Debugging Superpowers
- Inspect and modify views in the hierarchy.
- See the properties and ivars on any object.
- Dynamically modify many properties and ivars.
- Dynamically call instance and class methods.
- Access any live object via a scan of the heap.
- View the file system within your app's sandbox.
- Explore all classes in your app and linked systems frameworks (public and private).
- Quickly access useful objects such as `[UIApplication sharedApplication]`, the app delegate, the root view controller on the key window, and more.
- Dynamically view and modify `NSUserDefaults` values.
Unlike many other debugging tools, FLEX runs entirely inside your app, so you don't need to be connected to LLDB/Xcode or a different remote debugging server. It works well in the simulator and on physical devices.
## Usage
Short version:
```objc
[[FLEXManager sharedManager] showExplorer];
```
More complete version:
```objc
#if DEBUG
#import "FLEXManager.h"
#endif
...
- (void)handleSixFingerQuadrupleTap:(UITapGestureRecognizer *)tapRecognizer
{
#if DEBUG
if (tapRecognizer.state == UIGestureRecognizerStateRecognized) {
// This could also live in a handler for a keyboard shortcut, debug menu item, etc.
[[FLEXManager sharedManager] showExplorer];
}
#endif
}
```
## Feature Examples
### Modify Views
Once a view is selected, you can tap on the info bar below the toolbar to present more details about the view. From there, you can modify properties and call methods.

### All Objects on the Heap
FLEX queries malloc for all the live allocated memory blocks and searches for ones that look like objects. You can see everything from here.

### File Browser
View the file system within your app's sandbox. FLEX shows file sizes, image previews, and pretty prints `.json` and `.plist` files. You can copy text and image files to the pasteboard if you want to inspect them outside of your app.

### System Library Exploration
Go digging for all things public and private. To learn more about a class, you can create an instance of it and explore its default state.

### NSUserDefaults Editing
FLEX allows you to edit defaults that are any combination of strings, numbers, arrays, and dictionaries. The input is parsed as `JSON`. If other kinds of objects are set for a defaults key (i.e. `NSDate`), you can view them but not edit them.

### Learning from Other Apps
The code injection is left as an exercise for the reader. :innocent:
 
## Installation
FLEX is available on [Cocoapods](http://cocoapods.org/). Simply add the following line to your podfile:
```ruby
pod 'FLEX', '~> 1.1'
```
Alternatively, you can manually add the files in `Classes/` to your Xcode project. FLEX requires iOS 6 or higher.
## Excluding FLEX from Release (App Store) Builds
FLEX makes it easy to explore the internals of your app, so it is not something you should expose to your users. Fortunately, it is easy to exclude FLEX files from Release builds. In Xcode, navigate to the "Build Settings" tab of your project. Click the plus and select `Add User-Defined Setting`.

Name the setting `EXCLUDED_SOURCE_FILE_NAMES`. For your `Release` configuration, set the value to `FLEX*`. This will exclude all files with the prefix FLEX from compilation. Leave the value blank for your `Debug` configuration.

At the places in your code where you integrate FLEX, do a `#if DEBUG` check to ensure the tool is only accessible in your `Debug` builds and to avoid errors in your `Release` builds. For more help with integrating FLEX, see the example project.
## Additional Notes
- When setting fields of type `id` or values in `NSUserDefaults`, FLEX attempts to parse the input string as `JSON`. This allows you to use a combination of strings, numbers, arrays, and dictionaries. If you want to set a string value, it must be wrapped in quotes. For ivars or properties that are explicitly typed as `NSStrings`, quotes are not required.
- You may want to disable the exception breakpoint while using FLEX. Certain functions that FLEX uses throw exceptions when they get input they can't handle (i.e. `NSGetSizeAndAlignment()`). FLEX catches these to avoid crashing, but your breakpoint will get hit if it is active.
## Thanks & Credits
FLEX builds on ideas and inspiration from open source tools that came before it. The following resources have been particularly helpful:
- [DCIntrospect](https://github.com/domesticcatsoftware/DCIntrospect): view hierarchy debugging for the iOS simulator.
- [PonyDebugger](https://github.com/square/PonyDebugger): network, core data, and view hierarchy debugging using the Chrome Developer Tools interface.
- [Mike Ash](https://www.mikeash.com/pyblog/): well written, informative blog posts on all things obj-c and more. The links below were very useful for this project:
- [MAObjCRuntime](https://github.com/mikeash/MAObjCRuntime)
- [Let's Build Key Value Coding](https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html)
- [ARM64 and You](https://www.mikeash.com/pyblog/friday-qa-2013-09-27-arm64-and-you.html)
- [RHObjectiveBeagle](https://github.com/heardrwt/RHObjectiveBeagle): a tool for scanning the heap for live objects. It should be noted that the source code of RHObjectiveBeagle was not consulted due to licensing concerns.
- [heap_find.cpp](https://www.opensource.apple.com/source/lldb/lldb-179.1/examples/darwin/heap_find/heap/heap_find.cpp): an example of enumerating malloc blocks for finding objects on the heap.
- [Gist](https://gist.github.com/samdmarshall/17f4e66b5e2e579fd396) from [@samdmarshall](https://github.com/samdmarshall): another example of enumerating malloc blocks.
- [Non-pointer isa](http://www.sealiesoftware.com/blog/archive/2013/09/24/objc_explain_Non-pointer_isa.html): an explanation of changes to the isa field on iOS for ARM64 and mention of the useful `objc_debug_isa_class_mask` variable.
## Contributing
We welcome pull requests for bug fixes, new features, and improvements to FLEX. Contributors to the main FLEX repository must accept Flipboard's Apache-style [Individual Contributor License Agreement (CLA)](https://docs.google.com/forms/d/1gh9y6_i8xFn6pA15PqFeye19VqasuI9-bGp_e0owy74/viewform) before any changes can be merged.
## TODO
- Swift runtime introspection (swift classes, swift objects on the heap, etc.)
- Network request logging
- Improved file type detection and display in the file browser
- Add new NSUserDefault key/value pairs on the fly
Have a question or suggestion for FLEX? Contact [@ryanolsonk](https://twitter.com/ryanolsonk) on twitter.
| {
"content_hash": "1d2ccd020064c50b9b4761b1491da600",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 356,
"avg_line_length": 59.961832061068705,
"alnum_prop": 0.7773392743475493,
"repo_name": "gank0326/FLEX",
"id": "032f0d3e19be8444d6b2380f60e9350a78ebcc45",
"size": "7862",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "M",
"bytes": "331685"
},
{
"name": "Objective-C",
"bytes": "520200"
},
{
"name": "Ruby",
"bytes": "2355"
}
],
"symlink_target": ""
} |
package org.jfree.chart.plot;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* Defines the tokens that indicate the rendering order for series in a
* {@link org.jfree.chart.plot.XYPlot}.
*/
public final class SeriesRenderingOrder implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 209336477448807735L;
/**
* Render series in the order 0, 1, 2, ..., N-1, where N is the number
* of series.
*/
public static final SeriesRenderingOrder FORWARD
= new SeriesRenderingOrder("SeriesRenderingOrder.FORWARD");
/**
* Render series in the order N-1, N-2, ..., 2, 1, 0, where N is the
* number of series.
*/
public static final SeriesRenderingOrder REVERSE
= new SeriesRenderingOrder("SeriesRenderingOrder.REVERSE");
/** The name. */
private String name;
/**
* Private constructor.
*
* @param name the name.
*/
private SeriesRenderingOrder(String name) {
this.name = name;
}
/**
* Returns a string representing the object.
*
* @return The string (never <code>null</code>).
*/
@Override
public String toString() {
return this.name;
}
/**
* Returns <code>true</code> if this object is equal to the specified
* object, and <code>false</code> otherwise.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof SeriesRenderingOrder)) {
return false;
}
SeriesRenderingOrder order = (SeriesRenderingOrder) obj;
if (!this.name.equals(order.toString())) {
return false;
}
return true;
}
/**
* Returns a hash code for this instance.
*
* @return A hash code.
*/
@Override
public int hashCode() {
return this.name.hashCode();
}
/**
* Ensures that serialization returns the unique instances.
*
* @return The object.
*
* @throws ObjectStreamException if there is a problem.
*/
private Object readResolve() throws ObjectStreamException {
if (this.equals(SeriesRenderingOrder.FORWARD)) {
return SeriesRenderingOrder.FORWARD;
}
else if (this.equals(SeriesRenderingOrder.REVERSE)) {
return SeriesRenderingOrder.REVERSE;
}
return null;
}
}
| {
"content_hash": "5f6aa69496fda2f5afc47a90cb0e2f7c",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 74,
"avg_line_length": 25.21359223300971,
"alnum_prop": 0.5968425105891413,
"repo_name": "SESoS/SIMVA-SoS",
"id": "43611f194e88114aacc3c6f4100cde59ac6af8cb",
"size": "4223",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "jfreechart-1.0.19/source/org/jfree/chart/plot/SeriesRenderingOrder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12912"
},
{
"name": "HTML",
"bytes": "206469"
},
{
"name": "Java",
"bytes": "11748151"
},
{
"name": "JavaScript",
"bytes": "827"
},
{
"name": "Makefile",
"bytes": "1672"
},
{
"name": "Perl 6",
"bytes": "14396"
},
{
"name": "Python",
"bytes": "20588"
}
],
"symlink_target": ""
} |
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AppFrame extends JFrame implements IUserInterface{
private static final long serialVersionUID = 1L;
// VARIABLES
Utilisateur user;
JLabel lblNbLocation;
JLabel lblUser;
StationPanel panelStationA, panelStationB, panelStationC, panelStationD;
JPanel panelStations;
GridLayout stationsMainLayout = new GridLayout(2, 2);
javax.swing.border.Border blackBorder;
public AppFrame(Utilisateur user) throws RemoteException{
super("MobiOsLo: Location de vehicules dans toute la Suisse");
this.user = user;
user.setUserInterface(this);
blackBorder = BorderFactory.createLineBorder(Color.black, 2, true);
javax.swing.border.Border paneEdge = BorderFactory.createEmptyBorder(10,10,10,10);
setLayout(new BorderLayout());
// Create instances
lblNbLocation = new JLabel("...");
lblUser = new JLabel("...");
panelStationA = new StationPanel(this.user, 0);
panelStationB = new StationPanel(this.user, 1);
panelStationC = new StationPanel(this.user, 2);
panelStationD = new StationPanel(this.user, 3);
panelStations = new JPanel();
// Custom panel Stations and add stations
panelStations.setBorder(paneEdge);
panelStationA.setBorder(blackBorder);
panelStationB.setBorder(blackBorder);
panelStationC.setBorder(blackBorder);
panelStationD.setBorder(blackBorder);
panelStations.setLayout(stationsMainLayout);
panelStations.add(panelStationA);
panelStations.add(panelStationB);
panelStations.add(panelStationC);
panelStations.add(panelStationD);
stationsMainLayout.setHgap(10);
stationsMainLayout.setVgap(10);
// Custom labels
lblNbLocation.setOpaque(isOpaque());
lblNbLocation.setBackground(Color.DARK_GRAY);
lblNbLocation.setForeground(Color.WHITE);
lblUser.setOpaque(isOpaque());
lblUser.setBackground(Color.DARK_GRAY);
lblUser.setForeground(Color.WHITE);
// Add to pane
add(lblNbLocation, BorderLayout.NORTH);
add(panelStations, BorderLayout.CENTER);
add(lblUser, BorderLayout.SOUTH);
setSize(900, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Affecte au libellé du nombre de véhicule en cours de location
*/
@Override
public void setNbLocation(int nbLocation) {
lblNbLocation.setText("Nombre de locations : " + nbLocation + " véhicules");
}
/**
* Affecte au libellé le nom de l'utilisateur en cours
*/
@Override
public void setUser(String nomUser) {
lblUser.setText("Utilisateur : " + nomUser);
}
/**
* Affecte le nom des stations
*/
@Override
public void setTexteLabel() {
// Velo
if (panelStationA != null)
panelStationA.setTexteLabelVelo(user.getStation(0));
if (panelStationB != null)
panelStationB.setTexteLabelVelo(user.getStation(1));
if (panelStationC != null)
panelStationC.setTexteLabelVelo(user.getStation(2));
if (panelStationD != null)
panelStationD.setTexteLabelVelo(user.getStation(3));
// Voiture
if (panelStationA != null)
panelStationA.setTexteLabelVoiture(user.getStation(0));
if (panelStationB != null)
panelStationB.setTexteLabelVoiture(user.getStation(1));
if (panelStationC != null)
panelStationC.setTexteLabelVoiture(user.getStation(2));
if (panelStationD != null)
panelStationD.setTexteLabelVoiture(user.getStation(3));
}
}
| {
"content_hash": "a386a62c3c2fd2c97e83e160270a0dfc",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 84,
"avg_line_length": 29.583333333333332,
"alnum_prop": 0.7492957746478873,
"repo_name": "devos1/PProgDist_RMI",
"id": "1a2fe0aab450fdce90d5ac9467fc7fe1e47d8dd3",
"size": "3556",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppFrame.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2910"
}
],
"symlink_target": ""
} |
namespace Sunflower
{
Application::Application(const std::wstring& name, const HINSTANCE hInstance, const int nCmdShow)
: nCmdShow_(nCmdShow),
name_(name),
windowClass_(hInstance, name, &StaticWindowProcedure)
{
MEMBER_LOG_STRING_TAG(L"Application");
}
void Application::Run()
{
MEMBER_LOG_SEV(SunflowerUtil::LogLevel::INFO) << L"Running Application";
while(RunFrame());
}
bool Application::RunFrame()
{
if(windows_.empty())
return false;
// Remove windows marked for deletion
windows_.erase(boost::remove_if(windows_,
[&](const std::unique_ptr<Window>& window) -> bool { return window->remove_ ? true : false; }),
windows_.end());
// Process messages
MSG msg;
while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(msg.message == WM_QUIT)
return false;
TranslateMessage(&msg);
DispatchMessage(&msg);
// Check for exceptions caught in static window procedure
if(!windowProcedureExceptions_.empty())
{
AggregateException aggException(windowProcedureExceptions_);
aggException << error_description_info("Static window procedure caught exception(s)");
windowProcedureExceptions_.clear();
throw aggException;
}
}
// Just stubbing this in here for now
for(auto& window : windows_)
{
window->swapChain_.Clear(window->device_.GetImmediateDeviceContext(), DirectX::XMFLOAT4(0.0f, 0.2f, 0.3f, 1.0f));
window->swapChain_.Present(window->device_.GetImmediateDeviceContext());
}
return true;
}
void Application::AddWindow(const WindowProperties& windowProperties)
{
windows_.push_back(std::unique_ptr<Window>(new Window(*this, windowProperties)));
}
LRESULT CALLBACK Application::StaticWindowProcedure(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
Window* window = nullptr;
try
{
if(msg == WM_CREATE)
{
// Get window pointer passed to CreateWindow
window = reinterpret_cast<Window*>(reinterpret_cast<const CREATESTRUCT*>(lParam)->lpCreateParams);
// Set pointer to be retrievable in user data
SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(window));
}
else
window = reinterpret_cast<Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if(window)
{
auto result = window->WindowProcedure(hWnd, msg, wParam, lParam);
if(result)
return *result;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
catch(...)
{
// Don't catch in static function, try and push it to application instance if window exists
if(window)
window->application_.windowProcedureExceptions_.push_back(boost::current_exception());
return DefWindowProc(hWnd, msg, wParam, lParam);
}
}
Graphics::Device& Application::GetDevice(Graphics::DeviceInfo::Adapter& adapter)
{
auto returnedDevice = devices_.find(adapter);
if(returnedDevice == devices_.end())
returnedDevice = devices_.insert(std::make_pair(adapter, SunflowerUtil::make_unique<Graphics::Device>(adapter))).first;
return *returnedDevice->second;
}
} | {
"content_hash": "f8ab9cf750e535b07670d73b9bb41ca1",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 127,
"avg_line_length": 29.508928571428573,
"alnum_prop": 0.6384266263237519,
"repo_name": "kaylynb/Sunflower",
"id": "83df83c5ba8eca2cab81259bc5e33c132849cf56",
"size": "3425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Projects/Sunflower/src/Application.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4940"
},
{
"name": "C#",
"bytes": "15913"
},
{
"name": "C++",
"bytes": "75919"
},
{
"name": "Shell",
"bytes": "250"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.fs.glusterfs;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.hadoop.fs.FSError;
import org.apache.hadoop.fs.Path;
public class GlusterFileOut extends OutputStream{
private FileOutputStream fos;
private GlusterFileOut(File f, boolean append) throws IOException {
this.fos = new FileOutputStream(f, append);
}
/*
* Just forward to the fos
*/
@Override
public void close() throws IOException { fos.close(); }
@Override
public void flush() throws IOException { fos.flush(); }
@Override
public void write(byte[] b, int off, int len) throws IOException {
fos.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
fos.write(b);
}
}
| {
"content_hash": "217d5831e2d81f3cfd3190477c561900",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 71,
"avg_line_length": 24.65714285714286,
"alnum_prop": 0.6720741599073001,
"repo_name": "childsb/glusterfs-hpi",
"id": "5bc357c22f00e39a1625d166cb1eab884250ace9",
"size": "863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/apache/hadoop/fs/glusterfs/GlusterFileOut.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "74595"
},
{
"name": "Shell",
"bytes": "4306"
}
],
"symlink_target": ""
} |
package pubsub_test
import (
"context"
"fmt"
"runtime/debug"
"testing"
"time"
"github.com/hyperledger/burrow/event/pubsub"
"github.com/hyperledger/burrow/event/query"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
clientID = "test-client"
receiveTimeout = 10 * time.Second
)
func TestSubscribe(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
ch, err := s.Subscribe(ctx, clientID, query.Empty{}, 1)
require.NoError(t, err)
err = s.Publish(ctx, "Ka-Zar")
require.NoError(t, err)
assertReceive(t, "Ka-Zar", ch)
err = s.Publish(ctx, "Quicksilver")
require.NoError(t, err)
assertReceive(t, "Quicksilver", ch)
}
func TestDifferentClients(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
ch1, err := s.Subscribe(ctx, "client-1", query.MustParse("tm.events.type='NewBlock'"), 1)
require.NoError(t, err)
err = s.PublishWithTags(ctx, "Iceman", query.TagMap{"tm.events.type": "NewBlock"})
require.NoError(t, err)
assertReceive(t, "Iceman", ch1)
ch2, err := s.Subscribe(ctx, "client-2", query.MustParse("tm.events.type='NewBlock' AND abci.account.name='Igor'"), 1)
require.NoError(t, err)
err = s.PublishWithTags(ctx, "Ultimo", query.TagMap{"tm.events.type": "NewBlock", "abci.account.name": "Igor"})
require.NoError(t, err)
assertReceive(t, "Ultimo", ch1)
assertReceive(t, "Ultimo", ch2)
ch3, err := s.Subscribe(ctx, "client-3", query.MustParse("tm.events.type='NewRoundStep' AND abci.account.name='Igor' AND abci.invoice.number = 10"), 1)
require.NoError(t, err)
err = s.PublishWithTags(ctx, "Valeria Richards", query.TagMap{"tm.events.type": "NewRoundStep"})
require.NoError(t, err)
assert.Zero(t, len(ch3))
}
func TestClientSubscribesTwice(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
q := query.MustParse("tm.events.type='NewBlock'")
ch1, err := s.Subscribe(ctx, clientID, q, 1)
require.NoError(t, err)
err = s.PublishWithTags(ctx, "Goblin Queen", query.TagMap{"tm.events.type": "NewBlock"})
require.NoError(t, err)
assertReceive(t, "Goblin Queen", ch1)
_, err = s.Subscribe(ctx, clientID, q, 1)
require.Error(t, err)
err = s.PublishWithTags(ctx, "Spider-Man", query.TagMap{"tm.events.type": "NewBlock"})
require.NoError(t, err)
assertReceive(t, "Spider-Man", ch1)
}
func TestUnsubscribe(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
ch, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'"), 0)
require.NoError(t, err)
err = s.Unsubscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'"))
require.NoError(t, err)
err = s.Publish(ctx, "Nick Fury")
require.NoError(t, err)
assert.Zero(t, len(ch), "Should not receive anything after Unsubscribe")
_, ok := <-ch
assert.False(t, ok)
}
func TestResubscribe(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
_, err := s.Subscribe(ctx, clientID, query.Empty{}, 1)
require.NoError(t, err)
err = s.Unsubscribe(ctx, clientID, query.Empty{})
require.NoError(t, err)
ch, err := s.Subscribe(ctx, clientID, query.Empty{}, 1)
require.NoError(t, err)
err = s.Publish(ctx, "Cable")
require.NoError(t, err)
assertReceive(t, "Cable", ch)
}
func TestUnsubscribeAll(t *testing.T) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
ch1, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlock'"), 1)
require.NoError(t, err)
ch2, err := s.Subscribe(ctx, clientID, query.MustParse("tm.events.type='NewBlockHeader'"), 1)
require.NoError(t, err)
err = s.UnsubscribeAll(ctx, clientID)
require.NoError(t, err)
err = s.Publish(ctx, "Nick Fury")
require.NoError(t, err)
assert.Zero(t, len(ch1), "Should not receive anything after UnsubscribeAll")
assert.Zero(t, len(ch2), "Should not receive anything after UnsubscribeAll")
_, ok := <-ch1
assert.False(t, ok)
_, ok = <-ch2
assert.False(t, ok)
}
func TestBufferCapacity(t *testing.T) {
s := pubsub.NewServer(pubsub.BufferCapacity(2))
assert.Equal(t, 2, s.BufferCapacity())
ctx := context.Background()
err := s.Publish(ctx, "Nighthawk")
require.NoError(t, err)
err = s.Publish(ctx, "Sage")
require.NoError(t, err)
ctx, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
defer cancel()
err = s.Publish(ctx, "Ironclad")
if assert.Error(t, err) {
assert.Equal(t, context.DeadlineExceeded, err)
}
}
func Benchmark10Clients(b *testing.B) { benchmarkNClients(10, b) }
func Benchmark100Clients(b *testing.B) { benchmarkNClients(100, b) }
func Benchmark1000Clients(b *testing.B) { benchmarkNClients(1000, b) }
func Benchmark10ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(10, b) }
func Benchmark100ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(100, b) }
func Benchmark1000ClientsOneQuery(b *testing.B) { benchmarkNClientsOneQuery(1000, b) }
func benchmarkNClients(n int, b *testing.B) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
for i := 0; i < n; i++ {
ch, err := s.Subscribe(ctx, clientID, query.MustParse(fmt.Sprintf("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = %d", i)), 0)
require.NoError(b, err)
go func() {
for range ch {
}
}()
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
s.PublishWithTags(ctx, "Gamora", query.TagMap{"abci.Account.Owner": "Ivan", "abci.Invoices.Number": fmt.Sprint(i)})
}
}
func benchmarkNClientsOneQuery(n int, b *testing.B) {
s := pubsub.NewServer()
s.Start()
defer s.Stop()
ctx := context.Background()
q := query.MustParse("abci.Account.Owner = 'Ivan' AND abci.Invoices.Number = 1")
for i := 0; i < n; i++ {
ch, err := s.Subscribe(ctx, clientID, q, 0)
require.NoError(b, err)
go func() {
for range ch {
}
}()
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
s.PublishWithTags(ctx, "Gamora", query.TagMap{"abci.Account.Owner": "Ivan", "abci.Invoices.Number": "1"})
}
}
///////////////////////////////////////////////////////////////////////////////
/// HELPERS
///////////////////////////////////////////////////////////////////////////////
func assertReceive(t *testing.T, expected interface{}, ch <-chan interface{}, msgAndArgs ...interface{}) {
select {
case actual := <-ch:
if actual != nil {
assert.Equal(t, expected, actual, msgAndArgs...)
}
case <-time.After(receiveTimeout):
t.Errorf("Expected to receive %v from the channel, got nothing after %v", expected, receiveTimeout)
debug.PrintStack()
}
}
| {
"content_hash": "267de0d350dcb965bdb8933d20d6a564",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 152,
"avg_line_length": 28.067226890756302,
"alnum_prop": 0.6655688622754491,
"repo_name": "eris-ltd/eris-db",
"id": "e8a405462a770383cf562d92975437e80e735dc8",
"size": "6680",
"binary": false,
"copies": "1",
"ref": "refs/heads/dependabot/npm_and_yarn/vent/test/eth/object-path-0.11.8",
"path": "event/pubsub/pubsub_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "927037"
},
{
"name": "Makefile",
"bytes": "5091"
},
{
"name": "Shell",
"bytes": "16115"
}
],
"symlink_target": ""
} |
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
useAllAngular2AppRoots: true,
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
require('connect')().use(require('serve-static')('www')).listen(4200);
},
onPrepare() {
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};
| {
"content_hash": "1dc5a83138db529f18b1e44388bc44b8",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 90,
"avg_line_length": 26.181818181818183,
"alnum_prop": 0.65625,
"repo_name": "mtsukuda/ionicseed",
"id": "be4322d03225cb5133e0f322ecbfb58a7b80ae9f",
"size": "864",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "protractor.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2793"
},
{
"name": "HTML",
"bytes": "3216"
},
{
"name": "JavaScript",
"bytes": "2840"
},
{
"name": "Shell",
"bytes": "359"
},
{
"name": "TypeScript",
"bytes": "36181"
}
],
"symlink_target": ""
} |
package top.cardone.func.v1.configuration.navigation;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import top.cardone.CardoneConsumerApplication;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.CollectionUtils;
import top.cardone.context.ApplicationContextHolder;
import java.util.Map;
@Log4j2
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = CardoneConsumerApplication.class, value = {"spring.profiles.active=test"}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class U0004FuncTest {
@Value("http://localhost:${server.port:8765}${server.servlet.context-path:}/v1/configuration/navigation/u0004.json")
private String funcUrl;
@Value("file:src/test/resources/top/cardone/func/v1/configuration/navigation/U0004FuncTest.func.input.json")
private Resource funcInputResource;
@Value("file:src/test/resources/top/cardone/func/v1/configuration/navigation/U0004FuncTest.func.output.json")
private Resource funcOutputResource;
@Test
public void func() throws Exception {
if (!funcInputResource.exists()) {
FileUtils.write(funcInputResource.getFile(), "{}", Charsets.UTF_8);
}
val input = FileUtils.readFileToString(funcInputResource.getFile(), Charsets.UTF_8);
Map<String, Object> parametersMap = ApplicationContextHolder.getBean(Gson.class).fromJson(input, Map.class);
Assert.assertFalse("输入未配置", CollectionUtils.isEmpty(parametersMap));
Map<String, Object> output = Maps.newLinkedHashMap();
for (val parametersEntry : parametersMap.entrySet()) {
val body = ApplicationContextHolder.getBean(Gson.class).toJson(parametersEntry.getValue());
val headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
headers.set("collectionStationCodeForToken", parametersEntry.getKey().split(":")[0]);
headers.set("token", ApplicationContextHolder.getBean(org.apache.shiro.authc.credential.PasswordService.class).encryptPassword(headers.get("collectionStationCodeForToken").get(0)));
val httpEntity = new HttpEntity<>(body, headers);
val json = new org.springframework.boot.test.web.client.TestRestTemplate().postForObject(funcUrl, httpEntity, String.class);
val value = ApplicationContextHolder.getBean(Gson.class).fromJson(json, Map.class);
output.put(parametersEntry.getKey(), value);
}
FileUtils.write(funcOutputResource.getFile(), ApplicationContextHolder.getBean(Gson.class).toJson(output), Charsets.UTF_8);
}
} | {
"content_hash": "7a6481b27bb88c6583d91816e168dabb",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 193,
"avg_line_length": 44.83561643835616,
"alnum_prop": 0.7540482737549649,
"repo_name": "yht-fand/cardone-platform-configuration",
"id": "e0322dc99db5eabf15fe010e199ba85712f344df",
"size": "3283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "consumer-bak/src/test/java/top/cardone/func/v1/configuration/navigation/U0004FuncTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2141"
},
{
"name": "FreeMarker",
"bytes": "405054"
},
{
"name": "Java",
"bytes": "202112"
},
{
"name": "Shell",
"bytes": "2051"
}
],
"symlink_target": ""
} |
<?php
namespace Noergaard\ServerPilot\Contracts;
use Noergaard\ServerPilot\Entities\ServerEntity;
interface ServersContract
{
/**
* List all servers
*
* @return array
*/
public function all();
/**
* Retrieve an Existing Server
*
* @param $id
*
* @return ServerEntity
*/
public function get($id);
/**
* Connect a New Server
* Use this method to tell ServerPilot that you plan to connect a new serve
*
* @param $name
*
* @return ServerEntity
*/
public function create($name);
/**
* Update a Server
*
* @param $id
* @param bool $firewallEnabled
* @param bool $autoUpdatesEnabled
*
* @return ServerEntity
*/
public function update($id, $firewallEnabled = true, $autoUpdatesEnabled = true);
/**
* Delete a Server
*
* @param $id
*
* @return ServerEntity
*/
public function delete($id);
}
| {
"content_hash": "d9dfb3ca979fa11e4ef3cf2027824df7",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 85,
"avg_line_length": 18.22222222222222,
"alnum_prop": 0.5660569105691057,
"repo_name": "ThomasNoergaard/serverpilot-php-client",
"id": "4e4f27300820eb4bc7035a66205c1b0ef8085d1c",
"size": "984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Contracts/ServersContract.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "69932"
}
],
"symlink_target": ""
} |
namespace ash {
namespace {
InstallAttributes* g_install_attributes = nullptr;
// Calling SetForTesting sets this flag. This flag means that the production
// code which calls Initialize and Shutdown will have no effect - the test
// install attributes will remain in place until ShutdownForTesting is called.
bool g_using_install_attributes_for_testing = false;
// Number of TPM lock state query retries during consistency check.
const int kDbusRetryCount = 12;
// Interval of TPM lock state query retries during consistency check.
constexpr base::TimeDelta kDbusRetryInterval = base::Seconds(5);
std::string ReadMapKey(const std::map<std::string, std::string>& map,
const std::string& key) {
std::map<std::string, std::string>::const_iterator entry = map.find(key);
if (entry != map.end()) {
return entry->second;
}
return std::string();
}
void WarnIfNonempty(const std::map<std::string, std::string>& map,
const std::string& key) {
if (!ReadMapKey(map, key).empty()) {
LOG(WARNING) << key << " expected to be empty.";
}
}
} // namespace
// static
void InstallAttributes::Initialize() {
// Don't reinitialize if a specific instance has already been set for test.
if (g_using_install_attributes_for_testing)
return;
DCHECK(!g_install_attributes);
g_install_attributes = new InstallAttributes(InstallAttributesClient::Get());
g_install_attributes->Init(base::PathService::CheckedGet(
chromeos::dbus_paths::FILE_INSTALL_ATTRIBUTES));
}
// static
bool InstallAttributes::IsInitialized() {
return g_install_attributes;
}
// static
void InstallAttributes::Shutdown() {
if (g_using_install_attributes_for_testing)
return;
DCHECK(g_install_attributes);
delete g_install_attributes;
g_install_attributes = nullptr;
}
// static
InstallAttributes* InstallAttributes::Get() {
DCHECK(g_install_attributes);
return g_install_attributes;
}
// static
void InstallAttributes::SetForTesting(InstallAttributes* test_instance) {
DCHECK(!g_install_attributes);
DCHECK(!g_using_install_attributes_for_testing);
g_install_attributes = test_instance;
g_using_install_attributes_for_testing = true;
}
// static
void InstallAttributes::ShutdownForTesting() {
DCHECK(g_using_install_attributes_for_testing);
// Don't delete the test instance, we are not the owner.
g_install_attributes = nullptr;
g_using_install_attributes_for_testing = false;
}
InstallAttributes::InstallAttributes(
InstallAttributesClient* userdataauth_client)
: install_attributes_client_(userdataauth_client) {}
InstallAttributes::~InstallAttributes() = default;
void InstallAttributes::Init(const base::FilePath& cache_file) {
DCHECK(!device_locked_);
// Mark the consistency check as running to ensure that LockDevice() is
// blocked, but wait for the cryptohome service to be available before
// actually calling TriggerConsistencyCheck().
consistency_check_running_ = true;
install_attributes_client_->WaitForServiceToBeAvailable(
base::BindOnce(&InstallAttributes::OnCryptohomeServiceInitiallyAvailable,
weak_ptr_factory_.GetWeakPtr()));
if (!base::PathExists(cache_file)) {
LOG_IF(WARNING, base::SysInfo::IsRunningOnChromeOS())
<< "Install attributes missing, first sign in";
first_sign_in_ = true;
return;
}
device_locked_ = true;
char buf[16384];
int len = base::ReadFile(cache_file, buf, sizeof(buf));
if (len == -1 || len >= static_cast<int>(sizeof(buf))) {
PLOG(ERROR) << "Failed to read " << cache_file.value();
return;
}
cryptohome::SerializedInstallAttributes install_attrs_proto;
if (!install_attrs_proto.ParseFromArray(buf, len)) {
LOG(ERROR) << "Failed to parse install attributes cache.";
return;
}
google::protobuf::RepeatedPtrField<
const cryptohome::SerializedInstallAttributes::Attribute>::iterator entry;
std::map<std::string, std::string> attr_map;
for (entry = install_attrs_proto.attributes().begin();
entry != install_attrs_proto.attributes().end(); ++entry) {
// The protobuf values contain terminating null characters, so we have to
// sanitize the value here.
attr_map.insert(
std::make_pair(entry->name(), std::string(entry->value().c_str())));
}
DecodeInstallAttributes(attr_map);
}
void InstallAttributes::ReadImmutableAttributes(base::OnceClosure callback) {
if (device_locked_) {
std::move(callback).Run();
return;
}
// Get Install Attributes Status to know if it's ready.
install_attributes_client_->InstallAttributesGetStatus(
user_data_auth::InstallAttributesGetStatusRequest(),
base::BindOnce(&InstallAttributes::ReadAttributesIfReady,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void InstallAttributes::ReadAttributesIfReady(
base::OnceClosure callback,
absl::optional<user_data_auth::InstallAttributesGetStatusReply> reply) {
base::ScopedClosureRunner callback_runner(std::move(callback));
// Can't proceed if the call failed.
if (!reply.has_value()) {
return;
}
// Can't proceed if not ready.
if (reply->state() == ::user_data_auth::InstallAttributesState::UNKNOWN ||
reply->state() ==
::user_data_auth::InstallAttributesState::TPM_NOT_OWNED) {
return;
}
registration_mode_ = policy::DEVICE_MODE_NOT_SET;
// TODO(b/183608597): Migrate this to check reply->state() to avoid the
// blocking calls below.
if (!install_attributes_util::InstallAttributesIsInvalid() &&
!install_attributes_util::InstallAttributesIsFirstInstall()) {
device_locked_ = true;
static const char* const kEnterpriseAttributes[] = {
kAttrEnterpriseDeviceId, kAttrEnterpriseDomain, kAttrEnterpriseRealm,
kAttrEnterpriseMode, kAttrEnterpriseOwned, kAttrEnterpriseUser,
kAttrConsumerKioskEnabled,
};
std::map<std::string, std::string> attr_map;
for (size_t i = 0; i < std::size(kEnterpriseAttributes); ++i) {
std::string value;
if (install_attributes_util::InstallAttributesGet(
kEnterpriseAttributes[i], &value))
attr_map[kEnterpriseAttributes[i]] = value;
}
DecodeInstallAttributes(attr_map);
}
}
void InstallAttributes::SetBlockDevmodeInTpm(
bool block_devmode,
chromeos::DBusMethodCallback<
user_data_auth::SetFirmwareManagementParametersReply> callback) {
DCHECK(!callback.is_null());
DCHECK(!device_locked_);
user_data_auth::SetFirmwareManagementParametersRequest request;
// Set the flags, according to enum FirmwareManagementParametersFlags from
// rpc.proto if devmode is blocked.
if (block_devmode) {
request.mutable_fwmp()->set_flags(
cryptohome::DEVELOPER_DISABLE_BOOT |
cryptohome::DEVELOPER_DISABLE_CASE_CLOSED_DEBUGGING_UNLOCK);
}
install_attributes_client_->SetFirmwareManagementParameters(
request, std::move(callback));
}
void InstallAttributes::LockDevice(policy::DeviceMode device_mode,
const std::string& domain,
const std::string& realm,
const std::string& device_id,
LockResultCallback callback) {
CHECK((device_mode == policy::DEVICE_MODE_ENTERPRISE && !domain.empty() &&
realm.empty() && !device_id.empty()) ||
(device_mode == policy::DEVICE_MODE_ENTERPRISE_AD && domain.empty() &&
!realm.empty() && !device_id.empty()) ||
(device_mode == policy::DEVICE_MODE_DEMO && !domain.empty() &&
realm.empty() && !device_id.empty()) ||
(device_mode == policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH &&
domain.empty() && realm.empty() && device_id.empty()));
DCHECK(callback);
CHECK_EQ(device_lock_running_, false);
// Check for existing lock first.
if (device_locked_) {
if (device_mode != registration_mode_) {
LOG(ERROR) << "Trying to re-lock with wrong mode: device_mode: "
<< device_mode
<< ", registration_mode: " << registration_mode_;
std::move(callback).Run(LOCK_WRONG_MODE);
return;
}
if (domain != registration_domain_ || realm != registration_realm_ ||
device_id != registration_device_id_) {
LOG(ERROR) << "Trying to re-lock with non-matching parameters.";
std::move(callback).Run(LOCK_WRONG_DOMAIN);
return;
}
// Already locked in the right mode, signal success.
std::move(callback).Run(LOCK_SUCCESS);
return;
}
// In case the consistency check is still running, postpone the device locking
// until it has finished. This should not introduce additional delay since
// device locking must wait for TPM initialization anyways.
if (consistency_check_running_) {
CHECK(post_check_action_.is_null());
post_check_action_ = base::BindOnce(
&InstallAttributes::LockDevice, weak_ptr_factory_.GetWeakPtr(),
device_mode, domain, realm, device_id, std::move(callback));
return;
}
device_lock_running_ = true;
// Get Install Attributes Status to know if it's ready.
install_attributes_client_->InstallAttributesGetStatus(
user_data_auth::InstallAttributesGetStatusRequest(),
base::BindOnce(&InstallAttributes::LockDeviceIfAttributesIsReady,
weak_ptr_factory_.GetWeakPtr(), device_mode, domain, realm,
device_id, std::move(callback)));
}
void InstallAttributes::LockDeviceIfAttributesIsReady(
policy::DeviceMode device_mode,
const std::string& domain,
const std::string& realm,
const std::string& device_id,
LockResultCallback callback,
absl::optional<user_data_auth::InstallAttributesGetStatusReply> reply) {
if (!reply.has_value() ||
reply->state() == ::user_data_auth::InstallAttributesState::UNKNOWN ||
reply->state() ==
::user_data_auth::InstallAttributesState::TPM_NOT_OWNED) {
device_lock_running_ = false;
std::move(callback).Run(LOCK_NOT_READY);
return;
}
// Clearing the TPM password seems to be always a good deal. At this point
// install attributes is ready, which implies TPM readiness as well.
chromeos::TpmManagerClient::Get()->ClearStoredOwnerPassword(
::tpm_manager::ClearStoredOwnerPasswordRequest(),
base::BindOnce(&InstallAttributes::OnClearStoredOwnerPassword,
weak_ptr_factory_.GetWeakPtr()));
// Make sure we really have a working InstallAttrs.
if (install_attributes_util::InstallAttributesIsInvalid()) {
LOG(ERROR) << "Install attributes invalid.";
device_lock_running_ = false;
std::move(callback).Run(LOCK_BACKEND_INVALID);
return;
}
if (!install_attributes_util::InstallAttributesIsFirstInstall()) {
LOG(ERROR) << "Install attributes already installed.";
device_lock_running_ = false;
std::move(callback).Run(LOCK_ALREADY_LOCKED);
return;
}
// Set values in the InstallAttrs.
std::string kiosk_enabled, enterprise_owned;
if (device_mode == policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH) {
kiosk_enabled = "true";
} else {
enterprise_owned = "true";
}
std::string mode = GetDeviceModeString(device_mode);
if (!install_attributes_util::InstallAttributesSet(kAttrConsumerKioskEnabled,
kiosk_enabled) ||
!install_attributes_util::InstallAttributesSet(kAttrEnterpriseOwned,
enterprise_owned) ||
!install_attributes_util::InstallAttributesSet(kAttrEnterpriseMode,
mode) ||
!install_attributes_util::InstallAttributesSet(kAttrEnterpriseDomain,
domain) ||
!install_attributes_util::InstallAttributesSet(kAttrEnterpriseRealm,
realm) ||
!install_attributes_util::InstallAttributesSet(kAttrEnterpriseDeviceId,
device_id)) {
LOG(ERROR) << "Failed writing attributes.";
device_lock_running_ = false;
std::move(callback).Run(LOCK_SET_ERROR);
return;
}
if (!install_attributes_util::InstallAttributesFinalize() ||
install_attributes_util::InstallAttributesIsFirstInstall()) {
LOG(ERROR) << "Failed locking.";
device_lock_running_ = false;
std::move(callback).Run(LOCK_FINALIZE_ERROR);
return;
}
ReadImmutableAttributes(
base::BindOnce(&InstallAttributes::OnReadImmutableAttributes,
weak_ptr_factory_.GetWeakPtr(), device_mode, domain, realm,
device_id, std::move(callback)));
}
void InstallAttributes::OnReadImmutableAttributes(policy::DeviceMode mode,
const std::string& domain,
const std::string& realm,
const std::string& device_id,
LockResultCallback callback) {
device_lock_running_ = false;
if (registration_mode_ != mode || registration_domain_ != domain ||
registration_realm_ != realm || registration_device_id_ != device_id) {
LOG(ERROR) << "Locked data doesn't match.";
std::move(callback).Run(LOCK_READBACK_ERROR);
return;
}
std::move(callback).Run(LOCK_SUCCESS);
}
bool InstallAttributes::IsEnterpriseManaged() const {
if (!device_locked_) {
return false;
}
return registration_mode_ == policy::DEVICE_MODE_ENTERPRISE ||
registration_mode_ == policy::DEVICE_MODE_ENTERPRISE_AD ||
registration_mode_ == policy::DEVICE_MODE_DEMO;
}
bool InstallAttributes::IsActiveDirectoryManaged() const {
if (!device_locked_) {
return false;
}
return registration_mode_ == policy::DEVICE_MODE_ENTERPRISE_AD;
}
bool InstallAttributes::IsCloudManaged() const {
if (!device_locked_) {
return false;
}
return registration_mode_ == policy::DEVICE_MODE_ENTERPRISE ||
registration_mode_ == policy::DEVICE_MODE_DEMO;
}
bool InstallAttributes::IsConsumerKioskDeviceWithAutoLaunch() {
return device_locked_ &&
registration_mode_ == policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH;
}
void InstallAttributes::TriggerConsistencyCheck(int dbus_retries) {
chromeos::TpmManagerClient::Get()->GetTpmNonsensitiveStatus(
::tpm_manager::GetTpmNonsensitiveStatusRequest(),
base::BindOnce(&InstallAttributes::OnTpmStatusComplete,
weak_ptr_factory_.GetWeakPtr(), dbus_retries));
}
void InstallAttributes::OnTpmStatusComplete(
int dbus_retries_remaining,
const ::tpm_manager::GetTpmNonsensitiveStatusReply& reply) {
if (reply.status() != ::tpm_manager::STATUS_SUCCESS &&
dbus_retries_remaining) {
LOG(WARNING) << "Failed to get tpm status reply; status: "
<< reply.status();
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE,
base::BindOnce(&InstallAttributes::TriggerConsistencyCheck,
weak_ptr_factory_.GetWeakPtr(),
dbus_retries_remaining - 1),
kDbusRetryInterval);
return;
}
base::HistogramBase::Sample state;
// If we get the TPM status successfully, we are interested if install
// attributes file exists (device_locked_), if the device is enrolled
// (registration_mode_) and if the TPM is locked, meaning the TPM password
// is deleted so the value from result is empty.
if (reply.status() == ::tpm_manager::STATUS_SUCCESS) {
const bool is_cloud_managed =
registration_mode_ == policy::DEVICE_MODE_ENTERPRISE ||
registration_mode_ == policy::DEVICE_MODE_DEMO;
state = (device_locked_ ? 1 : 0) | (is_cloud_managed ? 2 : 0) |
(!reply.is_owner_password_present() ? 4 : 0);
} else {
LOG(WARNING) << "Failed to get TPM status after retries; status: "
<< reply.status();
state = 8;
}
UMA_HISTOGRAM_ENUMERATION("Enterprise.AttributesTPMConsistency", state, 9);
// Run any action (LockDevice call) that might have queued behind the
// consistency check.
consistency_check_running_ = false;
if (post_check_action_) {
std::move(post_check_action_).Run();
post_check_action_.Reset();
}
}
void InstallAttributes::OnClearStoredOwnerPassword(
const ::tpm_manager::ClearStoredOwnerPasswordReply& reply) {
LOG_IF(WARNING, reply.status() != ::tpm_manager::STATUS_SUCCESS)
<< "Failed to call ClearStoredOwnerPassword; status: " << reply.status();
}
// Warning: The values for these keys (but not the keys themselves) are stored
// in the protobuf with a trailing zero. Also note that some of these constants
// have been copied to login_manager/device_policy_service.cc. Please make sure
// that all changes to the constants are reflected there as well.
const char InstallAttributes::kConsumerDeviceMode[] = "consumer";
const char InstallAttributes::kEnterpriseDeviceMode[] = "enterprise";
const char InstallAttributes::kEnterpriseADDeviceMode[] = "enterprise_ad";
const char InstallAttributes::kLegacyRetailDeviceMode[] = "kiosk";
const char InstallAttributes::kConsumerKioskDeviceMode[] = "consumer_kiosk";
const char InstallAttributes::kDemoDeviceMode[] = "demo_mode";
const char InstallAttributes::kAttrEnterpriseDeviceId[] =
"enterprise.device_id";
const char InstallAttributes::kAttrEnterpriseDomain[] = "enterprise.domain";
const char InstallAttributes::kAttrEnterpriseRealm[] = "enterprise.realm";
const char InstallAttributes::kAttrEnterpriseMode[] = "enterprise.mode";
const char InstallAttributes::kAttrEnterpriseOwned[] = "enterprise.owned";
const char InstallAttributes::kAttrEnterpriseUser[] = "enterprise.user";
const char InstallAttributes::kAttrConsumerKioskEnabled[] =
"consumer.app_kiosk_enabled";
void InstallAttributes::OnCryptohomeServiceInitiallyAvailable(
bool service_is_ready) {
if (!service_is_ready)
LOG(ERROR) << "Failed waiting for cryptohome D-Bus service availability.";
// Start the consistency check even if we failed to wait for availability;
// hopefully the service will become available eventually.
TriggerConsistencyCheck(kDbusRetryCount);
}
std::string InstallAttributes::GetDeviceModeString(policy::DeviceMode mode) {
switch (mode) {
case policy::DEVICE_MODE_CONSUMER:
return InstallAttributes::kConsumerDeviceMode;
case policy::DEVICE_MODE_ENTERPRISE:
return InstallAttributes::kEnterpriseDeviceMode;
case policy::DEVICE_MODE_ENTERPRISE_AD:
return InstallAttributes::kEnterpriseADDeviceMode;
case policy::DEPRECATED_DEVICE_MODE_LEGACY_RETAIL_MODE:
return InstallAttributes::kLegacyRetailDeviceMode;
case policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH:
return InstallAttributes::kConsumerKioskDeviceMode;
case policy::DEVICE_MODE_DEMO:
return InstallAttributes::kDemoDeviceMode;
case policy::DEVICE_MODE_PENDING:
case policy::DEVICE_MODE_NOT_SET:
break;
}
NOTREACHED() << "Invalid device mode: " << mode;
return std::string();
}
policy::DeviceMode InstallAttributes::GetDeviceModeFromString(
const std::string& mode) {
if (mode == InstallAttributes::kConsumerDeviceMode)
return policy::DEVICE_MODE_CONSUMER;
if (mode == InstallAttributes::kEnterpriseDeviceMode)
return policy::DEVICE_MODE_ENTERPRISE;
if (mode == InstallAttributes::kEnterpriseADDeviceMode)
return policy::DEVICE_MODE_ENTERPRISE_AD;
if (mode == InstallAttributes::kLegacyRetailDeviceMode)
return policy::DEPRECATED_DEVICE_MODE_LEGACY_RETAIL_MODE;
if (mode == InstallAttributes::kConsumerKioskDeviceMode)
return policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH;
if (mode == InstallAttributes::kDemoDeviceMode)
return policy::DEVICE_MODE_DEMO;
return policy::DEVICE_MODE_NOT_SET;
}
void InstallAttributes::DecodeInstallAttributes(
const std::map<std::string, std::string>& attr_map) {
// Start from a clean slate.
registration_mode_ = policy::DEVICE_MODE_NOT_SET;
registration_domain_.clear();
registration_realm_.clear();
registration_device_id_.clear();
const std::string enterprise_owned =
ReadMapKey(attr_map, kAttrEnterpriseOwned);
const std::string consumer_kiosk_enabled =
ReadMapKey(attr_map, kAttrConsumerKioskEnabled);
const std::string mode = ReadMapKey(attr_map, kAttrEnterpriseMode);
const std::string domain = ReadMapKey(attr_map, kAttrEnterpriseDomain);
const std::string realm = ReadMapKey(attr_map, kAttrEnterpriseRealm);
const std::string device_id = ReadMapKey(attr_map, kAttrEnterpriseDeviceId);
const std::string user_deprecated = ReadMapKey(attr_map, kAttrEnterpriseUser);
if (enterprise_owned == "true") {
WarnIfNonempty(attr_map, kAttrConsumerKioskEnabled);
registration_device_id_ = device_id;
// Set registration_mode_.
registration_mode_ = GetDeviceModeFromString(mode);
if (registration_mode_ != policy::DEVICE_MODE_ENTERPRISE &&
registration_mode_ != policy::DEVICE_MODE_ENTERPRISE_AD &&
registration_mode_ != policy::DEVICE_MODE_DEMO) {
if (!mode.empty()) {
LOG(WARNING) << "Bad " << kAttrEnterpriseMode << ": " << mode;
}
registration_mode_ = policy::DEVICE_MODE_ENTERPRISE;
}
if (registration_mode_ == policy::DEVICE_MODE_ENTERPRISE ||
registration_mode_ == policy::DEVICE_MODE_DEMO) {
// Either set registration_domain_ ...
WarnIfNonempty(attr_map, kAttrEnterpriseRealm);
if (!domain.empty()) {
// The canonicalization is for compatibility with earlier versions.
registration_domain_ = gaia::CanonicalizeDomain(domain);
} else if (!user_deprecated.empty()) {
// Compatibility for pre M19 code.
registration_domain_ = gaia::ExtractDomainName(user_deprecated);
} else {
LOG(WARNING) << "Couldn't read domain.";
}
} else {
// ... or set registration_realm_.
WarnIfNonempty(attr_map, kAttrEnterpriseDomain);
if (!realm.empty()) {
registration_realm_ = realm;
} else {
LOG(WARNING) << "Couldn't read realm.";
}
}
return;
}
WarnIfNonempty(attr_map, kAttrEnterpriseOwned);
WarnIfNonempty(attr_map, kAttrEnterpriseDomain);
WarnIfNonempty(attr_map, kAttrEnterpriseRealm);
WarnIfNonempty(attr_map, kAttrEnterpriseDeviceId);
WarnIfNonempty(attr_map, kAttrEnterpriseUser);
if (consumer_kiosk_enabled == "true") {
registration_mode_ = policy::DEVICE_MODE_CONSUMER_KIOSK_AUTOLAUNCH;
return;
}
WarnIfNonempty(attr_map, kAttrConsumerKioskEnabled);
if (user_deprecated.empty()) {
registration_mode_ = policy::DEVICE_MODE_CONSUMER;
}
}
} // namespace ash
| {
"content_hash": "125d37bc4703e26fccc1b5ee2a415c26",
"timestamp": "",
"source": "github",
"line_count": 595,
"max_line_length": 80,
"avg_line_length": 38.452100840336136,
"alnum_prop": 0.6802744875213077,
"repo_name": "chromium/chromium",
"id": "12c4fc70ced01043b7263fe260fadaf1e7a90411",
"size": "24048",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "chromeos/ash/components/install_attributes/install_attributes.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Copyright (c) 2016-2017 Iman Ghafoori
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.**
| {
"content_hash": "d6890c305d54cbb5b6ec9f7a365c18ff",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 100,
"avg_line_length": 66.625,
"alnum_prop": 0.8030018761726079,
"repo_name": "imanghafoori1/laravel-widgetize",
"id": "1d7c2ddd4636eeae9c88a5bb9a5854914ec74075",
"size": "1081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "6"
},
{
"name": "PHP",
"bytes": "61069"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<datasource jndi-name="jdbc/ApiManagerDS" pool-name="apiman-manager-api" enabled="true"
use-java-context="true">
<connection-url>jdbc:mysql://MYSQLSERVER:3306/apiman</connection-url>
<driver>mysql-connector-java-5.1.33-bin.jar_com.mysql.jdbc.Driver_5_1</driver>
<pool>
<max-pool-size>30</max-pool-size>
</pool>
<security>
<user-name>DBUSER</user-name>
<password>DBPASS</password>
</security>
</datasource>
</datasources>
| {
"content_hash": "62a2a518d131973a5985c154c9e3ce33",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 89,
"avg_line_length": 34.93333333333333,
"alnum_prop": 0.6698473282442748,
"repo_name": "fadiabdeen/apiman",
"id": "bae8ee8c917448cbd00cca6e5cbfef6e43053a0a",
"size": "524",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "distro/wildfly8/src/main/resources/overlay/apiman/sample-configs/apiman-ds_mysql.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "37613"
},
{
"name": "HTML",
"bytes": "299621"
},
{
"name": "Java",
"bytes": "3101857"
},
{
"name": "JavaScript",
"bytes": "46420"
},
{
"name": "Shell",
"bytes": "1655"
},
{
"name": "TypeScript",
"bytes": "279927"
}
],
"symlink_target": ""
} |
namespace vfs {
class vfs : public interfaces::component {
constexpr static const char *name_ = "vfs";
static null_block_device null_bd_;
utils::array<block_device *, 32> block_devices_;
unsigned bd_index_ = 0;
utils::list<mount_point_t> mount_points_;
utils::list<file_t> files_;
cache cache_;
bool node_exists(const path_t &filename, const vnode_t &parent) const;
void get_vnode(const utils::string &name, vnode_t &parent_node, cache::dir_entry *parent_entry, cache::dir_entry *child_entry);
public:
enum class mode {
read, write, read_write
};
vfs(file_system &rootfs, block_device &bd = null_bd_);
void initialize() override;
utils::maybe<vnode_t> mount(const path_t &path, file_system &fs, block_device &bd);
utils::maybe<vnode_t> lookup(const path_t &path);
utils::maybe<vnode_t> create(const path_t &path, vnode::type type);
utils::maybe<file_t> open(const path_t &path, file::mode mode);
cache &get_cache();
int register_device(block_device &dev);
dev_t get_device_id(block_device &bd);
};
vnode_t mount_fs(const path_t &path, file_system &fs, block_device &bd = null_bd_);
} // namespace vfs
| {
"content_hash": "5b41e2c708ca703e39c9c4d65a875a0a",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 131,
"avg_line_length": 30.76923076923077,
"alnum_prop": 0.66,
"repo_name": "Mrokkk/objective-kernel",
"id": "9ac9fc7c0a9506b170957d980937f24029cb2b73",
"size": "1481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kernel/vfs/vfs.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3172"
},
{
"name": "C++",
"bytes": "134162"
},
{
"name": "CMake",
"bytes": "8120"
},
{
"name": "Shell",
"bytes": "4624"
}
],
"symlink_target": ""
} |
<?php
namespace app\modules\catalog\models;
use Yii;
/**
* This is the model class for table "{{%company_image}}".
*
* @property integer $company_id
* @property integer $image_id
*
* @property Image $image
* @property Company $company
*/
class CompanyImage extends \app\modules\core\models\CoreModel
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%company_image}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['company_id', 'image_id'], 'required'],
[['company_id', 'image_id'], 'integer']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'company_id' => 'Company ID',
'image_id' => 'Image ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getImage()
{
return $this->hasOne(Image::className(), ['id' => 'image_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCompany()
{
return $this->hasOne(Company::className(), ['id' => 'company_id']);
}
}
| {
"content_hash": "d47fd9ced612976e298dad915cb551cc",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 75,
"avg_line_length": 18.761904761904763,
"alnum_prop": 0.5135363790186125,
"repo_name": "proteye/YiiPress2",
"id": "0446ee26444015c3b9c2330078d1476af8b7a878",
"size": "1182",
"binary": false,
"copies": "1",
"ref": "refs/heads/developer",
"path": "modules/catalog/models/CompanyImage.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "271"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "1722"
},
{
"name": "JavaScript",
"bytes": "524"
},
{
"name": "PHP",
"bytes": "1318701"
}
],
"symlink_target": ""
} |
<?php
namespace Figaromedias\Bundle\PechealamoucheBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class PechealamoucheBundle extends Bundle
{
}
| {
"content_hash": "74c547288fa42e75cb3c626386607a21",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 51,
"avg_line_length": 17.22222222222222,
"alnum_prop": 0.832258064516129,
"repo_name": "figaromedias/Ateliers_figaro",
"id": "31801f1cac35fce076a819839aa00e00324678ff",
"size": "155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Figaromedias/Bundle/PechealamoucheBundle/PechealamoucheBundle.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1223"
},
{
"name": "CSS",
"bytes": "1604027"
},
{
"name": "HTML",
"bytes": "1332825"
},
{
"name": "JavaScript",
"bytes": "3543980"
},
{
"name": "PHP",
"bytes": "537359"
},
{
"name": "Shell",
"bytes": "167"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: code/googleappengine-read-only/python/google/appengine/dist27 Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="gae-python.logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">App Engine Python SDK
 <span id="projectnumber">v1.6.9 rev.445</span>
</div>
<div id="projectbrief">The Python runtime is available as an experimental Preview feature.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_cc5cb16f35c6261c73c82f9ce78b8312.html">code</a></li><li class="navelem"><a class="el" href="dir_64efef83f94b926fb27fb8d93d3ed9d2.html">googleappengine-read-only</a></li><li class="navelem"><a class="el" href="dir_25ebad5458da85d910971d428f275e1c.html">python</a></li><li class="navelem"><a class="el" href="dir_94267d97c0aa337e48bb4870b6bb9ca0.html">google</a></li><li class="navelem"><a class="el" href="dir_f5d04dff364ffdc181908d441c063eae.html">appengine</a></li><li class="navelem"><a class="el" href="dir_8b794d5cb57202a963916ef4386fee86.html">dist27</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">dist27 Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="subdirs"></a>
Directories</h2></td></tr>
<tr class="memitem:dir_92c77fe065d712b702640e334a57036a"><td class="memItemLeft" align="right" valign="top">directory  </td><td class="memItemRight" valign="bottom"><a class="el" href="dir_92c77fe065d712b702640e334a57036a.html">gae_override</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:dir_3c9001cc2d29cbe6f244ed78b9cfe501"><td class="memItemLeft" align="right" valign="top">directory  </td><td class="memItemRight" valign="bottom"><a class="el" href="dir_3c9001cc2d29cbe6f244ed78b9cfe501.html">python_std_lib</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:dist27_2____init_____8py"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>__init__.py</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:7_2httplib_8py"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>httplib.py</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:7_2socket_8py"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>socket.py</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:threading_8py"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>threading.py</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:urllib_8py"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><b>urllib.py</b></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<address class="footer">
<small>Maintained by <a href="http://www.tzmartin.com">tzmartin</a></small>
</address> | {
"content_hash": "cc4c6a688d20dc009c1ea87d8dc72225",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 615,
"avg_line_length": 67.8955223880597,
"alnum_prop": 0.6922400527588481,
"repo_name": "tzmartin/gae-python.docset",
"id": "6f4a89d4214bca7f3af09eaaf3526652e9e76f38",
"size": "4549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Contents/Resources/Documents/dir_8b794d5cb57202a963916ef4386fee86.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "26526"
},
{
"name": "JavaScript",
"bytes": "3140"
}
],
"symlink_target": ""
} |
class WelcomeController < ApplicationController
def index
render text: "It worked - #{Time.now} - #{hostname}"
end
private
def hostname
%x(hostname)
end
end
| {
"content_hash": "976da138e41af86bcf34e5f24ab5d8c7",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 16.09090909090909,
"alnum_prop": 0.6779661016949152,
"repo_name": "juwalter/capistrano-docker-rails-sample",
"id": "904c085b3a668a92d90df3a33585bba422e6e423",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/welcome_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "546"
},
{
"name": "JavaScript",
"bytes": "664"
},
{
"name": "Ruby",
"bytes": "15838"
},
{
"name": "Shell",
"bytes": "3620"
}
],
"symlink_target": ""
} |
title: azu25
type: products
image: /img/Screen Shot 2017-05-09 at 11.56.54 AM.png
heading: u25
description: lksadjf lkasdjf lksajdf lksdaj flksadj flksa fdj
main:
heading: Foo Bar BAz
description: |-
***This is i a thing***kjh hjk kj
# Blah Blah
## Blah
### Baah
image1:
alt: kkkk
---
| {
"content_hash": "bb516298e41c9903c204d1295ac10d3e",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 61,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6656716417910448,
"repo_name": "pblack/kaldi-hugo-cms-template",
"id": "0e82f1b74c7da5228278d853947f55797c7469ce",
"size": "339",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/content/pages2/azu25.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94394"
},
{
"name": "HTML",
"bytes": "18889"
},
{
"name": "JavaScript",
"bytes": "10014"
}
],
"symlink_target": ""
} |
@extends('plantillas.admin.mainAdmin')
@section('title','Editar Nombre')
@section('titleComplement','Admin')
@section('headerContent','Editar Nombre')
@section('headerDescription','...')
@section('contentPage')
<div class="row">
<div class="col-md-5"><div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">{{$tipo->nombre}}</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
{!! Form::open(['route'=> ['admin.tiposCoctel.update',$tipo],'method'=>'PUT']) !!}
<div class="box-body">
<div class="form-group has-feedback">
<input value="{{$tipo->nombre}}" type="text" class="form-control" name="nombre" placeholder="Nombre" required="required" maxlength="40">
<span class="glyphicon glyphicon fa fa-transgender-alt form-control-feedback"></span>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Editar</button>
</div>
{!! Form::close() !!}
</div></div>
<div class="col-md-4"></div>
</div>
@endsection | {
"content_hash": "93d61bce36658dd0e238a4a708e84883",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 160,
"avg_line_length": 41.53125,
"alnum_prop": 0.4928517682468021,
"repo_name": "fran-bravo/social-cocktail",
"id": "663a5b2cf2b2d305c1d01d5824a5b8f6889ea840",
"size": "1329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/views/plantillas/admin/tiposCoctel/edit.blade.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "CSS",
"bytes": "2259"
},
{
"name": "HTML",
"bytes": "2067424"
},
{
"name": "JavaScript",
"bytes": "2953688"
},
{
"name": "PHP",
"bytes": "201098"
}
],
"symlink_target": ""
} |
package com.sequenceiq.it.cloudbreak.action.v4.notificationtest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sequenceiq.it.cloudbreak.CloudbreakClient;
import com.sequenceiq.it.cloudbreak.action.Action;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.util.NotificationTestingTestDto;
public class NotificationTestingAction implements Action<NotificationTestingTestDto, CloudbreakClient> {
private static final Logger LOGGER = LoggerFactory.getLogger(NotificationTestingAction.class);
@Override
public NotificationTestingTestDto action(TestContext testContext, NotificationTestingTestDto testDto, CloudbreakClient cloudbreakClient) throws Exception {
String logInitMessage = "Posting notification test";
LOGGER.info("{}", logInitMessage);
cloudbreakClient.getDefaultClient().utilV4Endpoint().postNotificationTest();
LOGGER.info("{} was successful", logInitMessage);
return testDto;
}
}
| {
"content_hash": "f64b52639240f3aceb9bc056cbe19147",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 159,
"avg_line_length": 44.30434782608695,
"alnum_prop": 0.7978410206084396,
"repo_name": "hortonworks/cloudbreak",
"id": "0fed5e1e830d853c641446e9191a91d9932a1cce",
"size": "1019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "integration-test/src/main/java/com/sequenceiq/it/cloudbreak/action/v4/notificationtest/NotificationTestingAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7535"
},
{
"name": "Dockerfile",
"bytes": "9586"
},
{
"name": "Fluent",
"bytes": "10"
},
{
"name": "FreeMarker",
"bytes": "395982"
},
{
"name": "Groovy",
"bytes": "523"
},
{
"name": "HTML",
"bytes": "9917"
},
{
"name": "Java",
"bytes": "55250904"
},
{
"name": "JavaScript",
"bytes": "47923"
},
{
"name": "Jinja",
"bytes": "190660"
},
{
"name": "Makefile",
"bytes": "8537"
},
{
"name": "PLpgSQL",
"bytes": "1830"
},
{
"name": "Perl",
"bytes": "17726"
},
{
"name": "Python",
"bytes": "29898"
},
{
"name": "SaltStack",
"bytes": "222692"
},
{
"name": "Scala",
"bytes": "11168"
},
{
"name": "Shell",
"bytes": "416225"
}
],
"symlink_target": ""
} |
var frozenRef = firebase.database().ref('Lists/Walmart/Frozen');
var frozenList = document.getElementById("frozenList");
document.getElementById("addItemFrozen").addEventListener('click', function() {
var itemName = document.getElementById("itemName").value.trim();
if(itemName.length > 0) {
saveToFB(itemName);
var li = "<li>" + itemName + "<li>";
amazon.innerHTML += li;
}
document.getElementById("itemName").value = "";
alert(" " + itemName + " has been added!");
location.reload();
}, false);
function saveToFB(itemName) {
// save data to Frozen Firebase
frozenRef.push({
title: itemName
})
document.getElementById("itemName").value = "";
};
function refreshList(list, element) {
var ls = '';
for (var i = 0; i < list.length; i++) {
ls += '<li data-key="' + list[i].key + '">' + list[i].title + ' ' + genLinks(list[i].key, list[i].title) + '</li>';
};
/*document.getElementById('amazonList').innerHTML = ls;*/
/*document.getElementById('frozenList').innerHTML = ls;*/
document.getElementById(element).innerHTML = ls;
};
function genLinks(key, itName) {
var links = '';
links += '<a id="editBtn" href="javascript:edit(\'' + key + '\',\'' + itName + '\')">Edit</a> | ';
links += '<a id="deleteBtn" href="javascript:del(\'' + key + '\',\'' + itName + '\')">Delete</a>';
return links;
};
function edit(key, itName) {
var itemName = prompt("Update the item name", itName);
if (itName && itemName.length > 0) {
// Build the FireBase endpoint to the item
var updateFrozenRef = buildEndPoint(key);
updateFrozenRef.update({
title: itemName
});
}
}
function del(key, itName) {
var response = confirm("Remove \"" + itName + "\" from the list?");
if (response == true) {
// build the FB endpoint to the item in movies collection
var deleteItemRef = buildEndPoint(key);
deleteItemRef.remove();
}
}
function buildEndPoint(key) {
var frozenRef = firebase.database().ref('Lists/Walmart/Frozen').child(key);
location.reload();
return frozenRef;
}
// This will get fired on inital load as well as whenever there is a change in the data.
frozenRef.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
var element = 'frozenList';
for (var key in data) {
if (data.hasOwnProperty(key)) {
title = data[key].title ? data[key].title : '';
if (title.trim().length > 0) {
list.push({
title: title,
key: key
})
}
}
}
// refresh the UI
refreshList(list, element);
});
| {
"content_hash": "937c53e0df40274cb394a38d3649d6e9",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 117,
"avg_line_length": 30.11627906976744,
"alnum_prop": 0.6158301158301158,
"repo_name": "favaroj/shopping-list",
"id": "253fa7cf74c5539e503d20a33dbdb275d5004b5e",
"size": "2590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/Frozen.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3542"
},
{
"name": "HTML",
"bytes": "26164"
},
{
"name": "JavaScript",
"bytes": "37256"
}
],
"symlink_target": ""
} |
package org.jenkinsci.plugins.mesos;
import org.apache.commons.lang.StringUtils;
import org.apache.mesos.Protos;
import org.apache.mesos.SchedulerDriver;
import org.jenkinsci.plugins.mesos.scheduling.Lease;
import org.jenkinsci.plugins.mesos.scheduling.Request;
import org.jenkinsci.plugins.mesos.scheduling.creator.TaskCreator;
import org.jenkinsci.plugins.mesos.scheduling.fitness.FitnessRater;
import org.jenkinsci.plugins.mesos.scheduling.fitness.NodeAffineRaters;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
public class JenkinsSchedulerNew extends JenkinsScheduler {
public static final String NAME = "FitnessScheduler";
private final FitnessRater fitnessRater;
public JenkinsSchedulerNew(String jenkinsMaster, MesosCloud mesosCloud) {
this(jenkinsMaster, mesosCloud, NodeAffineRaters.NODE_AFFINE_CPU_MEM_SPREAD);
}
public JenkinsSchedulerNew(String jenkinsMaster, MesosCloud mesosCloud, FitnessRater fitnessRater) {
super(jenkinsMaster, mesosCloud, NAME);
// TODO: configurable fitness rater (on request with mapping like "FrameworkToItem"?)
this.fitnessRater = fitnessRater;
}
@Override
protected void resourceOffersImpl(SchedulerDriver driver, List<Protos.Offer> offers) {
List<Protos.Offer> offersToDecline;
double declineOfferDuration = 1;
// drain/move requests to a separate list, so that we try not to be greedy
List<Request> currentRequests = drainRequests();
if (!currentRequests.isEmpty()) {
// create leases list from offers
List<Lease> leases = createLeases(offers);
// try to assign requests
List<Request> unassignedRequests = assignRequests(currentRequests, leases);
// add still unassigned requests back to requests (finally block?)
enqueueRequests(unassignedRequests);
offersToDecline = launchAssignments(driver, leases);
} else {
// Decline offer for a longer period if no slave is waiting to get spawned.
// This prevents unnecessarily getting offers every few seconds and causing
// starvation when running a lot of frameworks.
declineOfferDuration = getNoRequestsDeclineOfferDuration();
LOGGER.info("No requests in queue, framework '" + getMesosCloud().getFrameworkName() + "' rejects offers for " + declineOfferDuration + "s");
offersToDecline = offers;
}
declineOffers(driver, offersToDecline, Protos.Filters.newBuilder().setRefuseSeconds(declineOfferDuration).build());
}
private List<Protos.Offer> launchAssignments(SchedulerDriver driver, List<Lease> leases) {
// launch tasks / decline other offers/leases
// TODO: what if launchMesosTask/declineOffer goes awry? -> add requests of unhandled leases back to requests as well
List<Protos.Offer> offersToDecline = new ArrayList<>();
for (Lease lease : leases) {
try {
if (lease.hasAssignments()) {
// launch tasks
launchMesosTasks(driver, lease);
} else {
// decline leases with no assignments
offersToDecline.addAll(lease.getOffers());
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unable to launch tasks for lease '" + lease + "':", e);
offersToDecline.addAll(lease.getOffers());
}
}
return offersToDecline;
}
private boolean assignToFittestLease(Request request, List<Lease> leases) {
// find fittest lease/offer
// (this part could be multi-threaded)
Lease fittestLease = findFittestLease(request, leases);
// assign request to fittest lease/offer ("create task")
return fittestLease != null && fittestLease.assign(request, new TaskCreator(request, fittestLease, this).createTask());
}
private List<Request> assignRequests(@Nonnull List<Request> currentRequests, @Nonnull List<Lease> leases) {
List<Request> unassignedRequests = new ArrayList<>();
// try to assign requests to a lease
for (Request request : currentRequests) {
try {
if (!(isExistingRequest(request, leases) || assignToFittestLease(request, leases))) {
unassignedRequests.add(request);
}
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unable to assign request '" + request + "' to a lease:", e);
unassignedRequests.add(request);
}
}
return unassignedRequests;
}
private boolean isRequestAlreadyAssigned(String agentName, List<Lease> leases) {
for (Lease lease : leases) {
for (Request existingRequest : lease.getAssignedRequests()) {
String existingAgentName = existingRequest.getRequest().getSlave().getName();
if (StringUtils.equals(agentName, existingAgentName)) {
return true;
}
}
}
return false;
}
private boolean isExistingRequest(Request request, List<Lease> leases) {
// dont test fitness if first part of createMesos applies:
// * is existing task
// * is existing jenkins agent
// (task for request already exists, or jenkins agent already created for it)
// in this case simply remove request from currentRequests and ignore (log it though)
String agentName = request.getRequest().getSlave().getName();
return isRequestAlreadyAssigned(agentName, leases) || isExistingTaskOrAgent(agentName);
}
private void declineOffers(SchedulerDriver driver, List<Protos.Offer> offers, Protos.Filters filters) {
// lock object to not allow a driver.revive() (revive should wait until all offers declined)
for (Protos.Offer offer : offers) {
try {
declineOffer(driver, offer, filters);
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Unable to decline offer '" + offer + "':", e);
}
}
// unlock object
}
private List<Lease> createLeases(List<Protos.Offer> offers) {
List<Lease> leases = new ArrayList<>(offers.size());
for (Protos.Offer offer : offers) {
leases.add(new Lease(offer));
}
return leases;
}
private Lease findFittestLease(Request request, List<Lease> leases) {
Lease fittestLease = null;
double fittestRating = FitnessRater.NOT_FIT;
for (Lease lease : leases) {
double currentRating = fitnessRater.rateFitness(request, lease);
if (currentRating > fittestRating) {
fittestLease = lease;
fittestRating = currentRating;
}
}
return fittestLease;
}
private void launchMesosTasks(SchedulerDriver driver, Lease lease) {
launchMesosTasks(driver, lease.getOfferIds(), lease.getAssignments(), lease.getHostname());
}
}
| {
"content_hash": "0dd2c1020abead95e9b27a676196ef27",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 153,
"avg_line_length": 39.07027027027027,
"alnum_prop": 0.6438848920863309,
"repo_name": "goettl79/mesos-plugin",
"id": "6db6b1f3bf0aa566a147dd1f5c26322ee2c31802",
"size": "7228",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/jenkinsci/plugins/mesos/JenkinsSchedulerNew.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "915"
},
{
"name": "HTML",
"bytes": "4787"
},
{
"name": "Java",
"bytes": "202811"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class WindowDecoder
| Pleosoft.XdeltaSharp - VCDIFF for .NET </title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class WindowDecoder
| Pleosoft.XdeltaSharp - VCDIFF for .NET ">
<meta name="generator" content="docfx 2.58.9.0">
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="../styles/docfx.vendor.css">
<link rel="stylesheet" href="../styles/docfx.css">
<link rel="stylesheet" href="../styles/main.css">
<meta property="docfx:navrel" content="../toc.html">
<meta property="docfx:tocrel" content="../dev/toc.html">
<meta property="docfx:rel" content="../">
<meta property="docfx:newtab" content="true">
</head>
<body data-spy="scroll" data-target="#affix" data-offset="120">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">
<img id="logo" class="svg" src="../logo.svg" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
<ul class="nav level1 navbar-nav">
<li>
<a href="../index.html" title="Home">Home</a>
</li>
<li>
<a href="../guides/Contributing.html" title="Guides">Guides</a>
</li>
<li>
<a href="../dev/Changelog.html" title="API">API</a>
</li>
<li>
<a href="https://github.com/pleonex/xdelta-sharp" title="GitHub">GitHub</a>
</li>
</ul> </div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div class="container body-content">
<div id="search-results">
<div class="search-list">Search Results for <span></span></div>
<div class="sr-items">
<p><i class="glyphicon glyphicon-refresh index-loading"></i></p>
</div>
<ul id="pagination" data-first="First" data-prev="Previous" data-next="Next" data-last="Last"></ul>
</div>
</div>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div>
<div class="sidefilter">
<form class="toc-filter">
<span class="glyphicon glyphicon-filter filter-icon"></span>
<input type="text" id="toc_filter_input" placeholder="Enter here to filter..." onkeypress="if(event.keyCode==13) {return false;}">
</form>
</div>
<div class="sidetoc">
<div class="toc" id="toc">
<ul class="nav level1">
<li class="">
<a href="../dev/Changelog.html" title="Changelog" class="">Changelog</a>
</li>
<li class="">
<span class="expand-stub"></span>
<a class="">API</a>
<ul class="nav level2">
<li class="">
<span class="expand-stub"></span>
<a href="../dev/../api/Pleosoft.XdeltaSharp.html" title="Pleosoft.XdeltaSharp" class="">Pleosoft.XdeltaSharp</a>
<ul class="nav level3">
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.AddressMode.html" title="AddressMode" class="">AddressMode</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Adler32.html" title="Adler32" class="">Adler32</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Cache.html" title="Cache" class="">Cache</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.CodeTable.html" title="CodeTable" class="">CodeTable</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.FinishedHandler.html" title="FinishedHandler" class="">FinishedHandler</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.ProgressChangedHandler.html" title="ProgressChangedHandler" class="">ProgressChangedHandler</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.VcdReader.html" title="VcdReader" class="">VcdReader</a>
</li>
</ul> </li>
<li class="">
<span class="expand-stub"></span>
<a href="../dev/../api/Pleosoft.XdeltaSharp.Decoder.html" title="Pleosoft.XdeltaSharp.Decoder" class="">Pleosoft.XdeltaSharp.Decoder</a>
<ul class="nav level3">
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Decoder.Decoder.html" title="Decoder" class="">Decoder</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Decoder.WindowDecoder.html" title="WindowDecoder" class="">WindowDecoder</a>
</li>
</ul> </li>
<li class="">
<span class="expand-stub"></span>
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.html" title="Pleosoft.XdeltaSharp.Vcdiff" class="">Pleosoft.XdeltaSharp.Vcdiff</a>
<ul class="nav level3">
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Header.html" title="Header" class="">Header</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.SecondaryCompressor.html" title="SecondaryCompressor" class="">SecondaryCompressor</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Window.html" title="Window" class="">Window</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.WindowCompressedFields.html" title="WindowCompressedFields" class="">WindowCompressedFields</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.WindowFields.html" title="WindowFields" class="">WindowFields</a>
</li>
</ul> </li>
<li class="">
<span class="expand-stub"></span>
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.html" title="Pleosoft.XdeltaSharp.Vcdiff.Instructions" class="">Pleosoft.XdeltaSharp.Vcdiff.Instructions</a>
<ul class="nav level3">
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.Add.html" title="Add" class="">Add</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.Copy.html" title="Copy" class="">Copy</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.Instruction.html" title="Instruction" class="">Instruction</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.InstructionType.html" title="InstructionType" class="">InstructionType</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.Noop.html" title="Noop" class="">Noop</a>
</li>
<li class="">
<a href="../dev/../api/Pleosoft.XdeltaSharp.Vcdiff.Instructions.Run.html" title="Run" class="">Run</a>
</li>
</ul> </li>
</ul> </li>
</ul> </div>
</div>
</div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder">
<h1 id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder" class="text-break">Class WindowDecoder
</h1>
<div class="markdown level0 summary"></div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.object">Object</a></div>
<div class="level1"><span class="xref">WindowDecoder</span></div>
</div>
<h6><strong>Namespace</strong>: <a class="xref" href="Pleosoft.XdeltaSharp.Decoder.html">Pleosoft.XdeltaSharp.Decoder</a></h6>
<h6><strong>Assembly</strong>: Pleosoft.XdeltaSharp.dll</h6>
<h5 id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder_syntax">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public class WindowDecoder</code></pre>
</div>
<h3 id="constructors">Constructors
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https://github.com/pleonex/xdelta-csharp/new/main/docs/apidoc/new?filename=Pleosoft_XdeltaSharp_Decoder_WindowDecoder__ctor_System_IO_Stream_System_IO_Stream_.md&value=---%0Auid%3A%20Pleosoft.XdeltaSharp.Decoder.WindowDecoder.%23ctor(System.IO.Stream%2CSystem.IO.Stream)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a>
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/pleonex/xdelta-sharp/blob/main/src/Pleosoft.XdeltaSharp/Decoder/WindowDecoder.cs/#L33">View Source</a>
</span>
<a id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder__ctor_" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder.#ctor*"></a>
<h4 id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder__ctor_System_IO_Stream_System_IO_Stream_" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder.#ctor(System.IO.Stream,System.IO.Stream)">WindowDecoder(Stream, Stream)</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public WindowDecoder(Stream input, Stream output)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.io.stream">Stream</a></td>
<td><span class="parametername">input</span></td>
<td></td>
</tr>
<tr>
<td><a class="xref" href="https://docs.microsoft.com/dotnet/api/system.io.stream">Stream</a></td>
<td><span class="parametername">output</span></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="methods">Methods
</h3>
<span class="small pull-right mobile-hide">
<span class="divider">|</span>
<a href="https://github.com/pleonex/xdelta-csharp/new/main/docs/apidoc/new?filename=Pleosoft_XdeltaSharp_Decoder_WindowDecoder_Decode_Pleosoft_XdeltaSharp_Vcdiff_Window_.md&value=---%0Auid%3A%20Pleosoft.XdeltaSharp.Decoder.WindowDecoder.Decode(Pleosoft.XdeltaSharp.Vcdiff.Window)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc</a>
</span>
<span class="small pull-right mobile-hide">
<a href="https://github.com/pleonex/xdelta-sharp/blob/main/src/Pleosoft.XdeltaSharp/Decoder/WindowDecoder.cs/#L40">View Source</a>
</span>
<a id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder_Decode_" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder.Decode*"></a>
<h4 id="Pleosoft_XdeltaSharp_Decoder_WindowDecoder_Decode_Pleosoft_XdeltaSharp_Vcdiff_Window_" data-uid="Pleosoft.XdeltaSharp.Decoder.WindowDecoder.Decode(Pleosoft.XdeltaSharp.Vcdiff.Window)">Decode(Window)</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public void Decode(Window window)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="xref" href="Pleosoft.XdeltaSharp.Vcdiff.Window.html">Window</a></td>
<td><span class="parametername">window</span></td>
<td></td>
</tr>
</tbody>
</table>
</article>
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<div class="contribution">
<ul class="nav">
<li>
<a href="https://github.com/pleonex/xdelta-csharp/new/main/docs/apidoc/new?filename=Pleosoft_XdeltaSharp_Decoder_WindowDecoder.md&value=---%0Auid%3A%20Pleosoft.XdeltaSharp.Decoder.WindowDecoder%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A" class="contribution-link">Improve this Doc</a>
</li>
<li>
<a href="https://github.com/pleonex/xdelta-sharp/blob/main/src/Pleosoft.XdeltaSharp/Decoder/WindowDecoder.cs/#L27" class="contribution-link">View Source</a>
</li>
</ul>
</div>
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
<h5>In This Article</h5>
<div></div>
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
Copyright (c) 2015 Benito Palacios Sánchez
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../styles/docfx.js"></script>
<script type="text/javascript" src="../styles/main.js"></script>
</body>
</html>
| {
"content_hash": "366ac03491607a181500feb57535f747",
"timestamp": "",
"source": "github",
"line_count": 333,
"max_line_length": 499,
"avg_line_length": 54.771771771771775,
"alnum_prop": 0.510718789407314,
"repo_name": "pleonex/xdelta-sharp",
"id": "c2153d0d04b3700a867a33872aaa256f2320622d",
"size": "18242",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "api/Pleosoft.XdeltaSharp.Decoder.WindowDecoder.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "87253"
}
],
"symlink_target": ""
} |
let checkResult = null
function checkForUpdates () {
const npmLatest = require('npm-latest')
const packageJson = require('../package.json')
const colors = require('colors')
const semver = require('semver')
npmLatest('how2', { timeout: 1500 }, (err, npm) => {
if (err) {
console.error(err)
return
}
if (semver.gt(npm.version, packageJson.version)) {
checkResult = colors.yellow(
`\nA new version of how2 is available: ${npm.version}\n` +
`Run ${colors.blue('npm update -g how2')} to update.\n`
)
}
})
}
function getResult () {
return checkResult
}
module.exports = {
checkForUpdates,
getResult
}
| {
"content_hash": "fbbc113d35f8a5cdeb839bf899a7e08f",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 71,
"avg_line_length": 22.7,
"alnum_prop": 0.6123348017621145,
"repo_name": "santinic/how2",
"id": "b85c786d5199995635dfb300d06f914df071cf83",
"size": "681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/updates.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "172"
},
{
"name": "JavaScript",
"bytes": "31445"
},
{
"name": "Shell",
"bytes": "1192"
}
],
"symlink_target": ""
} |
#include "stdafx.h"
#include "../PriorityTape.h"
#include "../PriorityTapeGroup.h"
#include "PriorityTapeTask.h"
#include "PriorityTapeGroupTest.h"
CPPUNIT_TEST_SUITE_REGISTRATION( PriorityTapeGroupTest );
void
PriorityTapeGroupTest::setUp()
{
}
void
PriorityTapeGroupTest::tearDown()
{
}
void
PriorityTapeGroupTest::testSchedule()
{
auto_ptr<PriorityTape> priority0(new PriorityTape());
auto_ptr<PriorityTape> priority1(new PriorityTape());
auto_ptr<PriorityTape> priority2(new PriorityTape());
auto_ptr<PriorityTape> priority3(new PriorityTape());
PriorityTapeTask task0(priority0.get(),10,0,1);
PriorityTapeTask task1(priority1.get(),10,0,1);
PriorityTapeTask task2(priority2.get(),10,0,1);
PriorityTapeTask task3(priority3.get(),10,0,1);
vector<string> tapes;
tapes.push_back("01000001");
tapes.push_back("01000002");
tapes.push_back("02000001");
tapes.push_back("02000002");
vector<PriorityTape *> priorities;
priorities.push_back(priority0.get());
priorities.push_back(priority1.get());
priorities.push_back(priority2.get());
priorities.push_back(priority3.get());
auto_ptr<PriorityTapeGroup> group(new PriorityTapeGroup(tapes,priorities));
task0.Start();
task1.Start();
task2.Start();
task3.Start();
boost::this_thread::sleep(
boost::posix_time::milliseconds(10) );
CPPUNIT_ASSERT( false == task0.Finished() );
CPPUNIT_ASSERT( false == task1.Finished() );
CPPUNIT_ASSERT( false == task2.Finished() );
CPPUNIT_ASSERT( false == task3.Finished() );
group->Enable(true);
task0.Start();
task1.Start();
task2.Start();
task3.Start();
boost::this_thread::sleep(
boost::posix_time::milliseconds(10) );
CPPUNIT_ASSERT( true == task0.Finished() );
CPPUNIT_ASSERT( true == task1.Finished() );
CPPUNIT_ASSERT( true == task2.Finished() );
CPPUNIT_ASSERT( true == task3.Finished() );
group->Enable(false);
task0.Start();
task1.Start();
task2.Start();
task3.Start();
boost::this_thread::sleep(
boost::posix_time::milliseconds(10) );
CPPUNIT_ASSERT( false == task0.Finished() );
CPPUNIT_ASSERT( false == task1.Finished() );
CPPUNIT_ASSERT( false == task2.Finished() );
CPPUNIT_ASSERT( false == task3.Finished() );
boost::posix_time::ptime begin =
boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( false == group->Request(false,10,0) );
boost::posix_time::ptime end =
boost::posix_time::microsec_clock::local_time();
int duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );
group->Enable(true);
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( false == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
duration >= 10 && duration <= 12 );
CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );
group->Release(false);
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
group->Release(false);
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(true,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(true,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( false == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT_MESSAGE( boost::lexical_cast<string>(duration),
duration >= 10 && duration <= 12 );
CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );
group->Release(true);
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( false == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration >= 10 && duration <= 12 );
group->Release(false);
begin = boost::posix_time::microsec_clock::local_time();
CPPUNIT_ASSERT( true == group->Request(false,10,0) );
end = boost::posix_time::microsec_clock::local_time();
duration = (end - begin).total_milliseconds();
CPPUNIT_ASSERT( duration <= 5 );
group->Release(true);
group->Release(false);
}
| {
"content_hash": "1be1778d3b3edaab0ea58bc5333e199e",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 79,
"avg_line_length": 32.04571428571428,
"alnum_prop": 0.6453281027104137,
"repo_name": "BDT-GER/SWIFT-TLC",
"id": "34335e588aa0573c149354edcc7d8fc30271f0bc",
"size": "6299",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Server/tlc-server/bdt/test/PriorityTapeGroupTest.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "882540"
},
{
"name": "C++",
"bytes": "2360724"
},
{
"name": "Makefile",
"bytes": "20290"
},
{
"name": "Python",
"bytes": "16625"
},
{
"name": "Shell",
"bytes": "124275"
}
],
"symlink_target": ""
} |
#if!defined __PRODUCERINVOKECALLBACK_H__
#define __PRODUCERINVOKECALLBACK_H__
#include "InvokeCallback.h"
class SendCallback;
/**
* Òì²½µ÷ÓÃÓ¦´ð»Øµ÷½Ó¿Ú
*
*/
class ProducerInvokeCallback : public InvokeCallback
{
public:
ProducerInvokeCallback(SendCallback* pSendCallBack);
virtual ~ProducerInvokeCallback();
virtual void operationComplete(ResponseFuture* pResponseFuture);
private:
SendCallback* m_pSendCallBack;
};
#endif
| {
"content_hash": "c2d22411b538824be1b1a26c5825e1bf",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 65,
"avg_line_length": 18.083333333333332,
"alnum_prop": 0.7788018433179723,
"repo_name": "mashibing/rocketmq-client4cpp",
"id": "d81b5552c7beff5f2a937bd232a4f742eb713a8b",
"size": "1036",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/producer/ProducerInvokeCallback.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "110484"
},
{
"name": "C++",
"bytes": "829080"
},
{
"name": "HTML",
"bytes": "1137"
},
{
"name": "Makefile",
"bytes": "2634"
},
{
"name": "Python",
"bytes": "65959"
},
{
"name": "Shell",
"bytes": "1144"
}
],
"symlink_target": ""
} |
CREATE OR REPLACE FUNCTION create_entity(identifier TEXT, doc json)
RETURNS json
AS
$$
BEGIN
return doc;
END;
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION update_entity(identifier TEXT, doc json)
RETURNS json
AS
$$
BEGIN
return doc;
END;
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION query_entity(identifier TEXT, doc json)
RETURNS json
AS
$$
BEGIN
return doc;
END;
$$
LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION remove_entity(identifier TEXT, doc json)
RETURNS json
AS
$$
BEGIN
return doc;
END;
$$
LANGUAGE plpgsql; | {
"content_hash": "21faaca14d95d03f45a4069dcbb6cda3",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 67,
"avg_line_length": 13.25,
"alnum_prop": 0.7603773584905661,
"repo_name": "letsface/pgspjs",
"id": "1e0007c8c809f80eebe32e800613e0d80abddf7e",
"size": "530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/multi-transaction.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "20916"
}
],
"symlink_target": ""
} |
<?php
namespace Vinala\Kernel\Filesystem\Exception;
/**
* File not fount exception.
*/
class FileNotFoundException extends \Exception
{
protected $message; // exception message
public function __construct($path)
{
$this->message = "File does not existe in ($path)";
}
}
| {
"content_hash": "7855bf807299defe17912cafec83de83",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 59,
"avg_line_length": 18.8125,
"alnum_prop": 0.6611295681063123,
"repo_name": "vinala/kernel",
"id": "f99bc56e7b37d0deda5a963f797c717b933aad19",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Filesystem/Exceptions/FileNotFoundException.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "657682"
}
],
"symlink_target": ""
} |
<?php declare(strict_types=1);
namespace e2e;
use Deployer\Exception\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
abstract class AbstractE2ETest extends TestCase
{
/** @var ConsoleApplicationTester */
protected $tester;
public function setUp(): void
{
$this->tester = new ConsoleApplicationTester(__DIR__ . '/../../bin/dep', __DIR__);
}
}
| {
"content_hash": "eb6ed8b819cd46aa845b692c20c1f889",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 90,
"avg_line_length": 24.176470588235293,
"alnum_prop": 0.6909975669099757,
"repo_name": "deployphp/deployer",
"id": "a1390da9983b54a79e62a68d11e589c0e9d1a964",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/e2e/AbstractE2ETest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "3140"
},
{
"name": "HTML",
"bytes": "58"
},
{
"name": "PHP",
"bytes": "573036"
},
{
"name": "Shell",
"bytes": "966"
}
],
"symlink_target": ""
} |
[![Standard Code Style][std_img]][std_site]
> A fast & lightweight responsive touch-friendly react slider component with sections.
<img src="./demo/slider.png" alt="Slider" />
Check out [project page](https://exelnait.github.io/react-range-slider/) and [demo](https://exelnait.github.io/react-range-slider/demo/index.html)
## Example
```js
import React, { PureComponent } from 'react'
import Slider from 'react-range-slider'
class PriceCountSlider extends PureComponent {
constructor(props, context) {
super(props, context)
this.state = {
count: 0
}
}
handleOnChange = (value) => {
this.setState({
count: value
})
}
render() {
return (
<Slider
range={[50, 100, 200, 400, 800]}
onChange={this.handleOnChange}
/>
)
}
}
```
## API
Range slider is bundled as a single component, that accepts data and callbacks only as `props`.
### Props
Prop | Type | Required | Description
--------- | ------- | ------- | -----------
`range` | array | true | array with ascending numbers. `[50, 100, 200, 400, 800]`
`onChange` | function | | function gets called whenever the slider handle is being dragged or clicked
## Development
To work on the project locally, you need to pull its dependencies and run `npm start`.
```bash
$ npm install
$ npm start
```
To start tests you need to run `npm test`.
To check linting you need to run `npm run lint`.
## Issues
Feel free to contribute. Submit a Pull Request or open an issue for further discussion.
## License
Licensed under MIT License. Copyright © 2017 Timofey Lavrenyuk
See [LICENSE](./LICENSE) for more information.
[std_img]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
[std_site]: http://standardjs.com | {
"content_hash": "09cb11ce3b56249705d396f0e76d7129",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 146,
"avg_line_length": 26.985294117647058,
"alnum_prop": 0.6446866485013624,
"repo_name": "exelnait/react-range-slider",
"id": "79f41bb0cb8ceae8637130fd449b3506a957012a",
"size": "1871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1891"
},
{
"name": "JavaScript",
"bytes": "8822"
}
],
"symlink_target": ""
} |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
namespace MonoMac.CoreGraphics {
public partial class CGDataConsumer : INativeObject, IDisposable {
internal IntPtr handle;
IntPtr buffer;
byte [] reference;
// invoked by marshallers
public CGDataConsumer (IntPtr handle)
: this (handle, false)
{
this.handle = handle;
}
[Preserve (Conditional=true)]
internal CGDataConsumer (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CGDataConsumerRetain (handle);
}
~CGDataConsumer ()
{
Dispose (false);
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public IntPtr Handle {
get { return handle; }
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGDataConsumerRelease (IntPtr handle);
[DllImport (Constants.CoreGraphicsLibrary)]
extern static void CGDataConsumerRetain (IntPtr handle);
protected virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
if (buffer != IntPtr.Zero)
Marshal.FreeHGlobal (buffer);
buffer = IntPtr.Zero;
CGDataConsumerRelease (handle);
handle = IntPtr.Zero;
}
reference = null;
}
[DllImport (Constants.CoreGraphicsLibrary)]
extern static IntPtr CGDataConsumerCreateWithCFData (IntPtr data);
public CGDataConsumer(NSMutableData data){
handle = CGDataConsumerCreateWithCFData(data.Handle);
}
}
}
| {
"content_hash": "e0f89af6c5be9301450881b4c7aab2a0",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 68,
"avg_line_length": 21.183098591549296,
"alnum_prop": 0.7061170212765957,
"repo_name": "mono/maccore",
"id": "79417402c9a0b5ee72bc68d46bd8bfece42c3f7b",
"size": "2756",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CoreGraphics/CGDataConsumer.cs",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "2491812"
}
],
"symlink_target": ""
} |
{-# LANGUAGE OverloadedStrings #-}
module Snap.Utilities.Configuration.Extract (
extractGroups,
withValidGroup
) where
import Prelude hiding (lookup)
import Control.Applicative
import qualified Data.Configurator as C
import qualified Data.Configurator.Types as CT
import Data.List (groupBy, intercalate, find, sortBy, lookup)
import Data.HashMap.Strict (toList)
import Data.Text (Text, isPrefixOf, splitOn, pack, unpack)
import Snap.Utilities.Configuration.Lookup
import Snap.Utilities.Configuration.Types
import Snap.Utilities.Configuration.Keys
------------------------------------------------------------------------------
extractGroups :: (ConfigPair -> Bool) -> CT.Config -> IO [[ConfigPair]]
extractGroups validator cfg = (groupBy authGroups . sortBy sortGroups . filter validator . toList) <$> C.getMap cfg
where
authGroups (k1, _) (k2, _) = (keyPre k1) == (keyPre k2)
sortGroups (k1, _) (k2, _) = (keyPre k1) `compare` (keyPre k2)
withValidGroup :: String -> (String -> String -> [ConfigPair] -> a) -> [ConfigPair] -> a
withValidGroup groupKey transformer cfg =
case fmap stringValue $ lookup (pack groupKey) cfg' of
Just a -> transformer gn a cfg'
_ -> error ("Not a valid " ++ groupKey ++ " in " ++ gn)
where
cfg' = map rebaseKey cfg
gn = groupName cfg
| {
"content_hash": "3e254176887bccd104ff0d4ac1fd5d7a",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 115,
"avg_line_length": 38.911764705882355,
"alnum_prop": 0.6628873771730914,
"repo_name": "anchor/snap-configuration-utilities",
"id": "52539c6283b1747d31fe78e92c23dc481ab63649",
"size": "1323",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/Snap/Utilities/Configuration/Extract.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Haskell",
"bytes": "4544"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.