text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello</string>
</resources> | {'content_hash': '6a3ff0e2fd80327063fec8d2b2287a06', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 39, 'avg_line_length': 25.75, 'alnum_prop': 0.6601941747572816, 'repo_name': 'FliesenUI/FliesenUI', 'id': '859932daa71052b448b615adbcf3481a28058fdf', 'size': '103', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/bright_side_it/fliesenui/res/data/strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '11958'}, {'name': 'HTML', 'bytes': '1518'}, {'name': 'Java', 'bytes': '1074585'}, {'name': 'JavaScript', 'bytes': '422164'}]} |
class InputParameter < ServiceParameter
end | {'content_hash': 'a0bf5534b95654f3e841514b175c0656', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 39, 'avg_line_length': 14.666666666666666, 'alnum_prop': 0.8636363636363636, 'repo_name': 'hpi-epic/repmine', 'id': '521b39914d873ecc7e157e01252f1df81221f1df', 'size': '44', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/services/input_parameter.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '13835'}, {'name': 'CoffeeScript', 'bytes': '105'}, {'name': 'HTML', 'bytes': '35194'}, {'name': 'JavaScript', 'bytes': '29605'}, {'name': 'Ruby', 'bytes': '284267'}, {'name': 'Web Ontology Language', 'bytes': '43430'}]} |
define(function (require, exports, module) {
/**
* 文件上传,HTML5 ONLY
*
* @module Upload
*/
'use strict';
var Widget = require('widget');
var File = require('./file');
/**
* Queue
*
* @class Queue
* @constructor
*/
var Queue = Widget.extend({
type: 'Queue',
defaults: {
classPrefix: 'queue'
},
setup: function () {
this.render();
this.queueFiles = [];
},
append: function (file) {
this.queueFiles.push(initFile(file, this));
/**
* 通知队列文件插入
*
* @event queue
* @param {Object} e Event.
*/
this.fire('queue');
},
remove: function (queueFile) {
var index;
if (!this.queueFiles) {
return;
}
if ((index = this.queueFiles.indexOf(queueFile)) !== -1) {
this.queueFiles.splice(index, 1);
// queueFile.destroy();
// this.fire('dequeue');
/**
* 通知队列文件清空
*
* @event empty
* @param {Object} e Event.
*/
this.queueFiles.length || this.fire('empty');
}
},
empty: function (queueFile) {
this.queueFiles.forEach(function (queueFile) {
queueFile.destroy();
});
this.queueFiles = [];
this.fire('empty');
},
submit: function () {
// 等待上传
this.getQueuedFiles().forEach(function (queueFile) {
queueFile.submit();
});
// 上传失败,重新上传
this.getErrorFiles().forEach(function (queueFile) {
queueFile.submit();
});
},
getFiles: function (filter) {
return filter ? this.queueFiles.filter(filter) : this.queueFiles;
},
getFilesByState: function (state) {
return this.getFiles(function (queueFile) {
return queueFile.state() === state;
});
},
getQueuedFiles: function () {
return this.getFilesByState(File.QUEUED);
},
getProgressFiles: function () {
return this.getFilesByState(File.PROGRESS);
},
getCompleteFiles: function () {
return this.getFilesByState(File.COMPLETE);
},
getErrorFiles: function () {
return this.getFilesByState(File.ERROR);
}
});
function initFile (file, queue) {
return new File({
container: queue.element,
events: {
all: function () {
// 事件传递
queue.fire.apply(queue, arguments);
},
destroy: function () {
queue.remove(this);
}
},
file: file,
fileName: queue.option('fileName'),
url: queue.option('url')
});
}
module.exports = Queue;
});
| {'content_hash': 'dba42d952b99725582f65c62bf52366c', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 69, 'avg_line_length': 17.18439716312057, 'alnum_prop': 0.5720181593066447, 'repo_name': 'zb188/generator-java-webapp', 'id': '5e96a40536bccae5562b38601555f7e70aec0343', 'size': '2499', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/templates/fed/src/app/common/upload/base/queue.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '397973'}, {'name': 'JavaScript', 'bytes': '9852784'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffffff">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.9"
android:background="#000000"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.1"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/list"
android:divider="#ffffff"
android:layout_height="match_parent"
android:clipToPadding="false"
android:layout_alignParentBottom="true"
android:background="@color/colorPrimary"/>
</RelativeLayout>
</LinearLayout>
| {'content_hash': 'd100af2cc1c40dd169b93265248682e6', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 72, 'avg_line_length': 36.464285714285715, 'alnum_prop': 0.653281096963761, 'repo_name': '24ark/CategorizedGalleryView', 'id': '6799e48a7efa4e9874f14e78c4e46fbe03f77aeb', 'size': '1021', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/layout_horizontal.xml', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '29545'}]} |
package com.spotify.heroic.shell.task;
import com.spotify.heroic.common.OptionalLimit;
import com.spotify.heroic.dagger.CoreComponent;
import com.spotify.heroic.filter.Filter;
import com.spotify.heroic.grammar.QueryParser;
import com.spotify.heroic.metadata.FindTags;
import com.spotify.heroic.metadata.MetadataManager;
import com.spotify.heroic.shell.ShellIO;
import com.spotify.heroic.shell.ShellTask;
import com.spotify.heroic.shell.TaskName;
import com.spotify.heroic.shell.TaskParameters;
import com.spotify.heroic.shell.TaskUsage;
import com.spotify.heroic.shell.Tasks;
import dagger.Component;
import eu.toolchain.async.AsyncFuture;
import lombok.Getter;
import lombok.ToString;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@TaskUsage("Get tags")
@TaskName("metadata-tags")
public class MetadataTags implements ShellTask {
private final MetadataManager metadata;
private final QueryParser parser;
@Inject
public MetadataTags(MetadataManager metadata, QueryParser parser) {
this.metadata = metadata;
this.parser = parser;
}
@Override
public TaskParameters params() {
return new Parameters();
}
@Override
public AsyncFuture<Void> run(final ShellIO io, TaskParameters base) throws Exception {
final Parameters params = (Parameters) base;
final Filter filter = Tasks.setupFilter(parser, params);
return metadata
.useOptionalGroup(params.group)
.findTags(new FindTags.Request(filter, params.getRange(), params.getLimit()))
.directTransform(result -> {
io.out().println(result.toString());
return null;
});
}
@ToString
private static class Parameters extends Tasks.QueryParamsBase {
@Option(name = "-g", aliases = {"--group"}, usage = "Backend group to use",
metaVar = "<group>")
private Optional<String> group = Optional.empty();
@Option(name = "--limit", aliases = {"--limit"},
usage = "Limit the number of printed entries")
@Getter
private OptionalLimit limit = OptionalLimit.empty();
@Argument
@Getter
private List<String> query = new ArrayList<String>();
}
public static MetadataTags setup(final CoreComponent core) {
return DaggerMetadataTags_C.builder().coreComponent(core).build().task();
}
@Component(dependencies = CoreComponent.class)
interface C {
MetadataTags task();
}
}
| {'content_hash': '209f71e9739a17eff52c43f14b39d287', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 90, 'avg_line_length': 31.058823529411764, 'alnum_prop': 0.6935606060606061, 'repo_name': 'OdenTech/heroic', 'id': '9b10d723564d711c4d6642b9baea68cc1653a939', 'size': '3484', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'heroic-core/src/main/java/com/spotify/heroic/shell/task/MetadataTags.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '4574'}, {'name': 'Java', 'bytes': '3021407'}]} |
require 'rails_helper'
describe UsersController do
before do
@signature = 'Rails is so cool!'
end
it "displays user's personal homepage" do
create(:user, :nickname => 'devin')
get :show, :nickname => 'devin'
response.should be_success
end
it "should display user's all topics" do
create(:user, :nickname => 'devin')
get :topics, :nickname => 'devin'
should respond_with(:success)
end
context "authenticated user" do
login_user(:devin)
it "allows editing profile" do
get :edit
response.should be_success
end
it "allows update account without password" do
post :update_account, :user => {:account_attributes => {:signature => @signature}}
should respond_with(:redirect)
should set_flash
flash[:error].should be_nil
flash[:success].should_not be_nil
assigns(:user).account.signature.should == @signature
end
it "allows update password" do
post :update_password, :user => {:current_password => ENV['RABEL_TEST_DEFAULT_PASSWORD'], :password => 'foobar', :password_confirmation => 'foobar'}
should respond_with(:redirect)
flash[:error].should be_nil
flash[:success].should_not be_nil
end
it "can visit my bookmarked topics" do
get :my_topics
should respond_with(:success)
should_not set_flash
end
it "can visit my following page" do
get :my_following
should respond_with(:success)
end
it "should follow people" do
dhh = create(:user, :nickname => 'dhh')
post :follow, :nickname => 'dhh'
should respond_with(:redirect)
should_not set_flash
current_user = User.find_by_nickname(:devin)
expect(assigns(:followed_user).followed_by?(current_user)).to be true
end
it "should unfollow people" do
dhh = create(:user, :nickname => 'dhh')
devin = User.find_by_nickname(:devin)
devin.follow(dhh)
post :unfollow, :nickname => 'dhh'
should respond_with(:redirect)
should_not set_flash
expect(devin.following?(dhh)).to be false
end
end
context "anonymous user" do
it "redirect to sign in page when trying to edit profile" do
get :edit
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when trying to update account" do
post :update_account, :user => {:account =>{:signature => @signature}}
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when trying to update password" do
post :update_password
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when visiting my topics" do
get :my_topics
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when visiting my following page" do
get :my_following
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when following people" do
post :follow, :nickname => 'nana'
should respond_with(:redirect)
should set_flash
end
it "redirect to sign in page when unfollowing people" do
post :unfollow, :nickname => 'nana'
should respond_with(:redirect)
should set_flash
end
end
end
| {'content_hash': '2fd76564935ba3d3f7f1e0852af5f721', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 154, 'avg_line_length': 28.008403361344538, 'alnum_prop': 0.6435643564356436, 'repo_name': 'HuiGuoGuo/rable', 'id': '623efe897938db4e90e6954fdcee32f466475adf', 'size': '3333', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/controllers/users_controller_spec.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '3201'}, {'name': 'CoffeeScript', 'bytes': '2884'}, {'name': 'Cucumber', 'bytes': '23403'}, {'name': 'HTML', 'bytes': '78634'}, {'name': 'JavaScript', 'bytes': '434'}, {'name': 'Ruby', 'bytes': '221481'}, {'name': 'Shell', 'bytes': '5306'}]} |
export { default } from 'ilios-calendar/components/ilios-calendar-single-event-objective-list'; | {'content_hash': '14b0311da125aa415f21516a410fd0cc', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 95, 'avg_line_length': 95.0, 'alnum_prop': 0.8105263157894737, 'repo_name': 'ilios/calendar', 'id': '1daa05f28fef17f45e04710ed6c16f672c4f48e8', 'size': '95', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'app/components/ilios-calendar-single-event-objective-list.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6460'}, {'name': 'HTML', 'bytes': '16260'}, {'name': 'JavaScript', 'bytes': '53564'}]} |
cConfiguration = inherit(cSingleton)
--[[
]]
-- ///////////////////////////////
-- ///// checkFile //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:checkFile()
self.xml = xmlLoadFile(self.m_sFileName);
if not(self.xml) then
self.xml = xmlCreateFile(self.m_sFileName, "config");
if(self.m_bInsertJustOnNoneExists == true) then
for index, val in pairs(self.defaultValues2) do
self:setConfig(index, val)
end
if(self.xtraValues) then
for index, val in pairs(self.xtraValues) do
self:setConfig(index, val)
end
end
end
end
xmlSaveFile(self.xml);
end
-- ///////////////////////////////
-- ///// setConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:setConfig(sConfig, sValue)
if not(self.xml) then
outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
return false;
end
local node = xmlFindChild(self.xml, sConfig, 0);
if not(node) then
node = xmlCreateChild(self.xml, sConfig);
end
local sucess = xmlNodeSetValue(node, tostring(sValue));
xmlSaveFile(self.xml)
if(sucess) then
return sValue;
end
return false;
end
-- ///////////////////////////////
-- ///// getConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:getConfig(sConfig)
if not(self.xml) then
outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
return false;
end
local node = xmlFindChild(self.xml, sConfig, 0);
if not(node) then
node = xmlCreateChild(self.xml, sConfig);
end
local value = xmlNodeGetValue(node);
if not(value) or (string.len(value) < 1) then
if(self.defaultValues[sConfig]) then
value = self.defaultValues[sConfig];
self:setConfig(sConfig, value);
outputDebugString("[CONFIG] Config "..sConfig.." not found, using default ("..tostring(value)..")");
return value
else
return false;
end
else
return value
end
return false;
end
-- ///////////////////////////////
-- ///// removeConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:removeConfig(sConfig)
if not(self.xml) then
outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
return false;
end
local node = xmlFindChild(self.xml, sConfig, 0);
if(node) then
local sucess = xmlDestroyNode(node)
xmlSaveFile(self.xml)
return sucess
end
return false;
end
-- ///////////////////////////////
-- ///// getAllConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:getAllConfig()
if not(self.xml) then
outputChatBox("Fatal Error: Config File not Available!", 255, 0, 0)
return false;
end
local childs = xmlNodeGetChildren(self.xml);
local tbl = {}
for index, _ in ipairs(childs) do
tbl[xmlNodeGetName(childs[index])] = xmlNodeGetValue(childs[index])
end
return tbl
end
-- ///////////////////////////////
-- ///// loadCoreConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:loadCoreConfig()
-- FPS --
local fps = tonumber(self:getConfig("fps"));
setFPSLimit(fps);
-- CURSOR --
local cursor = self:getConfig("cursorbind");
local function bindDat(sKey)
bindKey(sKey, "both", function( key, state)
if not (cursorOverride) then
showCursor(state == "down")
end
end)
end
bindDat(cursor)
addCommandHandler("bindcursor", function(cmd, key) bindDat(key) end)
-- DEV MODE --
local devmode = toBoolean(self:getConfig("development"))
setDevelopmentMode(devmode)
-- HEAT HAZE --
local heatHaze = tonumber(self:getConfig("heathaze"));
if not(heatHaze) then
resetHeatHaze()
else
setHeatHaze(heatHaze)
end
-- INTERIOR SOUNDS --
local intSound = toBoolean(self:getConfig("interior_sounds"))
setInteriorSoundsEnabled(intSound);
-- Occlusions --
local occlusions = toBoolean(self:getConfig("occlusions"))
setOcclusionsEnabled(occlusions);
-- Moon size --
local moon_size = tonumber(self:getConfig("moon_size"))
if(moon_size) then
setMoonSize(moon_size)
end
-- Hotsound --
hitsoundEnabled = toBoolean(self:getConfig("hitsound_enabled"))
addCommandHandler("hitsound", function()
hitsoundEnabled = not(hitsoundEnabled)
if(hitsoundEnabled) then
outputChatBox("Der Hitsound wurde angeschaltet!", 0, 255, 0)
else
outputChatBox("Der Hitsound wurde ausgeschaltet!", 0, 255, 0)
end
self:setConfig("hitsound_enabled", tostring(hitsoundEnabled));
end)
addCommandHandler("changelog", function()
local file = File("res/txt/changelog.txt")
local content = file:read(file:getSize())
for index, row in ipairs(split(content, "\n")) do
outputConsole(row);
end
file:close()
end)
if(toboolean(self:getConfig("load_world_textures")) == false) then
local _engineApplyShaderToWorldTexture = engineApplyShaderToWorldTexture
function engineApplyShaderToWorldTexture(...)
return false
end
end
end
-- ///////////////////////////////
-- ///// loadBasicConfig //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:loadBasicConfig()
for config, default in pairs(self.defaultValues) do
local dat = self:getConfig(config);
setElementData(localPlayer, config, dat);
end
end
-- ///////////////////////////////
-- ///// loadCommands //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:loadCommands()
addCommandHandler("scrambleword", function(cmd, ...)
local s = scrambleWord((table.concat({...}, " ") or "hello"))
outputConsole("Wort: "..s)
setClipboard(s)
end)
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function cConfiguration:constructor(sFileName, sDefaultValues, insertOnNonExists)
-- Klassenvariablen --
self.defaultValues =
{
["fps"] = "60",
["cursorbind"] = "m",
["moon_size"] = "0",
["heathaze"] = "reset",
["interior_sounds"] = "true",
["occlusions"] = "false",
["development"] = "true",
["upload_blitzer_images"] = "true",
["log_console"] = "false",
["nametags_enabled"] = "true",
["hud_enabled"] = "true",
["render_infotext"] = "true",
["render_3dtext"] = "true",
["save_password"] = "false",
["saved_password"] = "-",
["hitsound_enabled"] = "false",
["ooc_chat"] = "true",
["popsound"] = "res/sounds/poke.ogg",
["hide_scoreboard_avatar"] = "false",
["lowrammode"] = "false",
["log_actions"] = "true",
["load_world_textures"] = "true",
["log_debug"] = "false",
}
if not(sFileName) then
sFileName = "config.xml";
end
if(sDefaultValues) then
self.defaultValues = {}
self.defaultValues2 = sDefaultValues;
end
self.m_sFileName = sFileName;
self.m_bInsertJustOnNoneExists = insertOnNonExists
-- Funktionen --
self:checkFile()
if(sFileName == "config.xml") then
self:loadCommands();
self:loadCoreConfig()
self:loadBasicConfig();
end
addEventHandler("onClientResourceStop", getResourceRootElement(getThisResource()), function()
if(self.xml) then
xmlSaveFile(self.xml)
xmlUnloadFile(self.xml)
end
end)
-- Events --
end
-- EVENT HANDLER --
| {'content_hash': '358c4fa172504d8224a555f3da4f7526', 'timestamp': '', 'source': 'github', 'line_count': 312, 'max_line_length': 112, 'avg_line_length': 27.266025641025642, 'alnum_prop': 0.5208651698601152, 'repo_name': 'ReWrite94/iLife', 'id': 'ce1844b68b492b0b56834be3ca09f0ec996d71aa', 'size': '8661', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'client/Classes/util/cConfiguration.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '3154502'}]} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Windows.Media;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename.HighlightTags
{
[Export(typeof(EditorFormatDefinition))]
[Name(RenameFixupTag.TagId)]
[UserVisible(true)]
[ExcludeFromCodeCoverage]
internal class RenameFixupTagDefinition : MarkerFormatDefinition
{
public static double StrokeThickness => 1.0;
public static double[] StrokeDashArray => new[] { 4.0, 4.0 };
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameFixupTagDefinition()
{
this.Border = new Pen(Brushes.Green, thickness: StrokeThickness) { DashStyle = new DashStyle(StrokeDashArray, 0) };
this.DisplayName = EditorFeaturesResources.Inline_Rename_Fixup;
this.ZOrder = 1;
}
}
}
| {'content_hash': 'd56be59b1aaa5a909afc0f24bb97f350', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 127, 'avg_line_length': 37.2, 'alnum_prop': 0.7334869431643625, 'repo_name': 'tannergooding/roslyn', 'id': 'db234acd1765819d4ffa5680ae75903c01a19930', 'size': '1304', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/EditorFeatures/Core.Wpf/InlineRename/HighlightTags/RenameFixupTagDefinition.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '8757'}, {'name': 'C#', 'bytes': '125455772'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'CMake', 'bytes': '7955'}, {'name': 'Dockerfile', 'bytes': '2450'}, {'name': 'F#', 'bytes': '508'}, {'name': 'PowerShell', 'bytes': '236398'}, {'name': 'Shell', 'bytes': '94036'}, {'name': 'Smalltalk', 'bytes': '622'}, {'name': 'Visual Basic .NET', 'bytes': '70352399'}]} |
package com.vanco.abplayer.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;
import android.text.TextPaint;
/**
* 字符串工具类
*
* @author tangjun
*
*/
public class StringUtils {
public static final String EMPTY = "";
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
/** 用于生成文件 */
private static final String DEFAULT_FILE_PATTERN = "yyyy-MM-dd-HH-mm-ss";
private static final double KB = 1024.0;
private static final double MB = 1048576.0;
private static final double GB = 1073741824.0;
public static final SimpleDateFormat DATE_FORMAT_PART = new SimpleDateFormat(
"HH:mm");
public static String currentTimeString() {
return DATE_FORMAT_PART.format(Calendar.getInstance().getTime());
}
public static char chatAt(String pinyin, int index) {
if (pinyin != null && pinyin.length() > 0)
return pinyin.charAt(index);
return ' ';
}
/** 获取字符串宽度 */
public static float GetTextWidth(String Sentence, float Size) {
if (isEmpty(Sentence))
return 0;
TextPaint FontPaint = new TextPaint();
FontPaint.setTextSize(Size);
return FontPaint.measureText(Sentence.trim()) + (int) (Size * 0.1); // 留点余地
}
/**
* 格式化日期字符串
*
* @param date
* @param pattern
* @return
*/
public static String formatDate(Date date, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
/**
* 格式化日期字符串
*
* @param date
* @return 例如2011-3-24
*/
public static String formatDate(Date date) {
return formatDate(date, DEFAULT_DATE_PATTERN);
}
public static String formatDate(long date) {
return formatDate(new Date(date), DEFAULT_DATE_PATTERN);
}
/**
* 获取当前时间 格式为yyyy-MM-dd 例如2011-07-08
*
* @return
*/
public static String getDate() {
return formatDate(new Date(), DEFAULT_DATE_PATTERN);
}
/** 生成一个文件名,不含后缀 */
public static String createFileName() {
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_FILE_PATTERN);
return format.format(date);
}
/**
* 获取当前时间
*
* @return
*/
public static String getDateTime() {
return formatDate(new Date(), DEFAULT_DATETIME_PATTERN);
}
/**
* 格式化日期时间字符串
*
* @param date
* @return 例如2011-11-30 16:06:54
*/
public static String formatDateTime(Date date) {
return formatDate(date, DEFAULT_DATETIME_PATTERN);
}
public static String formatDateTime(long date) {
return formatDate(new Date(date), DEFAULT_DATETIME_PATTERN);
}
/**
* 格林威时间转换
*
* @param gmt
* @return
*/
public static String formatGMTDate(String gmt) {
TimeZone timeZoneLondon = TimeZone.getTimeZone(gmt);
return formatDate(Calendar.getInstance(timeZoneLondon)
.getTimeInMillis());
}
/**
* 拼接数组
*
* @param array
* @param separator
* @return
*/
public static String join(final ArrayList<String> array,
final String separator) {
StringBuffer result = new StringBuffer();
if (array != null && array.size() > 0) {
for (String str : array) {
result.append(str);
result.append(separator);
}
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
public static String join(final Iterator<String> iter,
final String separator) {
StringBuffer result = new StringBuffer();
if (iter != null) {
while (iter.hasNext()) {
String key = iter.next();
result.append(key);
result.append(separator);
}
if (result.length() > 0)
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
/**
*
* @param str
* @return
*/
public static String trim(String str) {
return str == null ? EMPTY : str.trim();
}
/**
* 转换时间显示
*
* @param time
* 毫秒
* @return
*/
public static String generateTime(long time) {
int totalSeconds = (int) (time / 1000);
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes,
seconds) : String.format("%02d:%02d", minutes, seconds);
}
/** 根据秒速获取时间格式 */
public static String gennerTime(int totalSeconds) {
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
return String.format("%02d:%02d", minutes, seconds);
}
/**
* 转换文件大小
*
* @param size
* @return
*/
public static String generateFileSize(long size) {
String fileSize;
if (size < KB)
fileSize = size + "B";
else if (size < MB)
fileSize = String.format("%.1f", size / KB) + "KB";
else if (size < GB)
fileSize = String.format("%.1f", size / MB) + "MB";
else
fileSize = String.format("%.1f", size / GB) + "GB";
return fileSize;
}
public static String getTimeDiff(long time) {
// Calendar cal = Calendar.getInstance();
long diff = 0;
// Date dnow = cal.getTime();
String str = "";
diff = System.currentTimeMillis() - time;
if (diff > 2592000000L) {// 30 * 24 * 60 * 60 * 1000=2592000000 毫秒
str = "1个月前";
} else if (diff > 1814400000) {// 21 * 24 * 60 * 60 * 1000=1814400000 毫秒
str = "3周前";
} else if (diff > 1209600000) {// 14 * 24 * 60 * 60 * 1000=1209600000 毫秒
str = "2周前";
} else if (diff > 604800000) {// 7 * 24 * 60 * 60 * 1000=604800000 毫秒
str = "1周前";
} else if (diff > 86400000) { // 24 * 60 * 60 * 1000=86400000 毫秒
// System.out.println("X天前");
str = (int) Math.floor(diff / 86400000f) + "天前";
} else if (diff > 18000000) {// 5 * 60 * 60 * 1000=18000000 毫秒
// System.out.println("X小时前");
str = (int) Math.floor(diff / 18000000f) + "小时前";
} else if (diff > 60000) {// 1 * 60 * 1000=60000 毫秒
// System.out.println("X分钟前");
str = (int) Math.floor(diff / 60000) + "分钟前";
} else {
str = (int) Math.floor(diff / 1000) + "秒前";
}
return str;
}
/**
* 截取字符串
*
* @param search
* 待搜索的字符串
* @param start
* 起始字符串 例如:<title>
* @param end
* 结束字符串 例如:</title>
* @param defaultValue
* @return
*/
public static String substring(String search, String start, String end,
String defaultValue) {
int start_len = start.length();
int start_pos = StringUtils.isEmpty(start) ? 0 : search.indexOf(start);
if (start_pos > -1) {
int end_pos = StringUtils.isEmpty(end) ? -1 : search.indexOf(end,
start_pos + start_len);
if (end_pos > -1)
return search.substring(start_pos + start.length(), end_pos);
else
return search.substring(start_pos + start.length());
}
return defaultValue;
}
/**
* 截取字符串
*
* @param search
* 待搜索的字符串
* @param start
* 起始字符串 例如:<title>
* @param end
* 结束字符串 例如:</title>
* @return
*/
public static String substring(String search, String start, String end) {
return substring(search, start, end, "");
}
/**
* 拼接字符串
*
* @param strs
* @return
*/
public static String concat(String... strs) {
StringBuffer result = new StringBuffer();
if (strs != null) {
for (String str : strs) {
if (str != null)
result.append(str);
}
}
return result.toString();
}
/** 获取中文字符个数 */
public static int getChineseCharCount(String str) {
String tempStr;
int count = 0;
for (int i = 0; i < str.length(); i++) {
tempStr = String.valueOf(str.charAt(i));
if (tempStr.getBytes().length == 3) {
count++;
}
}
return count;
}
/** 获取英文字符个数 */
public static int getEnglishCount(String str) {
String tempStr;
int count = 0;
for (int i = 0; i < str.length(); i++) {
tempStr = String.valueOf(str.charAt(i));
if (!(tempStr.getBytes().length == 3)) {
count++;
}
}
return count;
}
public static String encode(String url) {
try {
return URLEncoder.encode(url, "UTF-8");
} catch (UnsupportedEncodingException e) {
Logger.e(e);
}
return url;
}
}
| {'content_hash': 'afaf0d2ce9a1a1d87298c0c5a5fbb5a3', 'timestamp': '', 'source': 'github', 'line_count': 352, 'max_line_length': 78, 'avg_line_length': 23.34375, 'alnum_prop': 0.6313739807715711, 'repo_name': 'SteamedBunZL/PlayerTest', 'id': 'dc53855371593f49ac4d85f873c13a1119bf04b7', 'size': '8705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/vanco/abplayer/util/StringUtils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1828231'}]} |
package syscall
import "unsafe"
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getgroups(ngid int, gid *_Gid_t) (n int, err error) {
r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setgroups(ngid int, gid *_Gid_t) (err error) {
_, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(ngid), uintptr(unsafe.Pointer(gid)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) {
r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0)
wpid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) {
r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socket(domain int, typ int, proto int) (fd int, err error) {
r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) {
_, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) {
_, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Shutdown(s int, how int) (err error) {
_, _, e1 := Syscall(SYS_SHUTDOWN, uintptr(s), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) {
_, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) {
r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kevent(kq int, change unsafe.Pointer, nchange int, event unsafe.Pointer, nevent int, timeout *Timespec) (n int, err error) {
r0, _, e1 := Syscall6(SYS_KEVENT, uintptr(kq), uintptr(change), uintptr(nchange), uintptr(event), uintptr(nevent), uintptr(unsafe.Pointer(timeout)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func sysctl(mib []_C_int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
var _p0 unsafe.Pointer
if len(mib) > 0 {
_p0 = unsafe.Pointer(&mib[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall6(SYS___SYSCTL, uintptr(_p0), uintptr(len(mib)), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(oldlen)), uintptr(unsafe.Pointer(new)), uintptr(newlen))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func utimes(path string, timeval *[2]Timeval) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func futimes(fd int, timeval *[2]Timeval) (err error) {
_, _, e1 := Syscall(SYS_FUTIMES, uintptr(fd), uintptr(unsafe.Pointer(timeval)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func fcntl(fd int, cmd int, arg int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) {
_, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func pipe() (r int, w int, err error) {
r0, r1, e1 := RawSyscall(SYS_PIPE, 0, 0, 0)
r = int(r0)
w = int(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func kill(pid int, signum int, posix int) (err error) {
_, _, e1 := Syscall(SYS_KILL, uintptr(pid), uintptr(signum), uintptr(posix))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Access(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_ACCESS, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Adjtime(delta *Timeval, olddelta *Timeval) (err error) {
_, _, e1 := Syscall(SYS_ADJTIME, uintptr(unsafe.Pointer(delta)), uintptr(unsafe.Pointer(olddelta)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chflags(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHFLAGS, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chmod(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHMOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Chroot(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Close(fd int) (err error) {
_, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup(fd int) (nfd int, err error) {
r0, _, e1 := Syscall(SYS_DUP, uintptr(fd), 0, 0)
nfd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Dup2(from int, to int) (err error) {
_, _, e1 := Syscall(SYS_DUP2, uintptr(from), uintptr(to), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exchangedata(path1 string, path2 string, options int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path1)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(path2)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_EXCHANGEDATA, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(options))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Exit(code int) {
Syscall(SYS_EXIT, uintptr(code), 0, 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchdir(fd int) (err error) {
_, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchflags(fd int, flags int) (err error) {
_, _, e1 := Syscall(SYS_FCHFLAGS, uintptr(fd), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchmod(fd int, mode uint32) (err error) {
_, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fchown(fd int, uid int, gid int) (err error) {
_, _, e1 := Syscall(SYS_FCHOWN, uintptr(fd), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Flock(fd int, how int) (err error) {
_, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fpathconf(fd int, name int) (val int, err error) {
r0, _, e1 := Syscall(SYS_FPATHCONF, uintptr(fd), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstat(fd int, stat *Stat_t) (err error) {
_, _, e1 := Syscall(SYS_FSTAT64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fstatfs(fd int, stat *Statfs_t) (err error) {
_, _, e1 := Syscall(SYS_FSTATFS64, uintptr(fd), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Fsync(fd int) (err error) {
_, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Ftruncate(fd int, length int64) (err error) {
_, _, e1 := Syscall(SYS_FTRUNCATE, uintptr(fd), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) {
var _p0 unsafe.Pointer
if len(buf) > 0 {
_p0 = unsafe.Pointer(&buf[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_GETDIRENTRIES64, uintptr(fd), uintptr(_p0), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getdtablesize() (size int) {
r0, _, _ := Syscall(SYS_GETDTABLESIZE, 0, 0, 0)
size = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getegid() (egid int) {
r0, _, _ := RawSyscall(SYS_GETEGID, 0, 0, 0)
egid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Geteuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETEUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getgid() (gid int) {
r0, _, _ := RawSyscall(SYS_GETGID, 0, 0, 0)
gid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgid(pid int) (pgid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0)
pgid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpgrp() (pgrp int) {
r0, _, _ := RawSyscall(SYS_GETPGRP, 0, 0, 0)
pgrp = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpid() (pid int) {
r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0)
pid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getppid() (ppid int) {
r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0)
ppid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getpriority(which int, who int) (prio int, err error) {
r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0)
prio = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_GETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getrusage(who int, rusage *Rusage) (err error) {
_, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getsid(pid int) (sid int, err error) {
r0, _, e1 := RawSyscall(SYS_GETSID, uintptr(pid), 0, 0)
sid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Getuid() (uid int) {
r0, _, _ := RawSyscall(SYS_GETUID, 0, 0, 0)
uid = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Issetugid() (tainted bool) {
r0, _, _ := RawSyscall(SYS_ISSETUGID, 0, 0, 0)
tainted = bool(r0 != 0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Kqueue() (fd int, err error) {
r0, _, e1 := Syscall(SYS_KQUEUE, 0, 0, 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lchown(path string, uid int, gid int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LCHOWN, uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Link(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Listen(s int, backlog int) (err error) {
_, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(backlog), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Lstat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKDIR, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkfifo(path string, mode uint32) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKFIFO, uintptr(unsafe.Pointer(_p0)), uintptr(mode), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_MKNOD, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mlockall(flags int) (err error) {
_, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mprotect(b []byte, prot int) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlock(b []byte) (err error) {
var _p0 unsafe.Pointer
if len(b) > 0 {
_p0 = unsafe.Pointer(&b[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
_, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Munlockall() (err error) {
_, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Open(path string, mode int, perm uint32) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_OPEN, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm))
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pathconf(path string, name int) (val int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_PATHCONF, uintptr(unsafe.Pointer(_p0)), uintptr(name), 0)
val = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pread(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PREAD, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Pwrite(fd int, p []byte, offset int64) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall6(SYS_PWRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(offset), 0, 0)
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func read(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Readlink(path string, buf []byte) (n int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_READLINK, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rename(from string, to string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(from)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(to)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RENAME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Revoke(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_REVOKE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Rmdir(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_RMDIR, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seek(fd int, offset int64, whence int) (newoffset int64, err error) {
r0, _, e1 := Syscall(SYS_LSEEK, uintptr(fd), uintptr(offset), uintptr(whence))
newoffset = int64(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Select(n int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (err error) {
_, _, e1 := Syscall6(SYS_SELECT, uintptr(n), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setegid(egid int) (err error) {
_, _, e1 := Syscall(SYS_SETEGID, uintptr(egid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Seteuid(euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETEUID, uintptr(euid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setgid(gid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETGID, uintptr(gid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setlogin(name string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SETLOGIN, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpgid(pid int, pgid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setpriority(which int, who int, prio int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio))
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setprivexec(flag int) (err error) {
_, _, e1 := Syscall(SYS_SETPRIVEXEC, uintptr(flag), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setregid(rgid int, egid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREGID, uintptr(rgid), uintptr(egid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setreuid(ruid int, euid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETREUID, uintptr(ruid), uintptr(euid), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setrlimit(which int, lim *Rlimit) (err error) {
_, _, e1 := RawSyscall(SYS_SETRLIMIT, uintptr(which), uintptr(unsafe.Pointer(lim)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setsid() (pid int, err error) {
r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0)
pid = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Settimeofday(tp *Timeval) (err error) {
_, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Setuid(uid int) (err error) {
_, _, e1 := RawSyscall(SYS_SETUID, uintptr(uid), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Stat(path string, stat *Stat_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Statfs(path string, stat *Statfs_t) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_STATFS64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Symlink(path string, link string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 *byte
_p1, err = BytePtrFromString(link)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_SYMLINK, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Sync() (err error) {
_, _, e1 := Syscall(SYS_SYNC, 0, 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Truncate(path string, length int64) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_TRUNCATE, uintptr(unsafe.Pointer(_p0)), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Umask(newmask int) (oldmask int) {
r0, _, _ := Syscall(SYS_UMASK, uintptr(newmask), 0, 0)
oldmask = int(r0)
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Undelete(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNDELETE, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unlink(path string) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNLINK, uintptr(unsafe.Pointer(_p0)), 0, 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Unmount(path string, flags int) (err error) {
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
_, _, e1 := Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func write(fd int, p []byte) (n int, err error) {
var _p0 unsafe.Pointer
if len(p) > 0 {
_p0 = unsafe.Pointer(&p[0])
} else {
_p0 = unsafe.Pointer(&_zero)
}
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p)))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func mmap(addr uintptr, length uintptr, prot int, flag int, fd int, pos int64) (ret uintptr, err error) {
r0, _, e1 := Syscall6(SYS_MMAP, uintptr(addr), uintptr(length), uintptr(prot), uintptr(flag), uintptr(fd), uintptr(pos))
ret = uintptr(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func munmap(addr uintptr, length uintptr) (err error) {
_, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func readlen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func writelen(fd int, buf *byte, nbuf int) (n int, err error) {
r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(buf)), uintptr(nbuf))
n = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func gettimeofday(tp *Timeval) (sec int64, usec int32, err error) {
r0, r1, e1 := RawSyscall(SYS_GETTIMEOFDAY, uintptr(unsafe.Pointer(tp)), 0, 0)
sec = int64(r0)
usec = int32(r1)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
| {'content_hash': 'c4271ab0d2593232c17e04bdf3de7e37', 'timestamp': '', 'source': 'github', 'line_count': 1384, 'max_line_length': 178, 'avg_line_length': 23.542630057803468, 'alnum_prop': 0.6437099100758064, 'repo_name': 'ImJasonH/go', 'id': '73a834c7179a050df8e478a751e9b2e6bb7a73ef', 'size': '32755', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/syscall/zsyscall_darwin_arm64.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2566560'}, {'name': 'Awk', 'bytes': '450'}, {'name': 'Batchfile', 'bytes': '7351'}, {'name': 'C', 'bytes': '191319'}, {'name': 'C++', 'bytes': '1370'}, {'name': 'CSS', 'bytes': '8'}, {'name': 'Fortran', 'bytes': '394'}, {'name': 'Go', 'bytes': '36022050'}, {'name': 'HTML', 'bytes': '1806598'}, {'name': 'JavaScript', 'bytes': '2550'}, {'name': 'Logos', 'bytes': '1248'}, {'name': 'Makefile', 'bytes': '748'}, {'name': 'Perl', 'bytes': '34799'}, {'name': 'Protocol Buffer', 'bytes': '2015'}, {'name': 'Python', 'bytes': '12446'}, {'name': 'Shell', 'bytes': '70264'}]} |
'use strict'
// a test where we validate the siguature of the keys
// otherwise exactly the same as the ssl test
var server = require('./server')
, request = require('../index')
, fs = require('fs')
, path = require('path')
, tape = require('tape')
var s = server.createSSLServer()
, caFile = path.resolve(__dirname, 'ssl/ca/ca.crt')
, ca = fs.readFileSync(caFile)
, opts = {
ciphers: 'AES256-SHA',
key: path.resolve(__dirname, 'ssl/ca/server.key'),
cert: path.resolve(__dirname, 'ssl/ca/server.crt')
}
, sStrict = server.createSSLServer(s.port + 1, opts)
function runAllTests(strict, s) {
var strictMsg = (strict ? 'strict ' : 'relaxed ')
tape(strictMsg + 'setup', function(t) {
s.listen(s.port, function() {
t.end()
})
})
function runTest(name, test) {
tape(strictMsg + name, function(t) {
s.on('/' + name, test.resp)
test.uri = s.url + '/' + name
if (strict) {
test.strictSSL = true
test.ca = ca
test.headers = { host: 'testing.request.mikealrogers.com' }
} else {
test.rejectUnauthorized = false
}
request(test, function(err, resp, body) {
t.equal(err, null)
if (test.expectBody) {
t.deepEqual(test.expectBody, body)
}
t.end()
})
})
}
runTest('testGet', {
resp : server.createGetResponse('TESTING!')
, expectBody: 'TESTING!'
})
runTest('testGetChunkBreak', {
resp : server.createChunkResponse(
[ new Buffer([239])
, new Buffer([163])
, new Buffer([191])
, new Buffer([206])
, new Buffer([169])
, new Buffer([226])
, new Buffer([152])
, new Buffer([131])
])
, expectBody: '\uf8ff\u03a9\u2603'
})
runTest('testGetJSON', {
resp : server.createGetResponse('{"test":true}', 'application/json')
, json : true
, expectBody: {'test':true}
})
runTest('testPutString', {
resp : server.createPostValidator('PUTTINGDATA')
, method : 'PUT'
, body : 'PUTTINGDATA'
})
runTest('testPutBuffer', {
resp : server.createPostValidator('PUTTINGDATA')
, method : 'PUT'
, body : new Buffer('PUTTINGDATA')
})
runTest('testPutJSON', {
resp : server.createPostValidator(JSON.stringify({foo: 'bar'}))
, method: 'PUT'
, json: {foo: 'bar'}
})
runTest('testPutMultipart', {
resp: server.createPostValidator(
'--__BOUNDARY__\r\n' +
'content-type: text/html\r\n' +
'\r\n' +
'<html><body>Oh hi.</body></html>' +
'\r\n--__BOUNDARY__\r\n\r\n' +
'Oh hi.' +
'\r\n--__BOUNDARY__--'
)
, method: 'PUT'
, multipart:
[ {'content-type': 'text/html', 'body': '<html><body>Oh hi.</body></html>'}
, {'body': 'Oh hi.'}
]
})
tape(strictMsg + 'cleanup', function(t) {
s.close(function() {
t.end()
})
})
}
runAllTests(false, s)
if (!process.env.running_under_istanbul) {
// somehow this test modifies the process state
// test coverage runs all tests in a single process via tape
// executing this test causes one of the tests in test-tunnel.js to throw
runAllTests(true, sStrict)
}
| {'content_hash': '74f2682fc7c977abc98547ac3392adcd', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 81, 'avg_line_length': 25.095238095238095, 'alnum_prop': 0.5755850727387729, 'repo_name': 'simov/request', 'id': '74ebb880dcb93b573d1eb5c7e2a20e7e100280e6', 'size': '3162', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'tests/test-https.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '273285'}, {'name': 'Shell', 'bytes': '2535'}]} |
package com.gatf.executor.report;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import com.gatf.executor.core.GatfExecutorConfig;
/**
* @author Sumeet Chhetri
*
*/
public class TestCaseExecutionLogGenerator implements Runnable {
private static ConcurrentLinkedQueue<String> Q = new ConcurrentLinkedQueue<String>();
GatfExecutorConfig config;
private Writer writer;
public TestCaseExecutionLogGenerator(GatfExecutorConfig config)
{
this.config = config;
}
public static void log(TestCaseReport report)
{
Q.add(report.toStatisticsCsv());
}
public void run() {
try {
File basePath = new File(config.getOutFilesBasePath());
File resource = new File(basePath, config.getOutFilesDir());
writer = new BufferedWriter(new FileWriter(new File(resource.getAbsolutePath()
+ File.separator + UUID.randomUUID().toString() + ".csv")));
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
while(true)
{
String logentry = null;
while((logentry = Q.poll())==null)
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw e;
}
}
writer.write(logentry);
}
} catch (Exception e) {
if(!(e instanceof InterruptedException))
{
e.printStackTrace();
}
} finally {
if(writer!=null)
{
try {
String logentry = null;
while((logentry = Q.poll())!=null)
{
writer.write(logentry);
}
writer.flush();
writer.close();
} catch (Exception e) {
}
}
}
}
}
| {'content_hash': '08105e93b8dba92dd30bf9697b7b4705', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 86, 'avg_line_length': 22.02469135802469, 'alnum_prop': 0.6283632286995515, 'repo_name': 'sumeetchhetri/gatf', 'id': '9d3c29e94e38c0c2d522cad1b927dd3df6dd14c4', 'size': '2412', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'alldep-jar/src/main/java/com/gatf/executor/report/TestCaseExecutionLogGenerator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '130817'}, {'name': 'Dockerfile', 'bytes': '1880'}, {'name': 'HTML', 'bytes': '80457'}, {'name': 'Java', 'bytes': '1310854'}, {'name': 'JavaScript', 'bytes': '2320481'}, {'name': 'Shell', 'bytes': '5524'}]} |
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Express vs. Hapi</title>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="css/reveal.min.css">
<link rel="stylesheet" href="css/theme/default.css" id="theme">
<link rel="stylesheet" href="css/custom.css" id="custom-css">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-37756010-1', 'auto');
ga('send', 'pageview');
$(document).ready(function () {
Reveal.addEventListener("slidechanged",function(event){
ga('send', 'pageview', {
'page': event.indexh,
'title': document.title + ' : Slide ' + event.indexh
});
});
});
</script>
<!-- End Google Analytics -->
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<h1>Express vs. Hapi</h1>
<p>for APIs with Node.js</p>
<aside class="notes">
Hello world, notes
</aside>
</section>
<section data-background="white" class="presentation twins">
<h2>Qui sommes-nous ?</h2>
<div class="twin">
<h4 class="florent-name">Florent Jaby</h4>
<p>
<ul>
<li>Consultant pour OCTO Technology</li>
<li>Noder depuis 2009</li>
<li><a href="http://github.com/Floby">@Floby</a> sur Github et le reste d'internet</li>
</ul>
</p>
</div>
<div class="twin">
<h4 class="florent-name">Adrien Becchis</h4>
<p>
<ul>
<li>En stage chez OCTO Technology</li>
<li>Noder depuis 2015 =)</li>
<li><a href="https://github.com/AdrieanKhisbe">@AdrieanKhisbe</a> sur Github</li>
</ul>
</p>
</div>
<img src="images/octo-logo.png" alt="OCTO Technology" class="octo-logo pull-right" />
</section>
<section>
<h3>Pourquoi Node.js ?</h3>
<ul>
<li class="fragment">Itérations rapide sur le code</li>
<li class="fragment">JSON natif</li>
<li class="fragment">Asynchrone</li>
<li class="fragment">Écosystème riche (npm)</li>
<li class="fragment">Parce que c'est cool !</li>
</ul>
</section>
<section>
<h3>Quelques stats</h3>
<p>
<table >
<thead>
<tr>
<td scope="col" class="left"><strong>Métriques</strong></td>
<td scope="col" class="left"><frexpr>Express</frexpr></td>
<td scope="col" class="left"><frhapi>Hapi</frhapi></td>
</tr>
</thead>
<tbody>
<tr>
<th>Github stars</th>
<td>19k</td>
<td>4,2k</td>
</tr>
<tr>
<th>Github fork</th>
<td>3,6k</td>
<td>0,6k</td>
</tr>
<tr>
<th>StackOverflow</th>
<td>15k</td>
<td>180</td>
</tr>
<tr>
<th>Contributor</th>
<td>177</td>
<td>114</td>
</tr>
<tr>
<th>Github require</th>
<td>~360k</td>
<td>6k</td>
</tr>
<tr>
<th>First Commit</th>
<td>26 Juin 2009</td>
<td>6 Août 2011</td>
</tr>
</tbody>
</table>
</p>
</section>
<section>
<h4>
Fonctionnement d'<frexpr>Express</frexpr>
</h4>
<img src="images/express-lifecycle.png" class="schema">
<small>Cycle de vie d'une requête HTTP avec Express</small>
<img src="images/express-middleware.png" class="schema">
<small>Echainement des middlewares</small>
</section>
<section>
<h4>
Fonctionnement de <frhapi>Hapi</frhapi>
</h4>
<img src="images/hapi-lifecycle.png" class="schema">
<small>Cycle de vie d'une requête HTTP avec Hapi</small>
<img src="images/hapi-hooks.png" class="schema">
<small>"Hooks" disponible en Hapi</small>
</section>
<section>
<section>
<h4>
Exemple CRUD <frexpr>Express</frexpr>
</h4>
<pre><code data-trim>
var express = require('express');
var app = express();
var MeetupDAO = require(somePath)(someConfiguration);
app.get('/meetups', function (req, res) {
MeetupDAO.all(function (err, meetups) {
if(err) res.sendStatus(500);
else res.json(meetups);
});
});
// autres routes CRUD: collection.post, member.get,put,delete .
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
</code></pre>
</section>
<section>
<h5><frexpr>MiddleWare</frexpr></h5>
<pre><code data-trim>
var bodyParser = require('body-parser');
var morgan = require('morgan');
// loading
app.use(bodyParser.json());
app.use(morgan('combined'));
// declaration
function logger(request, response, next) {
var start = +new Date();
var url = request.url;
var method = request.method;
response.on('finish', function() {
var duration = +new Date() - start;
console.log(method + ' ' + url +' (' + duration + ')');
});
next();
}
</code></pre>
</section>
<section>
<h5><frexpr>Routes</frexpr></h5>
<pre><code data-trim>
app.route('/meetups')
.get(MeetupController.all)
.post(MeetupController.create);
app.route('/meetups/:id')
.get(MeetupController.get)
.put(MeetupController.update)
.patch(MeetupController.partialUpdate)
.delete(MeetupController.remove);
</code></pre>
</section>
<section>
<h5><frexpr>Controllers</frexpr></h5>
<pre><code data-trim>
function all(req, res) {
MeetupDAO.all(function (all) {
res.json(all);
});
}
function create(req, res) {
if (!req.body.url) {
return res.sendStatus(400);
}
var meetup = Meetup.create(req.body.url, req.body.title, req.body.date);
MeetupDAO.save(meetup, function (newMeetup) {
res.location(meetupsEndpoint + '/' + newMeetup._id);
res.status(201).json({});
});
}
</code></pre>
</section>
<section>
<h5><frexpr>Error handling</frexpr></h5>
<pre><code data-trim>
var StandardError = require('standard-error');
app.use(function (err, req, res, next) {
if (err instanceof IKnowThisError) {
res.status(503).json({
error: 'service_unavaible',
reason: 'Looks like one of our partners is not doing his job'
});
} else {
next(err);
}
});
app.use(function (err, req, res, next) {
if (err instanceof StandardError) {
res.status(err.code);
res.json(error.toJSON());
} else {
next(err);
}
});
</code></pre>
</section>
</section>
<section>
<section>
<h4>
Exemple CRUD <frhapi>Hapi</frhapi>
</h4>
<pre><code data-trim>
var MeetupDAO = require(somePath)(someConfiguration);
var server = new Hapi.Server({ load: {sampleInterval: 5000}});
server.connection({port: 3000});
server.route([
{ method: 'GET',
path: '/meetups',
handler: function (request, reply) {
MeetupDAO.all(function (err, meetups) {
if(err) reply().code(500);
else reply(meetups);
});
}
}
// autres routes.
]);
server.start(function () {
console.log('Server running at:', server.info.uri);
});
</code></pre>
</section>
<section>
<h5><frhapi>Routes</frhapi></h5>
<pre><code data-trim>
var meetupRoutes = [
{ method: 'GET', path: '/meetups', handler: MeetupController.all },
{
method: 'POST', path: '/meetups',
config: {
handler: MeetupController.create,
validate: {payload: schemas.meetupCreate}
}
},
{
method: 'PUT', path: '/meetups/{id}',
config: {
handler: MeetupController.update,
validate: { payload: schemas.meetupUpdate }
}
},
{ method: 'DELETE', path: '/meetups/{id}', handler: MeetupController.remove },
{ method: 'GET', path: '/meetups/{id}', handler: MeetupController.get },
];
</code></pre>
</section>
<section>
<h5><frhapi>Controllers</frhapi></h5>
<pre><code data-trim>
function all(request, reply) {
MeetupDAO.all(function (all) {
reply(all);
});
}
function create(request, reply) {
if (!request.payload.url) {
return reply().code(400);
}
var meetup = Meetup.create(request.payload.url,
request.payload.title, request.payload.date);
MeetupDAO.save(meetup, function (newMeetup) {
reply().created(meetupsEndpoint + '/' + newMeetup._id);
});
}
</code></pre>
</section>
<section>
<h5><frhapi>Error handling</frhapi></h5>
<pre><code data-trim>
var Boom = require('boom');
//....
server.route({
method: 'GET', path: '/meetups/{id}',
handler: function getMeetup(request, reply) {
if (!request.params.id) {
return reply(Boom.badRequest('No id was provided'));
}
MeetupDAO.get(request.params.id, function (err, meetup) {
if(err) reply(Boom.wrap(err, 500));
else reply(meetup);
});
}
});
</code></pre>
</section>
</section>
<section>
<section>
<h3>Injection de dépendances</h3>
<ul>
<li>"Inversion de contrôle"</li>
<li>Ne pas instancier ses classes de délégation dans le code qui les utilise</li>
</ul>
</section>
<section>
<h5>
<frexpr>Express</frexpr>
</h5>
<pre><code data-trim>
app.set('db', someDbConnection) // injecte 'db' dans 'app'
app.use(bodyparse.json()); // injecte `.body` dans `req`
app.use(cookieparser()); // injecte `.cookies` dans `req`
app.use(session()); // injecte `.session` dans `req`
app.use(function currentUser(req, res, next) {
var userId = req.session.userId;
if (!userId) return next();
app.get('db').users.findOne({_id: userId}, function (err, user) {
if (err) return next(err);
req.currentUser = user // injection de l'utilsateur courant
});
});
</code></pre>
</section>
<section>
<h5>
<frhapi>Hapi</frhapi>
</h5>
<pre><code data-trim>
server.bind({db: someDbConnection});
server.register({
// injecte `.session` sur l'objet `.request`
register: require('yar')
})
// ...
{
method: 'GET',
path: '/current-user',
handler: function (request, reply) {
this.db.users.findOne({_id: request.session.userId}, function (err, user) {
if (err) return reply(err);
reply(user);
})
}
}
</code></pre>
</section>
</section>
<section>
<section class="twins conclusion">
<h4>Conclusion</h4>
<div class="twin">
<h5>
<frexpr>Express</frexpr>
</h5>
<ul>
<li>old-timer</li>
<li>"lightweight", "thin", "lean", bref : minimal</li>
<li>Incrément et itérations rapides au début</li>
<li>Perte de robustesse et de maintenabilité au fil du temps</li>
</ul>
</div>
<div class="twin">
<h5>
<frhapi>Hapi</frhapi>
</h5>
<ul>
<li>new player</li>
<li>"Vrai" framework qui apporte ses conventions et abstractions</li>
<li>Courbe d'apprentissage plus forte</li>
<li>Plus industriel, plus compréhensible pour les dev non-js</li>
</ul>
</div>
<div></div>
<div class="twin">
<img src="images/productivity-curve-express.png" alt="">
</div>
<div class="twin">
<img src="images/productivity-curve-hapi.png" alt="">
</div>
</section>
<section class="twins">
<h4>Tooling</h4>
<div class="twin">
<h5>
<frexpr>Express</frexpr>
</h5>
<ul>
<li>20k modules npm</li>
<li>Les outils <a href="https://github.com/strongloop">StrongLoop</a></li>
<li class="fragment">n'importer quel outil unix ;)</li>
</ul>
</div>
<div class="twin">
<h5>
<frhapi>Hapi</frhapi>
</h5>
<ul>
<li>La suite <a href="https://github.com/hapijs">"Walmart / Hapijs"</a></li>
<li class="fragment">n'importer quel outil unix ;)</li>
</ul>
</div>
</section>
</section>
<section class="links">
<h5>Merci !</h5>
<p><em><small>have some more links</small></em></p>
<p class="link">
<img class="qr" src="images/link-github.svg" alt="">
<a href="https://github.com/AdrieanKhisbe/pending-link">Dépot Github du comparatif</a>
</p>
<p class="link">
<img class="qr" src="images/link-node-for-api.svg" alt="">
<a href="http://blog.octo.com/node-for-api/">Pourquoi utiliser Node pour réaliser mon API ?</a>
</p>
<p class="link">
<img class="qr" src="images/link-ecosystem.svg" alt="">
<a href="http://blog.octo.com/node-for-api-express-and-hapi-architecture-and-ecosystem/">Architecture et Ecosystème d’Express et Hapi</a>
</p>
<p class="link">
<img class="qr" src="images/link-en-pratique.svg" alt="">
<a href="http://blog.octo.com/node-for-api-express-and-hapi-en-pratique/">Express et Hapi en pratique</a>
</p>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme || 'night', // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'concave', // default/cube/page/concave/zoom/linear/fade/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: 'lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: 'plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: 'plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: 'plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: 'plugin/search/search.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>
| {'content_hash': '84047353d66115f76d9c0f3c4d68a41c', 'timestamp': '', 'source': 'github', 'line_count': 554, 'max_line_length': 174, 'avg_line_length': 31.93321299638989, 'alnum_prop': 0.5144423718274829, 'repo_name': 'Floby/nodejsparis-express-hapi', 'id': '29a8697fa242f86f7784b0a2cf31f5d07e279502', 'size': '17712', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '108299'}, {'name': 'HTML', 'bytes': '30772'}, {'name': 'JavaScript', 'bytes': '107567'}]} |
FROM balenalib/kitra710-alpine:3.10-run
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apk add --no-cache ca-certificates libffi \
&& apk add --no-cache libssl1.0 || apk add --no-cache libssl1.1
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.8.6
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 20.3.1
ENV SETUPTOOLS_VERSION 51.0.0
RUN set -x \
&& buildDeps=' \
curl \
gnupg \
' \
&& apk add --no-cache --virtual .build-deps $buildDeps \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \
&& echo "e1c61b20b9e3c35cc6fe765b4d49426ebfef188580592da1bdcd9ed40564e612 Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-aarch64-openssl1.1.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Alpine Linux 3.10 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.6, Pip v20.3.1, Setuptools v51.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {'content_hash': '51816a2b66a7f259dde70c3d77aac5f3', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 713, 'avg_line_length': 53.33766233766234, 'alnum_prop': 0.711955198441685, 'repo_name': 'nghiant2710/base-images', 'id': 'c3e6ddd99297a597b5247dffdfa6469254c06d27', 'size': '4128', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/python/kitra710/alpine/3.10/3.8.6/run/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]} |
<?php
/**
* Loop - Blog
*
* This is the loop file used on the "Blog" page template.
*
* @package WooFramework
* @subpackage Template
*/
global $more; $more = 0;
woo_loop_before();
// Fix for the WordPress 3.0 "paged" bug.
$paged = 1;
if ( get_query_var( 'paged' ) ) { $paged = get_query_var( 'paged' ); }
if ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); }
$paged = intval( $paged );
$query_args = array(
'post_type' => 'post',
'paged' => $paged
);
$query_args = apply_filters( 'woo_blog_template_query_args', $query_args ); // Do not remove. Used to exclude categories from displaying here.
remove_filter( 'pre_get_posts', 'woo_exclude_categories_homepage', 10 );
query_posts( $query_args );
if ( have_posts() ) { $count = 0;
?>
<div class="fix"></div>
<?php
while ( have_posts() ) { the_post(); $count++;
woo_get_template_part( 'content', get_post_type() );
} // End WHILE Loop
} else {
get_template_part( 'content', 'noposts' );
} // End IF Statement
woo_loop_after();
woo_pagenav();
?>
| {'content_hash': 'f7f37e178a6df4746ab02d16b1613f4a', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 142, 'avg_line_length': 21.428571428571427, 'alnum_prop': 0.6047619047619047, 'repo_name': 'misfit-inc/dinnerties.com', 'id': 'ed61dd712e06816d27363056f0e9f897bcbc3ef4', 'size': '1050', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'wp-content/themes/dinnerties/loop-blog.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1981533'}, {'name': 'JavaScript', 'bytes': '2341423'}, {'name': 'PHP', 'bytes': '11252525'}]} |
@import UIKit;
@interface QYAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {'content_hash': '440f9d91406090d1621d1b3aa376ba61', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 19.142857142857142, 'alnum_prop': 0.7835820895522388, 'repo_name': 'qiaoy/QYCategorys', 'id': 'ecb1bbe39443b6506a9ff250fe9ac723f3093e72', 'size': '267', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Example/QYCategorys/QYAppDelegate.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '12788'}, {'name': 'Ruby', 'bytes': '1749'}, {'name': 'Shell', 'bytes': '17196'}]} |
/** @constructor */
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp = (function() {
ScalaJS.c.scala_runtime_AbstractFunction2.call(this)
});
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype = new ScalaJS.inheritable.scala_runtime_AbstractFunction2();
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype.constructor = ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp;
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype.init___ = (function() {
ScalaJS.c.scala_runtime_AbstractFunction2.prototype.init___.call(this);
ScalaJS.impls.scala_Function2$mcVDJ$sp$class__$init$__Lscala_Function2$mcVDJ$sp__V(this);
return this
});
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype.apply__D__J__ = (function(v1, v2) {
return ScalaJS.bV(this.apply__D__J__V(v1, v2))
});
/** @constructor */
ScalaJS.inheritable.scala_runtime_AbstractFunction2$mcVDJ$sp = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype = ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype;
ScalaJS.is.scala_runtime_AbstractFunction2$mcVDJ$sp = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_runtime_AbstractFunction2$mcVDJ$sp)))
});
ScalaJS.as.scala_runtime_AbstractFunction2$mcVDJ$sp = (function(obj) {
if ((ScalaJS.is.scala_runtime_AbstractFunction2$mcVDJ$sp(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.runtime.AbstractFunction2$mcVDJ$sp")
}
});
ScalaJS.isArrayOf.scala_runtime_AbstractFunction2$mcVDJ$sp = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_runtime_AbstractFunction2$mcVDJ$sp)))
});
ScalaJS.asArrayOf.scala_runtime_AbstractFunction2$mcVDJ$sp = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_runtime_AbstractFunction2$mcVDJ$sp(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.runtime.AbstractFunction2$mcVDJ$sp;", depth)
}
});
ScalaJS.data.scala_runtime_AbstractFunction2$mcVDJ$sp = new ScalaJS.ClassTypeData({
scala_runtime_AbstractFunction2$mcVDJ$sp: 0
}, false, "scala.runtime.AbstractFunction2$mcVDJ$sp", ScalaJS.data.scala_runtime_AbstractFunction2, {
scala_runtime_AbstractFunction2$mcVDJ$sp: 1,
scala_Function2$mcVDJ$sp: 1,
scala_runtime_AbstractFunction2: 1,
scala_Function2: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_runtime_AbstractFunction2$mcVDJ$sp.prototype.$classData = ScalaJS.data.scala_runtime_AbstractFunction2$mcVDJ$sp;
//@ sourceMappingURL=AbstractFunction2$mcVDJ$sp.js.map
| {'content_hash': 'ebc4fe5132d535f2603c3e54142ef387', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 162, 'avg_line_length': 53.38, 'alnum_prop': 0.7545897339827651, 'repo_name': 'ignaciocases/hermeneumatics', 'id': '01023727eb3d89bba7519ea6f8038d4cbcc4ed3b', 'size': '2669', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/scala-node/main/target/streams/compile/externalDependencyClasspath/$global/package-js/extracted-jars/scalajs-library_2.10-0.4.0.jar--29fb2f8b/scala/runtime/AbstractFunction2$mcVDJ$sp.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '430'}, {'name': 'CoffeeScript', 'bytes': '9579'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.drools.testcoverage</groupId>
<artifactId>drools-kie-ci-with-domain-parent</artifactId>
<version>7.49.0-SNAPSHOT</version>
</parent>
<artifactId>drools-kie-ci-with-domain-test-domain</artifactId>
<name>Drools :: Test Coverage :: KIE-CI with Domain classes :: Domain</name>
<dependencies>
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
| {'content_hash': 'e232c19bbb3760e8247ccf9431b00e9d', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 108, 'avg_line_length': 30.884615384615383, 'alnum_prop': 0.6737235367372354, 'repo_name': 'droolsjbpm/drools', 'id': '4f4f3b82cadb606192055e9b6ef2ab84a6618712', 'size': '803', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'drools-test-coverage/standalone/kie-ci-with-domain/test-domain/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2554'}, {'name': 'CSS', 'bytes': '1412'}, {'name': 'GAP', 'bytes': '197127'}, {'name': 'HTML', 'bytes': '9298'}, {'name': 'Java', 'bytes': '26871006'}, {'name': 'Protocol Buffer', 'bytes': '13855'}, {'name': 'Python', 'bytes': '4555'}, {'name': 'Ruby', 'bytes': '491'}, {'name': 'Shell', 'bytes': '1120'}, {'name': 'Standard ML', 'bytes': '82260'}, {'name': 'XSLT', 'bytes': '24302'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project>
<body>
<menu name="Overview">
<item name="Introduction" href="./index.html"/>
<item name="Goals" href="./plugin-info.html"/>
<item name="Usage" href="./configuration-com.google.closure.plugin.ClosureGenerateSourcesMojo.html"/>
<!--
<item name="FAQ" href="./faq.html"/>
-->
</menu>
<menu name="Examples">
<item name="JS Compiler Flags"
href="./examples/js-configuration.html"/>
<item name="Protobufs"
href="./examples/protobuf-deps.html"/>
<item name="Extracting Dependencies"
href="./examples/extracting-deps.html"/>
</menu>
</body>
</project>
| {'content_hash': '6db97bc7c80d283a7798445b75e5d405', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 107, 'avg_line_length': 31.454545454545453, 'alnum_prop': 0.596820809248555, 'repo_name': 'mikesamuel/closure-maven-plugin', 'id': 'e46b925f8b08b32819ad830dac93501a6ea46fc8', 'size': '692', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'plugin/src/site/site.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1324'}, {'name': 'Groovy', 'bytes': '2360'}, {'name': 'Java', 'bytes': '599520'}, {'name': 'JavaScript', 'bytes': '24210'}, {'name': 'Protocol Buffer', 'bytes': '1842'}, {'name': 'Shell', 'bytes': '5823'}]} |
class AddTaskFieldIdToTaskFieldValues < ActiveRecord::Migration
def change
add_column :task_field_values, :task_field_id, :integer
end
end
| {'content_hash': 'aeb7af3ffbb766cbbddfb0473981bf39', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 63, 'avg_line_length': 29.4, 'alnum_prop': 0.7755102040816326, 'repo_name': 'boberetezeke/open_org_base', 'id': '8c3308290e118a569745fb2fa6ac6483b38a8e89', 'size': '147', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/migrate/20121228214413_add_task_field_id_to_task_field_values.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1282'}, {'name': 'Ruby', 'bytes': '85946'}]} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_int_placement_new_18.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml
Template File: sources-sink-18.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: placement_new Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 18 Control flow: goto statements
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_int_placement_new_18
{
#ifndef OMITBAD
void bad()
{
int * data;
data = NULL; /* Initialize data */
goto source;
source:
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
char buffer[sizeof(int)];
int * dataBuffer = new(buffer) int;
*dataBuffer = 5;
data = dataBuffer;
}
printIntLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */
static void goodG2B()
{
int * data;
data = NULL; /* Initialize data */
goto source;
source:
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
int * dataBuffer = new int;
*dataBuffer = 5;
data = dataBuffer;
}
printIntLine(*data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete data;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* 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
using namespace CWE590_Free_Memory_Not_on_Heap__delete_int_placement_new_18; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {'content_hash': '0bd3e54d797dc65f53aeb0e357277cdd', 'timestamp': '', 'source': 'github', 'line_count': 101, 'max_line_length': 121, 'avg_line_length': 25.633663366336634, 'alnum_prop': 0.6357667052916184, 'repo_name': 'maurer/tiamat', 'id': '4a80ccbe52cd8fbb569caae423fc94d819815b4d', 'size': '2589', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'samples/Juliet/testcases/CWE590_Free_Memory_Not_on_Heap/s03/CWE590_Free_Memory_Not_on_Heap__delete_int_placement_new_18.cpp', 'mode': '33188', 'license': 'mit', 'language': []} |
import Ember from "ember";
export default Ember.Route.extend({
_debug: function() {
console.log("debug", this.get("country-data"));
}.on("init")
});
| {'content_hash': '4fd0da9d8d13bc8396ce9c8738e0f457', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 51, 'avg_line_length': 22.571428571428573, 'alnum_prop': 0.6392405063291139, 'repo_name': 'PracticeIQ/ember-country-service', 'id': '6af072265414c3528574b697f7d609b34bc4b3de', 'size': '158', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/dummy/app/routes/application.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1623'}, {'name': 'JavaScript', 'bytes': '57469'}]} |
using NBi.Core.Injection;
using NBi.Core.ResultSet;
using NBi.Core.Variable;
using NBi.Extensibility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Transformation
{
public class TransformationProvider
{
private IDictionary<IColumnIdentifier, ITransformer> cacheTransformers;
private readonly TransformerFactory factory;
private Context Context { get; }
public TransformationProvider(ServiceLocator serviceLocator, Context context)
{
cacheTransformers = new Dictionary<IColumnIdentifier, ITransformer>();
factory = new TransformerFactory(serviceLocator, context);
Context = context;
}
public void Add(IColumnIdentifier indentifier, ITransformationInfo transfo)
{
var transformer = factory.Instantiate(transfo);
transformer.Initialize(transfo.Code);
if (cacheTransformers.ContainsKey(indentifier))
throw new NBiException($"You can't define two transformers for the same column. The column {indentifier.Label} has already another transformer specified.");
cacheTransformers.Add(indentifier, transformer);
}
public virtual IResultSet Transform(IResultSet resultSet)
{
foreach (var identifier in cacheTransformers.Keys)
{
var tsStart = DateTime.Now;
var transformer = cacheTransformers[identifier];
var newColumn = new DataColumn() { DataType = typeof(object) };
resultSet.Table.Columns.Add(newColumn);
var ordinal = (identifier as ColumnOrdinalIdentifier)?.Ordinal ?? resultSet.Table.Columns[(identifier as ColumnNameIdentifier).Name].Ordinal;
var originalName = resultSet.Table.Columns[ordinal].ColumnName;
foreach (DataRow row in resultSet.Table.Rows)
{
Context.Switch(row);
row[newColumn.Ordinal] = transformer.Execute(row[ordinal]);
}
resultSet.Table.Columns.RemoveAt(ordinal);
newColumn.SetOrdinal(ordinal);
newColumn.ColumnName = originalName;
Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, string.Format("Time needed to transform column {0}: {1}", identifier.Label, DateTime.Now.Subtract(tsStart).ToString(@"d\d\.hh\h\:mm\m\:ss\s\ \+fff\m\s")));
}
return resultSet;
}
}
}
| {'content_hash': '562b8566c6f3a188046a81c720a3307d', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 215, 'avg_line_length': 39.71212121212121, 'alnum_prop': 0.6489889355207936, 'repo_name': 'Seddryck/NBi', 'id': 'ebd4af4cfa7947ae8475d5a8d905b3a7177c91b4', 'size': '2623', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'NBi.Core/Transformation/TransformationProvider.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '197'}, {'name': 'C#', 'bytes': '4397422'}, {'name': 'HTML', 'bytes': '28966'}, {'name': 'PowerShell', 'bytes': '7401'}]} |
<?php
/**
* DO NOT EDIT THIS FILE!
*
* This file was automatically generated from external sources.
*
* Any manual change here will be lost the next time the SDK
* is updated. You've been warned!
*/
namespace DTS\eBaySDK\Finding\Enums;
class GallerySizeEnum
{
const C_LARGE = 'Large';
const C_MEDIUM = 'Medium';
const C_SMALL = 'Small';
}
| {'content_hash': '79f018da970903338af7b09f95457905', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 63, 'avg_line_length': 20.0, 'alnum_prop': 0.675, 'repo_name': 'davidtsadler/ebay-sdk-php', 'id': '4b64f5d95e908c2f3fb23e2850d9f9cbbff08554', 'size': '360', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Finding/Enums/GallerySizeEnum.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Makefile', 'bytes': '10944'}, {'name': 'PHP', 'bytes': '9958599'}]} |
module RuboCop
module Cop
module Style
# Checks for empty else-clauses, possibly including comments and/or an
# explicit `nil` depending on the EnforcedStyle.
#
# SupportedStyles:
#
# @example
# # good for all styles
# if condition
# statement
# else
# statement
# end
#
# # good for all styles
# if condition
# statement
# end
#
# empty - warn only on empty else
# @example
# # bad
# if condition
# statement
# else
# end
#
# # good
# if condition
# statement
# else
# nil
# end
#
# nil - warn on else with nil in it
# @example
# # bad
# if condition
# statement
# else
# nil
# end
#
# # good
# if condition
# statement
# else
# end
#
# both - warn on empty else and else with nil in it
# @example
# # bad
# if condition
# statement
# else
# nil
# end
#
# # bad
# if condition
# statement
# else
# end
class EmptyElse < Cop
include OnNormalIfUnless
include ConfigurableEnforcedStyle
MSG = 'Redundant `else`-clause.'.freeze
def on_normal_if_unless(node)
check(node, if_else_clause(node))
end
def on_case(node)
check(node, case_else_clause(node))
end
private
def check(node, else_clause)
case style
when :empty
empty_check(node, else_clause)
when :nil
nil_check(node, else_clause)
when :both
both_check(node, else_clause)
end
end
def empty_check(node, else_clause)
add_offense(node, :else, MSG) if node.loc.else && else_clause.nil?
end
def nil_check(node, else_clause)
return unless else_clause && else_clause.type == :nil
add_offense(node, node.location, MSG)
end
def both_check(node, else_clause)
return if node.loc.else.nil?
if else_clause.nil?
add_offense(node, :else, MSG)
elsif else_clause.type == :nil
add_offense(node, :else, MSG)
end
end
def autocorrect(node)
return false if autocorrect_forbidden?(node.type.to_s)
lambda do |corrector|
end_pos = if node.loc.end
node.loc.end.begin_pos
else
node.source_range.end_pos + 1
end
range = Parser::Source::Range.new(node.source_range.source_buffer,
node.loc.else.begin_pos,
end_pos)
corrector.remove(range)
end
end
def autocorrect_forbidden?(type)
[type, 'both'].include? missing_else_style
end
def missing_else_style
missing_config = config.for_cop('Style/MissingElse')
missing_config['Enabled'] ? missing_config['EnforcedStyle'] : nil
end
end
end
end
end
| {'content_hash': 'db9adfcff46d9f69dd56640765034859', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 78, 'avg_line_length': 24.381294964028775, 'alnum_prop': 0.474181174387725, 'repo_name': 'volkert/rubocop', 'id': '829a4f811900dac3ec146989f947438551141ff3', 'size': '3438', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/rubocop/cop/style/empty_else.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5047'}, {'name': 'Ruby', 'bytes': '2317912'}]} |
(function(){
var Tinycon = {};
var currentFavicon = null;
var originalFavicon = null;
var faviconImage = null;
var canvas = null;
var options = {};
var r = window.devicePixelRatio || 1;
var size = 16 * r;
var defaults = {
width: 7,
height: 9,
font: 10 * r + 'px arial',
colour: '#ffffff',
background: '#F03D25',
fallback: true,
crossOrigin: true,
abbreviate: true
};
var ua = (function () {
var agent = navigator.userAgent.toLowerCase();
// New function has access to 'agent' via closure
return function (browser) {
return agent.indexOf(browser) !== -1;
};
}());
var browser = {
ie: ua('msie'),
chrome: ua('chrome'),
webkit: ua('chrome') || ua('safari'),
safari: ua('safari') && !ua('chrome'),
mozilla: ua('mozilla') && !ua('chrome') && !ua('safari')
};
// private methods
var getFaviconTag = function(){
var links = document.getElementsByTagName('link');
for(var i=0, len=links.length; i < len; i++) {
if ((links[i].getAttribute('rel') || '').match(/\bicon\b/)) {
return links[i];
}
}
return false;
};
var removeFaviconTag = function(){
var links = document.getElementsByTagName('link');
var head = document.getElementsByTagName('head')[0];
for(var i=0, len=links.length; i < len; i++) {
var exists = (typeof(links[i]) !== 'undefined');
if (exists && (links[i].getAttribute('rel') || '').match(/\bicon\b/)) {
head.removeChild(links[i]);
}
}
};
var getCurrentFavicon = function(){
if (!originalFavicon || !currentFavicon) {
var tag = getFaviconTag();
originalFavicon = currentFavicon = tag ? tag.getAttribute('href') : '/favicon.ico';
}
return currentFavicon;
};
var getCanvas = function (){
if (!canvas) {
canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
}
return canvas;
};
var setFaviconTag = function(url){
if(url){
removeFaviconTag();
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'icon';
link.href = url;
document.getElementsByTagName('head')[0].appendChild(link);
}
};
var log = function(message){
if (window.console) window.console.log(message);
};
var drawFavicon = function(label, colour) {
// fallback to updating the browser title if unsupported
if (!getCanvas().getContext || browser.ie || browser.safari || options.fallback === 'force') {
return updateTitle(label);
}
var context = getCanvas().getContext("2d");
var colour = colour || '#000000';
var src = getCurrentFavicon();
faviconImage = document.createElement('img');
faviconImage.onload = function() {
// clear canvas
context.clearRect(0, 0, size, size);
// draw the favicon
context.drawImage(faviconImage, 0, 0, faviconImage.width, faviconImage.height, 0, 0, size, size);
// draw bubble over the top
if ((label + '').length > 0) drawBubble(context, label, colour);
// refresh tag in page
refreshFavicon();
};
// allow cross origin resource requests if the image is not a data:uri
// as detailed here: https://github.com/mrdoob/three.js/issues/1305
if (!src.match(/^data/) && options.crossOrigin) {
faviconImage.crossOrigin = 'anonymous';
}
faviconImage.src = src;
};
var updateTitle = function(label) {
if (options.fallback) {
// Grab the current title that we can prefix with the label
var originalTitle = document.title;
// Strip out the old label if there is one
if (originalTitle[0] === '(') {
originalTitle = originalTitle.slice(originalTitle.indexOf(' '));
}
if ((label + '').length > 0) {
document.title = '(' + label + ') ' + originalTitle;
} else {
document.title = originalTitle;
}
}
};
var drawBubble = function(context, label, colour) {
// automatic abbreviation for long (>2 digits) numbers
if (typeof label == 'number' && label > 99 && options.abbreviate) {
label = abbreviateNumber(label);
}
// bubble needs to be larger for double digits
var len = (label + '').length-1;
var width = options.width * r + (6 * r * len),
height = options.height * r;
var top = size - height,
left = size - width - r,
bottom = 16 * r,
right = 16 * r,
radius = 2 * r;
// webkit seems to render fonts lighter than firefox
context.font = (browser.webkit ? 'bold ' : '') + options.font;
context.fillStyle = options.background;
context.strokeStyle = options.background;
context.lineWidth = r;
// bubble
context.beginPath();
context.moveTo(left + radius, top);
context.quadraticCurveTo(left, top, left, top + radius);
context.lineTo(left, bottom - radius);
context.quadraticCurveTo(left, bottom, left + radius, bottom);
context.lineTo(right - radius, bottom);
context.quadraticCurveTo(right, bottom, right, bottom - radius);
context.lineTo(right, top + radius);
context.quadraticCurveTo(right, top, right - radius, top);
context.closePath();
context.fill();
// bottom shadow
context.beginPath();
context.strokeStyle = "rgba(0,0,0,0.3)";
context.moveTo(left + radius / 2.0, bottom);
context.lineTo(right - radius / 2.0, bottom);
context.stroke();
// label
context.fillStyle = options.colour;
context.textAlign = "right";
context.textBaseline = "top";
// unfortunately webkit/mozilla are a pixel different in text positioning
context.fillText(label, r === 2 ? 29 : 15, browser.mozilla ? 7*r : 6*r);
};
var refreshFavicon = function(){
// check support
if (!getCanvas().getContext) return;
setFaviconTag(getCanvas().toDataURL());
};
var abbreviateNumber = function(label) {
var metricPrefixes = [
['G', 1000000000],
['M', 1000000],
['k', 1000]
];
for(var i = 0; i < metricPrefixes.length; ++i) {
if (label >= metricPrefixes[i][1]) {
label = round(label / metricPrefixes[i][1]) + metricPrefixes[i][0];
break;
}
}
return label;
};
var round = function (value, precision) {
var number = new Number(value);
return number.toFixed(precision);
};
// public methods
Tinycon.setOptions = function(custom){
options = {};
for(var key in defaults){
options[key] = custom.hasOwnProperty(key) ? custom[key] : defaults[key];
}
return this;
};
Tinycon.setImage = function(url){
currentFavicon = url;
refreshFavicon();
return this;
};
Tinycon.setBubble = function(label, colour) {
label = label || '';
drawFavicon(label, colour);
return this;
};
Tinycon.reset = function(){
setFaviconTag(originalFavicon);
};
Tinycon.setOptions(defaults);
if(typeof define === 'function' && define.amd) {
define(Tinycon);
} else if (typeof module !== 'undefined') {
module.exports = Tinycon;
} else {
window.Tinycon = Tinycon;
}
})();
| {'content_hash': 'a4774030777742647c685ca79bf0fd1a', 'timestamp': '', 'source': 'github', 'line_count': 278, 'max_line_length': 100, 'avg_line_length': 24.553956834532375, 'alnum_prop': 0.6340462935833577, 'repo_name': 'lcnbala/tinycon', 'id': '2b5795fc0ca4018a45d7101b4e6fa04c32edda7c', 'size': '6997', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'tinycon.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '7288'}]} |
package cz.abclinuxu.datoveschranky.common.impl;
import java.io.Serializable;
import java.security.KeyStore;
/**
*
* Konfigurace připojení k ISDS.
*
* @author Vaclav Rosecky <xrosecky 'at' gmail 'dot' com>
*/
public class Config implements Serializable {
private static final long serialVersionUID = 3L;
/**
* URL testovacího provozu
*/
@Deprecated
public static final String TEST_URL = "ws1.czebox.cz"; // was ws1.czebox.cz
/**
* URL produkčního prostředí
*/
@Deprecated
public static final String PRODUCTION_URL = "ws1.mojedatovaschranka.cz"; // was ws1.mojedatovaschranka.cz
private final DataBoxEnvironment dataBoxEnvironment;
// private final String url;
private final KeyStore keyStore;
/**
* Vytvoří konfiguraci s daným URL a s KeyStore načteným z resources.
* Konstruktor je určen pro testovací účely, pro realné nasazení použijte
* vlastní keyStore.
*
* @see Config#constructor((String, KeyStore) konstruktor Config.
*
* @param servURL URL služby (TEST_URL či PRODUCTION_URL)
*
*/
@Deprecated
public Config(String servURL) {
if (servURL.equals(TEST_URL)) {
this.dataBoxEnvironment = DataBoxEnvironment.TEST;
} else if (servURL.equals(PRODUCTION_URL)) {
this.dataBoxEnvironment = DataBoxEnvironment.PRODUCTION;
} else {
throw new IllegalArgumentException("servURL");
}
this.keyStore = Utils.createTrustStore();
}
public Config(DataBoxEnvironment dbe) {
this.dataBoxEnvironment = dbe;
this.keyStore = Utils.createTrustStore();
}
/**
* Vytvoří konfiguraci s daným URL a příslušným klíči
*
* @param servURL URL služby (TEST_URL či PRODUCTION_URL)
* @param keys instance třídy KeyStore, která obsahuje certifikáty
* nutné pro přihlášení do ISDS, certifikáty, kterými je podepsána obálka
* zprávy a certifikáty časových razítek.
*
*/
@Deprecated
public Config(String servURL, KeyStore keys) {
if (servURL.equals(TEST_URL)) {
this.dataBoxEnvironment = DataBoxEnvironment.TEST;
} else if (servURL.equals(PRODUCTION_URL)) {
this.dataBoxEnvironment = DataBoxEnvironment.PRODUCTION;
} else {
throw new IllegalArgumentException("servURL");
}
this.keyStore = keys;
}
public String getServiceURL() {
// return "https://" + url + "/cert/DS/"; // was "/DS/"
return "https://" + dataBoxEnvironment.basicURL() + "/DS/";
}
public String getServiceURLClientCert() {
return "https://" + dataBoxEnvironment.clientCertURL() + "/cert/DS/";
}
@Deprecated
public String getLoginScope() {
return "login." + dataBoxEnvironment.basicURL();
}
public KeyStore getKeyStore() {
return keyStore;
}
}
| {'content_hash': 'c652c3f54d61a00e1c38063bb3937d3d', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 109, 'avg_line_length': 31.29787234042553, 'alnum_prop': 0.6390210740992522, 'repo_name': 'xrosecky/JAVA_ISDS', 'id': 'ec00655a2f09c9d2f4a447f6162a1424dd9dae96', 'size': '2993', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ISDSCommon/src/main/java/cz/abclinuxu/datoveschranky/common/impl/Config.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '225450'}]} |
package net.buycraft.plugin.bungeecord;
import net.buycraft.plugin.BuyCraftAPI;
import net.buycraft.plugin.IBuycraftPlatform;
import net.buycraft.plugin.UuidUtil;
import net.buycraft.plugin.data.QueuedPlayer;
import net.buycraft.plugin.data.responses.ServerInformation;
import net.buycraft.plugin.execution.placeholder.PlaceholderManager;
import net.buycraft.plugin.execution.strategy.CommandExecutor;
import net.buycraft.plugin.platform.NoBlocking;
import net.buycraft.plugin.platform.PlatformInformation;
import net.buycraft.plugin.platform.PlatformType;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
@NoBlocking
public class BungeeCordBuycraftPlatform implements IBuycraftPlatform {
private final BuycraftPlugin plugin;
public BungeeCordBuycraftPlatform(BuycraftPlugin plugin) {
this.plugin = plugin;
}
@Override
public BuyCraftAPI getApiClient() {
return plugin.getApiClient();
}
@Override
public PlaceholderManager getPlaceholderManager() {
return plugin.getPlaceholderManager();
}
@Override
public void dispatchCommand(String command) {
plugin.getProxy().getPluginManager().dispatchCommand(plugin.getProxy().getConsole(), command);
}
@Override
public void executeAsync(Runnable runnable) {
plugin.getProxy().getScheduler().runAsync(plugin, runnable);
}
@Override
public void executeAsyncLater(Runnable runnable, long time, TimeUnit unit) {
plugin.getProxy().getScheduler().schedule(plugin, runnable, time, unit);
}
@Override
public void executeBlocking(Runnable runnable) {
// BungeeCord has no concept of "blocking"
executeAsync(runnable);
}
@Override
public void executeBlockingLater(Runnable runnable, long time, TimeUnit unit) {
// BungeeCord has no concept of "blocking"
executeAsyncLater(runnable, time, unit);
}
private ProxiedPlayer getPlayer(QueuedPlayer player) {
if (player.getUuid() != null && plugin.getProxy().getConfig().isOnlineMode()) {
return plugin.getProxy().getPlayer(UuidUtil.mojangUuidToJavaUuid(player.getUuid()));
}
return plugin.getProxy().getPlayer(player.getName());
}
@Override
public boolean isPlayerOnline(QueuedPlayer player) {
return getPlayer(player) != null;
}
@Override
public int getFreeSlots(QueuedPlayer player) {
return 0; // Bungee has no concept of an inventory
}
@Override
public void log(Level level, String message) {
plugin.getLogger().log(level, message);
}
@Override
public void log(Level level, String message, Throwable throwable) {
plugin.getLogger().log(level, message, throwable);
}
@Override
public CommandExecutor getExecutor() {
return plugin.getCommandExecutor();
}
@Override
public PlatformInformation getPlatformInformation() {
return new PlatformInformation(PlatformType.BUNGEECORD, plugin.getProxy().getVersion());
}
@Override
public String getPluginVersion() {
return plugin.getDescription().getVersion();
}
@Override
public ServerInformation getServerInformation() {
return plugin.getServerInformation();
}
}
| {'content_hash': 'ebb8761c9f04b2f13aa1f92ada70249c', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 102, 'avg_line_length': 30.779816513761467, 'alnum_prop': 0.7129657228017884, 'repo_name': 'BuycraftPlugin/BuycraftX', 'id': 'd91e12b96a958b706173a094d6624adc08db1990', 'size': '3355', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bungeecord/src/main/java/net/buycraft/plugin/bungeecord/BungeeCordBuycraftPlatform.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '443595'}, {'name': 'Shell', 'bytes': '159'}]} |
#pragma once
#include <thrust/detail/config.h>
// the purpose of this header is to #include the reduce_by_key.h header
// of the sequential, host, and device systems. It should be #included in any
// code which uses adl to dispatch reduce_by_key
#include <thrust/system/detail/sequential/reduce_by_key.h>
#define __THRUST_HOST_SYSTEM_REDUCE_BY_KEY_HEADER <__THRUST_HOST_SYSTEM_ROOT/detail/reduce_by_key.h>
#include __THRUST_HOST_SYSTEM_REDUCE_BY_KEY_HEADER
#undef __THRUST_HOST_SYSTEM_REDUCE_BY_KEY_HEADER
#define __THRUST_DEVICE_SYSTEM_REDUCE_BY_KEY_HEADER <__THRUST_DEVICE_SYSTEM_ROOT/detail/reduce_by_key.h>
#include __THRUST_DEVICE_SYSTEM_REDUCE_BY_KEY_HEADER
#undef __THRUST_DEVICE_SYSTEM_REDUCE_BY_KEY_HEADER
| {'content_hash': 'a57008f23ca0b9377220bbc34f11fd89', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 104, 'avg_line_length': 36.15, 'alnum_prop': 0.7607192254495159, 'repo_name': 'GrimDerp/thrust', 'id': '0ce1c78ec9bb200630155ffaabdc72513d0786b3', 'size': '1339', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'thrust/system/detail/adl/reduce_by_key.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '184530'}, {'name': 'C++', 'bytes': '3967703'}, {'name': 'Cuda', 'bytes': '3007600'}, {'name': 'Python', 'bytes': '48614'}]} |
from sys import argv
# getting the command line arguments
script, filename = argv
# printing some text
print "We're going to erase %r." % filename
print "If you do not want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
# asking for confirmation
raw_input("?")
# opening the file defined on command line
print "Opening the file..."
target = open(filename, 'w')
# following not necessery, open() does truncate
# truncating the file
#print "Truncating the file..."
#target.truncate()
# printing
print "Now I'm going to ask you for three lines."
# input some text from command line
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
# printing
print "I'm going to write these to the file."
# writing them with newlines after to the file
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
# closing the file
print "And finally, we close it."
target.close()
| {'content_hash': '461ed2957eb3dea67a2939d44d7d4e68', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 56, 'avg_line_length': 24.342105263157894, 'alnum_prop': 0.6972972972972973, 'repo_name': '1uk/LPTHW', 'id': '62f5b47c5a210446a944fd4412c0b291dc5c975e', 'size': '962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ex16.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '28466'}]} |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Popover = factory());
})(this, (function () { 'use strict';
/**
* Shortcut for `Object.assign()` static method.
* @param {Record<string, any>} obj a target object
* @param {Record<string, any>} source a source object
*/
const ObjectAssign = (obj, source) => Object.assign(obj, source);
/**
* Utility to focus an `HTMLElement` target.
*
* @param {HTMLElement | Element} element is the target
*/
// @ts-ignore -- `Element`s resulted from querySelector can focus too
const focus = (element) => element.focus();
/**
* Returns the `document` or the `#document` element.
* @see https://github.com/floating-ui/floating-ui
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {Document}
*/
function getDocument(node) {
if (node instanceof HTMLElement) return node.ownerDocument;
if (node instanceof Window) return node.document;
return window.document;
}
/**
* A global array of possible `ParentNode`.
*/
const parentNodes = [Document, Node, Element, HTMLElement];
/**
* A global array with `Element` | `HTMLElement`.
*/
const elementNodes = [Element, HTMLElement];
/**
* Utility to check if target is typeof `HTMLElement`, `Element`, `Node`
* or find one that matches a selector.
*
* @param {HTMLElement | Element | string} selector the input selector or target element
* @param {(HTMLElement | Element | Node | Document)=} parent optional node to look into
* @return {(HTMLElement | Element)?} the `HTMLElement` or `querySelector` result
*/
function querySelector(selector, parent) {
const selectorIsString = typeof selector === 'string';
const lookUp = parent && parentNodes.some((x) => parent instanceof x)
? parent : getDocument();
if (!selectorIsString && elementNodes.some((x) => selector instanceof x)) {
return selector;
}
// @ts-ignore -- `ShadowRoot` is also a node
return selectorIsString ? lookUp.querySelector(selector) : null;
}
/** @type {Map<string, Map<HTMLElement | Element, Record<string, any>>>} */
const componentData = new Map();
/**
* An interface for web components background data.
* @see https://github.com/thednp/bootstrap.native/blob/master/src/components/base-component.js
*/
const Data = {
/**
* Sets web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @param {Record<string, any>} instance the component instance
*/
set: (target, component, instance) => {
const element = querySelector(target);
if (!element) return;
if (!componentData.has(component)) {
componentData.set(component, new Map());
}
const instanceMap = componentData.get(component);
// @ts-ignore - not undefined, but defined right above
instanceMap.set(element, instance);
},
/**
* Returns all instances for specified component.
* @param {string} component the component's name or a unique key
* @returns {Map<HTMLElement | Element, Record<string, any>>?} all the component instances
*/
getAllFor: (component) => {
const instanceMap = componentData.get(component);
return instanceMap || null;
},
/**
* Returns the instance associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
* @returns {Record<string, any>?} the instance
*/
get: (target, component) => {
const element = querySelector(target);
const allForC = Data.getAllFor(component);
const instance = element && allForC && allForC.get(element);
return instance || null;
},
/**
* Removes web components data.
* @param {HTMLElement | Element | string} target target element
* @param {string} component the component's name or a unique key
*/
remove: (target, component) => {
const element = querySelector(target);
const instanceMap = componentData.get(component);
if (!instanceMap || !element) return;
instanceMap.delete(element);
if (instanceMap.size === 0) {
componentData.delete(component);
}
},
};
/**
* An alias for `Data.get()`.
* @type {SHORTER.getInstance<any>}
*/
const getInstance = (target, component) => Data.get(target, component);
/**
* Global namespace for most components `toggle` option.
*/
const dataBsToggle = 'data-bs-toggle';
/** @type {string} */
const popoverString = 'popover';
/** @type {string} */
const popoverComponent = 'Popover';
/** @type {string} */
const tooltipString = 'tooltip';
/**
* Returns a template for Popover / Tooltip.
*
* @param {string} tipType the expected markup type
* @returns {string} the template markup
*/
function getTipTemplate(tipType) {
const isTooltip = tipType === tooltipString;
const bodyClass = isTooltip ? `${tipType}-inner` : `${tipType}-body`;
const header = !isTooltip ? `<h3 class="${tipType}-header"></h3>` : '';
const arrow = `<div class="${tipType}-arrow"></div>`;
const body = `<div class="${bodyClass}"></div>`;
return `<div class="${tipType}" role="${tooltipString}">${header + arrow + body}</div>`;
}
/**
* Checks if an element is an `<svg>` (or any type of SVG element),
* `<img>` or `<video>`.
*
* *Tooltip* / *Popover* works different with media elements.
* @param {any} element the target element
* @returns {boolean} the query result
*/
const isMedia = (element) => element
&& [SVGElement, HTMLImageElement, HTMLVideoElement]
.some((mediaType) => element instanceof mediaType);
/**
* Returns the `document.documentElement` or the `<html>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLHtmlElement}
*/
function getDocumentElement(node) {
return getDocument(node).documentElement;
}
/**
* Checks if a page is Right To Left.
* @param {(HTMLElement | Element)=} node the target
* @returns {boolean} the query result
*/
const isRTL = (node) => getDocumentElement(node).dir === 'rtl';
/**
* Shortcut for `window.getComputedStyle(element).propertyName`
* static method.
*
* * If `element` parameter is not an `HTMLElement`, `getComputedStyle`
* throws a `ReferenceError`.
*
* @param {HTMLElement | Element} element target
* @param {string} property the css property
* @return {string} the css property value
*/
function getElementStyle(element, property) {
const computedStyle = getComputedStyle(element);
// @ts-ignore -- must use camelcase strings,
// or non-camelcase strings with `getPropertyValue`
return property in computedStyle ? computedStyle[property] : '';
}
/**
* Returns the bounding client rect of a target `HTMLElement`.
*
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element event.target
* @param {boolean=} includeScale when *true*, the target scale is also computed
* @returns {SHORTER.BoundingClientRect} the bounding client rect object
*/
function getBoundingClientRect(element, includeScale) {
const {
width, height, top, right, bottom, left,
} = element.getBoundingClientRect();
let scaleX = 1;
let scaleY = 1;
if (includeScale && element instanceof HTMLElement) {
const { offsetWidth, offsetHeight } = element;
scaleX = offsetWidth > 0 ? Math.round(width) / offsetWidth || 1 : 1;
scaleY = offsetHeight > 0 ? Math.round(height) / offsetHeight || 1 : 1;
}
return {
width: width / scaleX,
height: height / scaleY,
top: top / scaleY,
right: right / scaleX,
bottom: bottom / scaleY,
left: left / scaleX,
x: left / scaleX,
y: top / scaleY,
};
}
/**
* Returns an `{x,y}` object with the target
* `HTMLElement` / `Node` scroll position.
*
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element | Window} element target node / element
* @returns {{x: number, y: number}} the scroll tuple
*/
function getNodeScroll(element) {
const isWin = 'scrollX' in element;
const x = isWin ? element.scrollX : element.scrollLeft;
const y = isWin ? element.scrollY : element.scrollTop;
return { x, y };
}
/**
* Checks if a target `HTMLElement` is affected by scale.
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement} element target
* @returns {boolean} the query result
*/
function isScaledElement(element) {
const { width, height } = getBoundingClientRect(element);
const { offsetWidth, offsetHeight } = element;
return Math.round(width) !== offsetWidth
|| Math.round(height) !== offsetHeight;
}
/**
* Returns the rect relative to an offset parent.
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element target
* @param {HTMLElement | Element | Window} offsetParent the container / offset parent
* @param {{x: number, y: number}} scroll
* @returns {SHORTER.OffsetRect}
*/
function getRectRelativeToOffsetParent(element, offsetParent, scroll) {
const isParentAnElement = offsetParent instanceof HTMLElement;
const rect = getBoundingClientRect(element, isParentAnElement && isScaledElement(offsetParent));
const offsets = { x: 0, y: 0 };
if (isParentAnElement) {
const offsetRect = getBoundingClientRect(offsetParent, true);
offsets.x = offsetRect.x + offsetParent.clientLeft;
offsets.y = offsetRect.y + offsetParent.clientTop;
}
return {
x: rect.left + scroll.x - offsets.x,
y: rect.top + scroll.y - offsets.y,
width: rect.width,
height: rect.height,
};
}
/**
* Shortcut for multiple uses of `HTMLElement.style.propertyName` method.
* @param {HTMLElement | Element} element target element
* @param {Partial<CSSStyleDeclaration>} styles attribute value
*/
// @ts-ignore
const setElementStyle = (element, styles) => { ObjectAssign(element.style, styles); };
/** @type {Record<string, string>} */
var tipClassPositions = {
top: 'top',
bottom: 'bottom',
left: 'start',
right: 'end',
};
/**
* Style popovers and tooltips.
* @param {BSN.Tooltip | BSN.Popover} self the `Popover` / `Tooltip` instance
* @param {PointerEvent=} e event object
*/
function styleTip(self, e) {
const tipClasses = /\b(top|bottom|start|end)+/;
const {
element, tooltip, options, arrow, offsetParent,
} = self;
const tipPositions = { ...tipClassPositions };
// reset tooltip style (top: 0, left: 0 works best)
setElementStyle(tooltip, { top: '0px', left: '0px', right: '' });
// @ts-ignore
const isPopover = self.name === popoverComponent;
const tipWidth = tooltip.offsetWidth;
const tipHeight = tooltip.offsetHeight;
const RTL = isRTL(element);
if (RTL) {
tipPositions.left = 'end';
tipPositions.right = 'start';
}
const documentElement = getDocumentElement(element);
const windowWidth = documentElement.clientWidth;
const windowHeight = documentElement.clientHeight;
const { container } = options;
let { placement } = options;
const {
left: parentLeft, right: parentRight, top: parentTop,
} = getBoundingClientRect(container, true);
const parentWidth = container.clientWidth;
const scrollbarWidth = Math.abs(parentWidth - container.offsetWidth);
const parentPosition = getElementStyle(container, 'position');
// const absoluteParent = parentPosition === 'absolute';
const fixedParent = parentPosition === 'fixed';
const staticParent = parentPosition === 'static';
const stickyParent = parentPosition === 'sticky';
const isSticky = stickyParent && parentTop === parseFloat(getElementStyle(container, 'top'));
// const absoluteTarget = getElementStyle(element, 'position') === 'absolute';
// const stickyFixedParent = ['sticky', 'fixed'].includes(parentPosition);
const leftBoundry = RTL && fixedParent ? scrollbarWidth : 0;
const rightBoundry = fixedParent ? parentWidth + parentLeft + (RTL ? scrollbarWidth : 0)
: parentWidth + parentLeft + (windowWidth - parentRight) - 1;
const {
width: elemWidth,
height: elemHeight,
left: elemRectLeft,
right: elemRectRight,
top: elemRectTop,
} = getBoundingClientRect(element, true);
const scroll = getNodeScroll(offsetParent);
const { x, y } = getRectRelativeToOffsetParent(element, offsetParent, scroll);
// reset arrow style
setElementStyle(arrow, { top: '', left: '', right: '' });
let topPosition;
let leftPosition;
let rightPosition;
let arrowTop;
let arrowLeft;
let arrowRight;
const arrowWidth = arrow.offsetWidth || 0;
const arrowHeight = arrow.offsetHeight || 0;
const arrowAdjust = arrowWidth / 2;
// check placement
let topExceed = elemRectTop - tipHeight - arrowHeight < 0;
let bottomExceed = elemRectTop + tipHeight + elemHeight
+ arrowHeight >= windowHeight;
let leftExceed = elemRectLeft - tipWidth - arrowWidth < leftBoundry;
let rightExceed = elemRectLeft + tipWidth + elemWidth
+ arrowWidth >= rightBoundry;
const horizontal = ['left', 'right'];
const vertical = ['top', 'bottom'];
topExceed = horizontal.includes(placement)
? elemRectTop + elemHeight / 2 - tipHeight / 2 - arrowHeight < 0
: topExceed;
bottomExceed = horizontal.includes(placement)
? elemRectTop + tipHeight / 2 + elemHeight / 2 + arrowHeight >= windowHeight
: bottomExceed;
leftExceed = vertical.includes(placement)
? elemRectLeft + elemWidth / 2 - tipWidth / 2 < leftBoundry
: leftExceed;
rightExceed = vertical.includes(placement)
? elemRectLeft + tipWidth / 2 + elemWidth / 2 >= rightBoundry
: rightExceed;
// recompute placement
// first, when both left and right limits are exceeded, we fall back to top|bottom
placement = (horizontal.includes(placement)) && leftExceed && rightExceed ? 'top' : placement;
placement = placement === 'top' && topExceed ? 'bottom' : placement;
placement = placement === 'bottom' && bottomExceed ? 'top' : placement;
placement = placement === 'left' && leftExceed ? 'right' : placement;
placement = placement === 'right' && rightExceed ? 'left' : placement;
// update tooltip/popover class
if (!tooltip.className.includes(placement)) {
tooltip.className = tooltip.className.replace(tipClasses, tipPositions[placement]);
}
// compute tooltip / popover coordinates
if (horizontal.includes(placement)) { // secondary|side positions
if (placement === 'left') { // LEFT
leftPosition = x - tipWidth - (isPopover ? arrowWidth : 0);
} else { // RIGHT
leftPosition = x + elemWidth + (isPopover ? arrowWidth : 0);
}
// adjust top and arrow
if (topExceed) {
topPosition = y;
topPosition += (isSticky ? -parentTop - scroll.y : 0);
arrowTop = elemHeight / 2 - arrowWidth;
} else if (bottomExceed) {
topPosition = y - tipHeight + elemHeight;
topPosition += (isSticky ? -parentTop - scroll.y : 0);
arrowTop = tipHeight - elemHeight / 2 - arrowWidth;
} else {
topPosition = y - tipHeight / 2 + elemHeight / 2;
topPosition += (isSticky ? -parentTop - scroll.y : 0);
arrowTop = tipHeight / 2 - arrowHeight / 2;
}
} else if (vertical.includes(placement)) {
if (e && isMedia(element)) {
let eX = 0;
let eY = 0;
if (staticParent) {
eX = e.pageX;
eY = e.pageY;
} else { // fixedParent | stickyParent
eX = e.clientX - parentLeft + (fixedParent ? scroll.x : 0);
eY = e.clientY - parentTop + (fixedParent ? scroll.y : 0);
}
// some weird RTL bug
eX -= RTL && fixedParent && scrollbarWidth ? scrollbarWidth : 0;
if (placement === 'top') {
topPosition = eY - tipHeight - arrowWidth;
} else {
topPosition = eY + arrowWidth;
}
// adjust (left | right) and also the arrow
if (e.clientX - tipWidth / 2 < leftBoundry) {
leftPosition = 0;
arrowLeft = eX - arrowAdjust;
} else if (e.clientX + tipWidth / 2 > rightBoundry) {
leftPosition = 'auto';
rightPosition = 0;
arrowRight = rightBoundry - eX - arrowAdjust;
arrowRight -= fixedParent ? parentLeft + (RTL ? scrollbarWidth : 0) : 0;
// normal top/bottom
} else {
leftPosition = eX - tipWidth / 2;
arrowLeft = tipWidth / 2 - arrowAdjust;
}
} else {
if (placement === 'top') {
topPosition = y - tipHeight - (isPopover ? arrowHeight : 0);
} else { // BOTTOM
topPosition = y + elemHeight + (isPopover ? arrowHeight : 0);
}
// adjust left | right and also the arrow
if (leftExceed) {
leftPosition = 0;
arrowLeft = x + elemWidth / 2 - arrowAdjust;
} else if (rightExceed) {
leftPosition = 'auto';
rightPosition = 0;
arrowRight = elemWidth / 2 + rightBoundry - elemRectRight - arrowAdjust;
} else {
leftPosition = x - tipWidth / 2 + elemWidth / 2;
arrowLeft = tipWidth / 2 - arrowAdjust;
}
}
}
// apply style to tooltip/popover
setElementStyle(tooltip, {
top: `${topPosition}px`,
left: leftPosition === 'auto' ? leftPosition : `${leftPosition}px`,
right: rightPosition !== undefined ? `${rightPosition}px` : '',
});
// update arrow placement
if (arrow instanceof HTMLElement) {
if (arrowTop !== undefined) {
arrow.style.top = `${arrowTop}px`;
}
if (arrowLeft !== undefined) {
arrow.style.left = `${arrowLeft}px`;
} else if (arrowRight !== undefined) {
arrow.style.right = `${arrowRight}px`;
}
}
}
const tooltipDefaults = {
/** @type {string} */
template: getTipTemplate(tooltipString),
/** @type {string?} */
title: null, // string
/** @type {string?} */
customClass: null, // string | null
/** @type {string} */
trigger: 'hover focus',
/** @type {string?} */
placement: 'top', // string
/** @type {((c:string)=>string)?} */
sanitizeFn: null, // function
/** @type {boolean} */
animation: true, // bool
/** @type {number} */
delay: 200, // number
/** @type {(HTMLElement | Element)?} */
container: null,
};
/**
* A global namespace for aria-describedby.
* @type {string}
*/
const ariaDescribedBy = 'aria-describedby';
/**
* A global namespace for `click` event.
* @type {string}
*/
const mouseclickEvent = 'click';
/**
* A global namespace for `mousedown` event.
* @type {string}
*/
const mousedownEvent = 'mousedown';
/**
* A global namespace for `mouseenter` event.
* @type {string}
*/
const mouseenterEvent = 'mouseenter';
/**
* A global namespace for `mouseleave` event.
* @type {string}
*/
const mouseleaveEvent = 'mouseleave';
/**
* A global namespace for `mousemove` event.
* @type {string}
*/
const mousemoveEvent = 'mousemove';
/**
* A global namespace for `focus` event.
* @type {string}
*/
const focusEvent = 'focus';
/**
* A global namespace for `focusin` event.
* @type {string}
*/
const focusinEvent = 'focusin';
/**
* A global namespace for `focusout` event.
* @type {string}
*/
const focusoutEvent = 'focusout';
/**
* A global namespace for `hover` event.
* @type {string}
*/
const mousehoverEvent = 'hover';
/**
* A global namespace for `scroll` event.
* @type {string}
*/
const scrollEvent = 'scroll';
/**
* A global namespace for `resize` event.
* @type {string}
*/
const resizeEvent = 'resize';
/**
* A global namespace for `touchstart` event.
* @type {string}
*/
const touchstartEvent = 'touchstart';
/**
* Shortcut for `HTMLElement.setAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
* @param {string} value attribute value
*/
const setAttribute = (element, attribute, value) => element.setAttribute(attribute, value);
/**
* Shortcut for `HTMLElement.getAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const getAttribute = (element, attribute) => element.getAttribute(attribute);
/**
* Shortcut for `HTMLElement.removeAttribute()` method.
* @param {HTMLElement | Element} element target element
* @param {string} attribute attribute name
*/
const removeAttribute = (element, attribute) => element.removeAttribute(attribute);
/**
* Returns the `Window` object of a target node.
* @see https://github.com/floating-ui/floating-ui
*
* @param {(Node | HTMLElement | Element | Window)=} node target node
* @returns {globalThis}
*/
function getWindow(node) {
if (node == null) {
return window;
}
if (!(node instanceof Window)) {
const { ownerDocument } = node;
return ownerDocument ? ownerDocument.defaultView || window : window;
}
// @ts-ignore
return node;
}
/**
* Returns the `document.body` or the `<body>` element.
*
* @param {(Node | HTMLElement | Element | globalThis)=} node
* @returns {HTMLElement | HTMLBodyElement}
*/
function getDocumentBody(node) {
return getDocument(node).body;
}
/**
* A global namespace for 'transitionDuration' string.
* @type {string}
*/
const transitionDuration = 'transitionDuration';
/**
* A global namespace for:
* * `transitionProperty` string for Firefox,
* * `transition` property for all other browsers.
*
* @type {string}
*/
const transitionProperty = 'transitionProperty';
/**
* Utility to get the computed `transitionDuration`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDuration(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const durationValue = getElementStyle(element, transitionDuration);
const durationScale = durationValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(durationValue) * durationScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Shortcut for `HTMLElement.closest` method which also works
* with children of `ShadowRoot`. The order of the parameters
* is intentional since they're both required.
*
* @see https://stackoverflow.com/q/54520554/803358
*
* @param {HTMLElement | Element} element Element to look into
* @param {string} selector the selector name
* @return {(HTMLElement | Element)?} the query result
*/
function closest(element, selector) {
return element ? (element.closest(selector)
// @ts-ignore -- break out of `ShadowRoot`
|| closest(element.getRootNode().host, selector)) : null;
}
/**
* Add class to `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to add
*/
function addClass(element, classNAME) {
element.classList.add(classNAME);
}
/**
* Check class in `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to check
* @return {boolean}
*/
function hasClass(element, classNAME) {
return element.classList.contains(classNAME);
}
/**
* Remove class from `HTMLElement.classList`.
*
* @param {HTMLElement | Element} element target
* @param {string} classNAME to remove
*/
function removeClass(element, classNAME) {
element.classList.remove(classNAME);
}
/**
* Add eventListener to an `Element` | `HTMLElement` | `Document` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function on(element, eventName, handler, options) {
const ops = options || false;
element.addEventListener(eventName, handler, ops);
}
/**
* Remove eventListener from an `Element` | `HTMLElement` | `Document` | `Window` target.
*
* @param {HTMLElement | Element | Document | Window} element event.target
* @param {string} eventName event.type
* @param {EventListenerObject['handleEvent']} handler callback
* @param {(EventListenerOptions | boolean)=} options other event options
*/
function off(element, eventName, handler, options) {
const ops = options || false;
element.removeEventListener(eventName, handler, ops);
}
// @ts-ignore
const { userAgentData: uaDATA } = navigator;
/**
* A global namespace for `userAgentData` object.
*/
const userAgentData = uaDATA;
const { userAgent: userAgentString } = navigator;
/**
* A global namespace for `navigator.userAgent` string.
*/
const userAgent = userAgentString;
const appleBrands = /(iPhone|iPod|iPad)/;
/**
* A global `boolean` for Apple browsers.
* @type {boolean}
*/
const isApple = !userAgentData ? appleBrands.test(userAgent)
: userAgentData.brands.some((/** @type {Record<string, any>} */x) => appleBrands.test(x.brand));
/**
* Shortcut for the `Element.dispatchEvent(Event)` method.
*
* @param {HTMLElement | Element} element is the target
* @param {Event} event is the `Event` object
*/
const dispatchEvent = (element, event) => element.dispatchEvent(event);
/**
* A global namespace for most scroll event listeners.
* @type {Partial<AddEventListenerOptions>}
*/
const passiveHandler = { passive: true };
/**
* A global namespace for 'transitionend' string.
* @type {string}
*/
const transitionEndEvent = 'transitionend';
/**
* A global namespace for 'transitionDelay' string.
* @type {string}
*/
const transitionDelay = 'transitionDelay';
/**
* Utility to get the computed `transitionDelay`
* from Element in miliseconds.
*
* @param {HTMLElement | Element} element target
* @return {number} the value in miliseconds
*/
function getElementTransitionDelay(element) {
const propertyValue = getElementStyle(element, transitionProperty);
const delayValue = getElementStyle(element, transitionDelay);
const delayScale = delayValue.includes('ms') ? 1 : 1000;
const duration = propertyValue && propertyValue !== 'none'
? parseFloat(delayValue) * delayScale : 0;
return !Number.isNaN(duration) ? duration : 0;
}
/**
* Utility to make sure callbacks are consistently
* called when transition ends.
*
* @param {HTMLElement | Element} element target
* @param {EventListener} handler `transitionend` callback
*/
function emulateTransitionEnd(element, handler) {
let called = 0;
const endEvent = new Event(transitionEndEvent);
const duration = getElementTransitionDuration(element);
const delay = getElementTransitionDelay(element);
if (duration) {
/**
* Wrap the handler in on -> off callback
* @param {TransitionEvent} e Event object
*/
const transitionEndWrapper = (e) => {
if (e.target === element) {
handler.apply(element, [e]);
off(element, transitionEndEvent, transitionEndWrapper);
called = 1;
}
};
on(element, transitionEndEvent, transitionEndWrapper);
setTimeout(() => {
if (!called) element.dispatchEvent(endEvent);
}, duration + delay + 17);
} else {
handler.apply(element, [endEvent]);
}
}
/** @type {Map<HTMLElement | Element, any>} */
const TimeCache = new Map();
/**
* An interface for one or more `TimerHandler`s per `Element`.
* @see https://github.com/thednp/navbar.js/
*/
const Timer = {
/**
* Sets a new timeout timer for an element, or element -> key association.
* @param {HTMLElement | Element | string} target target element
* @param {ReturnType<TimerHandler>} callback the callback
* @param {number} delay the execution delay
* @param {string=} key a unique
*/
set: (target, callback, delay, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
if (!TimeCache.has(element)) {
TimeCache.set(element, new Map());
}
const keyTimers = TimeCache.get(element);
keyTimers.set(key, setTimeout(callback, delay));
} else {
TimeCache.set(element, setTimeout(callback, delay));
}
},
/**
* Returns the timer associated with the target.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique
* @returns {number?} the timer
*/
get: (target, key) => {
const element = querySelector(target);
if (!element) return null;
const keyTimers = TimeCache.get(element);
if (key && key.length && keyTimers && keyTimers.get) {
return keyTimers.get(key) || null;
}
return keyTimers || null;
},
/**
* Clears the element's timer.
* @param {HTMLElement | Element | string} target target element
* @param {string=} key a unique key
*/
clear: (target, key) => {
const element = querySelector(target);
if (!element) return;
if (key && key.length) {
const keyTimers = TimeCache.get(element);
if (keyTimers && keyTimers.get) {
clearTimeout(keyTimers.get(key));
keyTimers.delete(key);
if (keyTimers.size === 0) {
TimeCache.delete(element);
}
}
} else {
clearTimeout(TimeCache.get(element));
TimeCache.delete(element);
}
},
};
let elementUID = 1;
const elementIDMap = new Map();
/**
* Returns a unique identifier for popover, tooltip, scrollspy.
*
* @param {HTMLElement | Element} element target element
* @param {string=} key predefined key
* @returns {number} an existing or new unique ID
*/
function getUID(element, key) {
elementUID += 1;
let elMap = elementIDMap.get(element);
let result = elementUID;
if (elMap) {
result = key && key.length && elMap.get && elMap.get(key)
? elMap.get(key) : elMap;
} else if (key && key.length) {
if (!elMap) {
elementIDMap.set(element, new Map());
elMap = elementIDMap.get(element);
}
elMap.set(key, result);
} else {
elementIDMap.set(element, result);
}
return result;
}
/**
* Returns a namespaced `CustomEvent` specific to each component.
* @param {string} EventType Event.type
* @param {Record<string, any>=} config Event.options | Event.properties
* @returns {SHORTER.OriginalEvent} a new namespaced event
*/
function OriginalEvent(EventType, config) {
const OriginalCustomEvent = new CustomEvent(EventType, {
cancelable: true, bubbles: true,
});
if (config instanceof Object) {
ObjectAssign(OriginalCustomEvent, config);
}
return OriginalCustomEvent;
}
/**
* Shortcut for `String.toLowerCase()`.
*
* @param {string} source input string
* @returns {string} lowercase output string
*/
const toLowerCase = (source) => source.toLowerCase();
/**
* Global namespace for `data-bs-title` attribute.
*/
const dataOriginalTitle = 'data-original-title';
/**
* Global namespace for most components `show` class.
*/
const showClass = 'show';
/** @type {string} */
const tooltipComponent = 'Tooltip';
/** @type {string} */
const modalString = 'modal';
/** @type {string} */
const offcanvasString = 'offcanvas';
/**
* Global namespace for most components `fade` class.
*/
const fadeClass = 'fade';
/**
* Append an existing `Element` to Popover / Tooltip component or HTML
* markup string to be parsed & sanitized to be used as popover / tooltip content.
*
* @param {HTMLElement | Element} element target
* @param {HTMLElement | Element | string} content the `Element` to append / string
* @param {ReturnType<any>} sanitizeFn a function to sanitize string content
*/
function setHtml(element, content, sanitizeFn) {
if (typeof content === 'string' && !content.length) return;
if (typeof content === 'string') {
let dirty = content.trim(); // fixing #233
if (typeof sanitizeFn === 'function') dirty = sanitizeFn(dirty);
const domParser = new DOMParser();
const tempDocument = domParser.parseFromString(dirty, 'text/html');
const { body } = tempDocument;
const method = body.children.length ? 'innerHTML' : 'innerText';
// @ts-ignore
element[method] = body[method];
} else if (content instanceof HTMLElement) {
element.append(content);
}
}
/**
* Creates a new tooltip / popover.
*
* @param {BSN.Popover | BSN.Tooltip} self the `Popover` instance
*/
function createTip(self) {
const { id, element, options } = self;
const {
animation, customClass, sanitizeFn, placement, dismissible,
} = options;
let { title, content } = options;
const isTooltip = self.name === tooltipComponent;
const tipString = isTooltip ? tooltipString : popoverString;
const { template, btnClose } = options;
const tipPositions = { ...tipClassPositions };
if (isRTL(element)) {
tipPositions.left = 'end';
tipPositions.right = 'start';
}
// set initial popover class
const placementClass = `bs-${tipString}-${tipPositions[placement]}`;
// load template
/** @type {(HTMLElement | Element)?} */
let popoverTemplate;
if ([Element, HTMLElement].some((x) => template instanceof x)) {
popoverTemplate = template;
} else {
const htmlMarkup = getDocument(element).createElement('div');
setHtml(htmlMarkup, template, sanitizeFn);
popoverTemplate = htmlMarkup.firstElementChild;
}
// set popover markup
self.tooltip = popoverTemplate && popoverTemplate.cloneNode(true);
const { tooltip } = self;
// set id and role attributes
setAttribute(tooltip, 'id', id);
setAttribute(tooltip, 'role', tooltipString);
const bodyClass = isTooltip ? `${tooltipString}-inner` : `${popoverString}-body`;
const tooltipHeader = isTooltip ? null : querySelector(`.${popoverString}-header`, tooltip);
const tooltipBody = querySelector(`.${bodyClass}`, tooltip);
// set arrow and enable access for styleTip
self.arrow = querySelector(`.${tipString}-arrow`, tooltip);
// set dismissible button
if (dismissible) {
if (title) {
if (title instanceof HTMLElement) setHtml(title, btnClose, sanitizeFn);
else title += btnClose;
} else {
if (tooltipHeader) tooltipHeader.remove();
if (content instanceof HTMLElement) setHtml(content, btnClose, sanitizeFn);
else content += btnClose;
}
}
// fill the template with content from options / data attributes
// also sanitize title && content
if (!isTooltip) {
if (title && tooltipHeader) setHtml(tooltipHeader, title, sanitizeFn);
if (content && tooltipBody) setHtml(tooltipBody, content, sanitizeFn);
// @ts-ignore -- set btn
self.btn = querySelector('.btn-close', tooltip);
} else if (title && tooltipBody) setHtml(tooltipBody, title, sanitizeFn);
// set popover animation and placement
if (!hasClass(tooltip, tipString)) addClass(tooltip, tipString);
if (animation && !hasClass(tooltip, fadeClass)) addClass(tooltip, fadeClass);
if (customClass && !hasClass(tooltip, customClass)) {
addClass(tooltip, customClass);
}
if (!hasClass(tooltip, placementClass)) addClass(tooltip, placementClass);
}
/**
* @param {(HTMLElement | Element)?} tip target
* @param {HTMLElement | ParentNode} container parent container
* @returns {boolean}
*/
function isVisibleTip(tip, container) {
return tip instanceof HTMLElement && container.contains(tip);
}
/**
* Check if target is a `ShadowRoot`.
*
* @param {any} element target
* @returns {boolean} the query result
*/
const isShadowRoot = (element) => {
const OwnElement = getWindow(element).ShadowRoot;
return element instanceof OwnElement || element instanceof ShadowRoot;
};
/**
* Returns the `parentNode` also going through `ShadowRoot`.
* @see https://github.com/floating-ui/floating-ui
*
* @param {Node | HTMLElement | Element} node the target node
* @returns {Node | HTMLElement | Element} the apropriate parent node
*/
function getParentNode(node) {
if (node.nodeName === 'HTML') {
return node;
}
// this is a quicker (but less type safe) way to save quite some bytes from the bundle
return (
// @ts-ignore
node.assignedSlot // step into the shadow DOM of the parent of a slotted node
|| node.parentNode // @ts-ignore DOM Element detected
|| (isShadowRoot(node) ? node.host : null) // ShadowRoot detected
|| getDocumentElement(node) // fallback
);
}
/**
* Check if a target element is a `<table>`, `<td>` or `<th>`.
* @param {any} element the target element
* @returns {boolean} the query result
*/
const isTableElement = (element) => ['TABLE', 'TD', 'TH'].includes(element.tagName);
/**
* Checks if an element is an `HTMLElement`.
*
* @param {any} element the target object
* @returns {boolean} the query result
*/
const isHTMLElement = (element) => element instanceof HTMLElement;
/**
* Returns an `HTMLElement` to be used as default value for *options.container*
* for `Tooltip` / `Popover` components.
*
* When `getOffset` is *true*, it returns the `offsetParent` for tooltip/popover
* offsets computation similar to **floating-ui**.
* @see https://github.com/floating-ui/floating-ui
*
* @param {HTMLElement | Element} element the target
* @param {boolean=} getOffset when *true* it will return an `offsetParent`
* @returns {HTMLElement | HTMLBodyElement | Window | globalThis} the query result
*/
function getElementContainer(element, getOffset) {
const majorBlockTags = ['HTML', 'BODY'];
if (getOffset) {
/** @type {any} */
let { offsetParent } = element;
const win = getWindow(element);
// const { innerWidth } = getDocumentElement(element);
while (offsetParent && (isTableElement(offsetParent)
|| (isHTMLElement(offsetParent)
// we must count for both fixed & sticky
&& !['sticky', 'fixed'].includes(getElementStyle(offsetParent, 'position'))))) {
offsetParent = offsetParent.offsetParent;
}
if (!offsetParent || (offsetParent
&& (majorBlockTags.includes(offsetParent.tagName)
|| getElementStyle(offsetParent, 'position') === 'static'))) {
offsetParent = win;
}
return offsetParent;
}
/** @type {(HTMLElement)[]} */
const containers = [];
/** @type {any} */
let { parentNode } = element;
while (parentNode && !majorBlockTags.includes(parentNode.nodeName)) {
parentNode = getParentNode(parentNode);
if (!(isShadowRoot(parentNode) || !!parentNode.shadowRoot
|| isTableElement(parentNode))) {
containers.push(parentNode);
}
}
return containers.find((c, i) => {
if (getElementStyle(c, 'position') !== 'relative'
&& containers.slice(i + 1).every((r) => getElementStyle(r, 'position') === 'static')) {
return c;
}
return null;
}) || getDocumentBody(element);
}
/**
* The raw value or a given component option.
*
* @typedef {string | HTMLElement | Function | number | boolean | null} niceValue
*/
/**
* Utility to normalize component options
*
* @param {any} value the input value
* @return {niceValue} the normalized value
*/
function normalizeValue(value) {
if (value === 'true') { // boolean
return true;
}
if (value === 'false') { // boolean
return false;
}
if (!Number.isNaN(+value)) { // number
return +value;
}
if (value === '' || value === 'null') { // null
return null;
}
// string / function / HTMLElement / object
return value;
}
/**
* Shortcut for `Object.keys()` static method.
* @param {Record<string, any>} obj a target object
* @returns {string[]}
*/
const ObjectKeys = (obj) => Object.keys(obj);
/**
* Utility to normalize component options.
*
* @param {HTMLElement | Element} element target
* @param {Record<string, any>} defaultOps component default options
* @param {Record<string, any>} inputOps component instance options
* @param {string=} ns component namespace
* @return {Record<string, any>} normalized component options object
*/
function normalizeOptions(element, defaultOps, inputOps, ns) {
// @ts-ignore -- our targets are always `HTMLElement`
const data = { ...element.dataset };
/** @type {Record<string, any>} */
const normalOps = {};
/** @type {Record<string, any>} */
const dataOps = {};
const title = 'title';
ObjectKeys(data).forEach((k) => {
const key = ns && k.includes(ns)
? k.replace(ns, '').replace(/[A-Z]/, (match) => toLowerCase(match))
: k;
dataOps[key] = normalizeValue(data[k]);
});
ObjectKeys(inputOps).forEach((k) => {
inputOps[k] = normalizeValue(inputOps[k]);
});
ObjectKeys(defaultOps).forEach((k) => {
if (k in inputOps) {
normalOps[k] = inputOps[k];
} else if (k in dataOps) {
normalOps[k] = dataOps[k];
} else {
normalOps[k] = k === title
? getAttribute(element, title)
: defaultOps[k];
}
});
return normalOps;
}
var version = "4.1.0alpha3";
const Version = version;
/* Native JavaScript for Bootstrap 5 | Base Component
----------------------------------------------------- */
/** Returns a new `BaseComponent` instance. */
class BaseComponent {
/**
* @param {HTMLElement | Element | string} target `Element` or selector string
* @param {BSN.ComponentOptions=} config component instance options
*/
constructor(target, config) {
const self = this;
const element = querySelector(target);
if (!element) {
throw Error(`${self.name} Error: "${target}" is not a valid selector.`);
}
/** @static @type {BSN.ComponentOptions} */
self.options = {};
const prevInstance = Data.get(element, self.name);
if (prevInstance) prevInstance.dispose();
/** @type {HTMLElement | Element} */
self.element = element;
if (self.defaults && Object.keys(self.defaults).length) {
self.options = normalizeOptions(element, self.defaults, (config || {}), 'bs');
}
Data.set(element, self.name, self);
}
/* eslint-disable */
/** @static */
get version() { return Version; }
/* eslint-enable */
/** @static */
get name() { return this.constructor.name; }
/** @static */
// @ts-ignore
get defaults() { return this.constructor.defaults; }
/**
* Removes component from target element;
*/
dispose() {
const self = this;
Data.remove(self.element, self.name);
// @ts-ignore
ObjectKeys(self).forEach((prop) => { self[prop] = null; });
}
}
/* Native JavaScript for Bootstrap 5 | Tooltip
---------------------------------------------- */
// TOOLTIP PRIVATE GC
// ==================
const tooltipSelector = `[${dataBsToggle}="${tooltipString}"],[data-tip="${tooltipString}"]`;
const titleAttr = 'title';
/**
* Static method which returns an existing `Tooltip` instance associated
* to a target `Element`.
*
* @type {BSN.GetInstance<Tooltip>}
*/
let getTooltipInstance = (element) => getInstance(element, tooltipComponent);
/**
* A `Tooltip` initialization callback.
* @type {BSN.InitCallback<Tooltip>}
*/
const tooltipInitCallback = (element) => new Tooltip(element);
// TOOLTIP PRIVATE METHODS
// =======================
/**
* Removes the tooltip from the DOM.
*
* @param {Tooltip} self the `Tooltip` instance
*/
function removeTooltip(self) {
const { element, tooltip } = self;
removeAttribute(element, ariaDescribedBy);
tooltip.remove();
}
/**
* Executes after the instance has been disposed.
*
* @param {Tooltip} self the `Tooltip` instance
*/
function disposeTooltipComplete(self) {
const { element } = self;
toggleTooltipHandlers(self);
if (element.hasAttribute(dataOriginalTitle) && self.name === tooltipString) {
toggleTooltipTitle(self);
}
}
/**
* Toggles on/off the special `Tooltip` event listeners.
*
* @param {Tooltip} self the `Tooltip` instance
* @param {boolean=} add when `true`, event listeners are added
*/
function toggleTooltipAction(self, add) {
const action = add ? on : off;
const { element } = self;
action(getDocument(element), touchstartEvent, tooltipTouchHandler, passiveHandler);
if (!isMedia(element)) {
[scrollEvent, resizeEvent].forEach((ev) => {
// @ts-ignore
action(getWindow(element), ev, self.update, passiveHandler);
});
}
}
/**
* Executes after the tooltip was shown to the user.
*
* @param {Tooltip} self the `Tooltip` instance
*/
function tooltipShownAction(self) {
const { element } = self;
const shownTooltipEvent = OriginalEvent(`shown.bs.${toLowerCase(self.name)}`);
toggleTooltipAction(self, true);
dispatchEvent(element, shownTooltipEvent);
Timer.clear(element, 'in');
}
/**
* Executes after the tooltip was hidden to the user.
*
* @param {Tooltip} self the `Tooltip` instance
*/
function tooltipHiddenAction(self) {
const { element } = self;
const hiddenTooltipEvent = OriginalEvent(`hidden.bs.${toLowerCase(self.name)}`);
toggleTooltipAction(self);
removeTooltip(self);
dispatchEvent(element, hiddenTooltipEvent);
Timer.clear(element, 'out');
}
/**
* Toggles on/off the `Tooltip` event listeners.
*
* @param {Tooltip} self the `Tooltip` instance
* @param {boolean=} add when `true`, event listeners are added
*/
function toggleTooltipHandlers(self, add) {
const action = add ? on : off;
// @ts-ignore -- btn is only for dismissible popover
const { element, options, btn } = self;
const { trigger, dismissible } = options;
if (trigger.includes('manual')) return;
self.enabled = !!add;
/** @type {string[]} */
const triggerOptions = trigger.split(' ');
const elemIsMedia = isMedia(element);
if (elemIsMedia) {
action(element, mousemoveEvent, self.update, passiveHandler);
}
triggerOptions.forEach((tr) => {
if (elemIsMedia || tr === mousehoverEvent) {
action(element, mousedownEvent, self.show);
action(element, mouseenterEvent, self.show);
if (dismissible && btn) {
action(btn, mouseclickEvent, self.hide);
} else {
action(element, mouseleaveEvent, self.hide);
action(getDocument(element), touchstartEvent, tooltipTouchHandler, passiveHandler);
}
} else if (tr === mouseclickEvent) {
action(element, tr, (!dismissible ? self.toggle : self.show));
} else if (tr === focusEvent) {
action(element, focusinEvent, self.show);
if (!dismissible) action(element, focusoutEvent, self.hide);
if (isApple) action(element, mouseclickEvent, () => focus(element));
}
});
}
/**
* Toggles on/off the `Tooltip` event listeners that hide/update the tooltip.
*
* @param {Tooltip} self the `Tooltip` instance
* @param {boolean=} add when `true`, event listeners are added
*/
function toggleTooltipOpenHandlers(self, add) {
const action = add ? on : off;
const { element, options, offsetParent } = self;
const { container } = options;
const { offsetHeight, scrollHeight } = container;
const parentModal = closest(element, `.${modalString}`);
const parentOffcanvas = closest(element, `.${offcanvasString}`);
if (!isMedia(element)) {
const win = getWindow(element);
const overflow = offsetHeight !== scrollHeight;
const scrollTarget = overflow || offsetParent !== win ? container : win;
// @ts-ignore
action(win, resizeEvent, self.update, passiveHandler);
action(scrollTarget, scrollEvent, self.update, passiveHandler);
}
// dismiss tooltips inside modal / offcanvas
if (parentModal) on(parentModal, `hide.bs.${modalString}`, self.hide);
if (parentOffcanvas) on(parentOffcanvas, `hide.bs.${offcanvasString}`, self.hide);
}
/**
* Toggles the `title` and `data-original-title` attributes.
*
* @param {Tooltip} self the `Tooltip` instance
* @param {string=} content when `true`, event listeners are added
*/
function toggleTooltipTitle(self, content) {
// [0 - add, 1 - remove] | [0 - remove, 1 - add]
const titleAtt = [dataOriginalTitle, titleAttr];
const { element } = self;
setAttribute(element, titleAtt[content ? 0 : 1],
// @ts-ignore
(content || getAttribute(element, titleAtt[0])));
removeAttribute(element, titleAtt[content ? 1 : 0]);
}
// TOOLTIP EVENT HANDLERS
// ======================
/**
* Handles the `touchstart` event listener for `Tooltip`
* @this {Tooltip}
* @param {TouchEvent} e the `Event` object
*/
function tooltipTouchHandler({ target }) {
const { tooltip, element } = this;
// @ts-ignore
if (tooltip.contains(target) || target === element || element.contains(target)) ; else {
this.hide();
}
}
// TOOLTIP DEFINITION
// ==================
/** Creates a new `Tooltip` instance. */
class Tooltip extends BaseComponent {
/**
* @param {HTMLElement | Element | string} target the target element
* @param {BSN.Options.Tooltip=} config the instance options
*/
constructor(target, config) {
super(target, config);
// bind
const self = this;
const { element } = self;
const isTooltip = self.name === tooltipComponent;
const tipString = isTooltip ? tooltipString : popoverString;
const tipComponent = isTooltip ? tooltipComponent : popoverComponent;
getTooltipInstance = (elem) => getInstance(elem, tipComponent);
// additional properties
/** @type {any} */
self.tooltip = {};
if (!isTooltip) {
/** @type {any?} */
// @ts-ignore
self.btn = null;
}
/** @type {any} */
self.arrow = {};
/** @type {any} */
self.offsetParent = {};
/** @type {boolean} */
self.enabled = true;
/** @type {string} Set unique ID for `aria-describedby`. */
self.id = `${tipString}-${getUID(element, tipString)}`;
// instance options
const { options } = self;
// invalidate
if ((!options.title && isTooltip) || (!isTooltip && !options.content)) return;
const container = querySelector(options.container);
const idealContainer = getElementContainer(element);
// bypass container option when its position is static/relative
self.options.container = !container || (container
&& ['static', 'relative'].includes(getElementStyle(container, 'position')))
? idealContainer
: container || getDocumentBody(element);
// reset default options
tooltipDefaults[titleAttr] = null;
// all functions bind
tooltipTouchHandler.bind(self);
self.update = self.update.bind(self);
self.show = self.show.bind(self);
self.hide = self.hide.bind(self);
self.toggle = self.toggle.bind(self);
// set title attributes and add event listeners
if (element.hasAttribute(titleAttr) && isTooltip) {
toggleTooltipTitle(self, options.title);
}
// create tooltip here
createTip(self);
// attach events
toggleTooltipHandlers(self, true);
}
/* eslint-disable */
/**
* Returns component name string.
* @readonly @static
*/
get name() { return tooltipComponent; }
/**
* Returns component default options.
* @readonly @static
*/
get defaults() { return tooltipDefaults; }
/* eslint-enable */
// TOOLTIP PUBLIC METHODS
// ======================
/**
* Shows the tooltip.
*
* @param {Event=} e the `Event` object
* @this {Tooltip}
*/
show(e) {
const self = this;
const {
options, tooltip, element, id,
} = self;
const { container, animation } = options;
const outTimer = Timer.get(element, 'out');
Timer.clear(element, 'out');
if (tooltip && !outTimer && !isVisibleTip(tooltip, container)) {
Timer.set(element, () => {
const showTooltipEvent = OriginalEvent(`show.bs.${toLowerCase(self.name)}`);
dispatchEvent(element, showTooltipEvent);
if (showTooltipEvent.defaultPrevented) return;
// append to container
container.append(tooltip);
setAttribute(element, ariaDescribedBy, `#${id}`);
// set offsetParent
self.offsetParent = getElementContainer(tooltip, true);
self.update(e);
toggleTooltipOpenHandlers(self, true);
if (!hasClass(tooltip, showClass)) addClass(tooltip, showClass);
if (animation) emulateTransitionEnd(tooltip, () => tooltipShownAction(self));
else tooltipShownAction(self);
}, 17, 'in');
}
}
/**
* Hides the tooltip.
*
* @this {Tooltip}
*/
hide() {
const self = this;
const { options, tooltip, element } = self;
const { container, animation, delay } = options;
Timer.clear(element, 'in');
if (tooltip && isVisibleTip(tooltip, container)) {
Timer.set(element, () => {
const hideTooltipEvent = OriginalEvent(`hide.bs.${toLowerCase(self.name)}`);
dispatchEvent(element, hideTooltipEvent);
if (hideTooltipEvent.defaultPrevented) return;
// @ts-ignore
removeClass(tooltip, showClass);
toggleTooltipOpenHandlers(self);
if (animation) emulateTransitionEnd(tooltip, () => tooltipHiddenAction(self));
else tooltipHiddenAction(self);
}, delay + 17, 'out');
}
}
/**
* Updates the tooltip position.
*
* @param {Event=} e the `Event` object
* @this {Tooltip} the `Tooltip` instance
*/
update(e) {
// @ts-ignore
styleTip(this, e);
}
/**
* Toggles the tooltip visibility.
*
* @param {Event=} e the `Event` object
* @this {Tooltip} the instance
*/
toggle(e) {
const self = this;
const { tooltip, options } = self;
if (!isVisibleTip(tooltip, options.container)) self.show(e);
else self.hide();
}
/** Enables the tooltip. */
enable() {
const self = this;
const { enabled } = self;
if (!enabled) {
toggleTooltipHandlers(self, true);
self.enabled = !enabled;
}
}
/** Disables the tooltip. */
disable() {
const self = this;
const {
element, tooltip, options, enabled,
} = self;
const { animation, container, delay } = options;
if (enabled) {
if (isVisibleTip(tooltip, container) && animation) {
self.hide();
Timer.set(element, () => {
toggleTooltipHandlers(self);
Timer.clear(element, tooltipString);
}, getElementTransitionDuration(tooltip) + delay + 17, tooltipString);
} else {
toggleTooltipHandlers(self);
}
self.enabled = !enabled;
}
}
/** Toggles the `disabled` property. */
toggleEnabled() {
const self = this;
if (!self.enabled) self.enable();
else self.disable();
}
/** Removes the `Tooltip` from the target element. */
dispose() {
const self = this;
const { tooltip, options } = self;
if (options.animation && isVisibleTip(tooltip, options.container)) {
options.delay = 0; // reset delay
self.hide();
emulateTransitionEnd(tooltip, () => disposeTooltipComplete(self));
} else {
disposeTooltipComplete(self);
}
super.dispose();
}
}
ObjectAssign(Tooltip, {
selector: tooltipSelector,
init: tooltipInitCallback,
getInstance: getTooltipInstance,
styleTip,
});
/* Native JavaScript for Bootstrap 5 | Popover
---------------------------------------------- */
// POPOVER PRIVATE GC
// ==================
const popoverSelector = `[${dataBsToggle}="${popoverString}"],[data-tip="${popoverString}"]`;
const popoverDefaults = {
...tooltipDefaults,
/** @type {string} */
template: getTipTemplate(popoverString),
/** @type {string} */
btnClose: '<button class="btn-close" aria-label="Close"></button>',
/** @type {boolean} */
dismissible: false,
/** @type {string?} */
content: null,
};
// POPOVER DEFINITION
// ==================
/** Returns a new `Popover` instance. */
class Popover extends Tooltip {
/* eslint-disable -- we want to specify Popover Options */
/**
* @param {HTMLElement | Element | string} target the target element
* @param {BSN.Options.Popover=} config the instance options
*/
constructor(target, config) {
super(target, config);
}
/**
* Returns component name string.
* @readonly @static
*/
get name() { return popoverComponent; }
/**
* Returns component default options.
* @readonly @static
*/
get defaults() { return popoverDefaults; }
/* eslint-enable */
/* extend original `show()` */
show() {
super.show();
// @ts-ignore -- btn only exists within dismissible popover
const { options, btn } = this;
if (options.dismissible && btn) setTimeout(() => focus(btn), 17);
}
}
/**
* Static method which returns an existing `Popover` instance associated
* to a target `Element`.
*
* @type {BSN.GetInstance<Popover>}
*/
const getPopoverInstance = (element) => getInstance(element, popoverComponent);
/**
* A `Popover` initialization callback.
* @type {BSN.InitCallback<Popover>}
*/
const popoverInitCallback = (element) => new Popover(element);
ObjectAssign(Popover, {
selector: popoverSelector,
init: popoverInitCallback,
getInstance: getPopoverInstance,
styleTip,
});
return Popover;
}));
| {'content_hash': 'f8e2c11fe95f9d244694de5005d67d8d', 'timestamp': '', 'source': 'github', 'line_count': 1934, 'max_line_length': 105, 'avg_line_length': 31.00258531540848, 'alnum_prop': 0.6199236144698878, 'repo_name': 'cdnjs/cdnjs', 'id': 'f7b73934f2935a397c758b025513fd1072cba108', 'size': '60196', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ajax/libs/bootstrap.native/4.1.0-alpha3/components/popover-native.js', 'mode': '33188', 'license': 'mit', 'language': []} |
' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.[Shared].Collections
Imports Microsoft.CodeAnalysis.Structure
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Structure
Friend Class RegionDirectiveStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of RegionDirectiveTriviaSyntax)
Private Shared Function GetBannerText(regionDirective As RegionDirectiveTriviaSyntax) As String
Dim text = regionDirective.Name.ToString().Trim(""""c)
If text.Length = 0 Then
Return regionDirective.HashToken.ToString() & regionDirective.RegionKeyword.ToString()
End If
Return text
End Function
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
regionDirective As RegionDirectiveTriviaSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
options As BlockStructureOptions,
CancellationToken As CancellationToken)
Dim matchingDirective = regionDirective.GetMatchingStartOrEndDirective(CancellationToken)
If matchingDirective IsNot Nothing Then
' Always auto-collapse regions for Metadata As Source. These generated files only have one region at the
' top of the file, which has content like the following:
'
' #Region "Assembly System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
' ' C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Runtime.dll
' #End Region
'
' For other files, auto-collapse regions based on the user option.
Dim autoCollapse = options.IsMetadataAsSource OrElse options.CollapseRegionsWhenCollapsingToDefinitions
Dim span = TextSpan.FromBounds(regionDirective.SpanStart, matchingDirective.Span.End)
spans.AddIfNotNull(CreateBlockSpan(
span, span,
GetBannerText(regionDirective),
autoCollapse:=autoCollapse,
isDefaultCollapsed:=options.CollapseRegionsWhenFirstOpened,
type:=BlockTypes.PreprocessorRegion,
isCollapsible:=True))
End If
End Sub
End Class
End Namespace
| {'content_hash': 'cf2d5cdf11bc9d48685da303e163f7aa', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 120, 'avg_line_length': 53.056603773584904, 'alnum_prop': 0.6465149359886202, 'repo_name': 'dotnet/roslyn', 'id': '41889b9e2492e444b68623757a1925171d54db8e', 'size': '2814', 'binary': False, 'copies': '7', 'ref': 'refs/heads/main', 'path': 'src/Features/VisualBasic/Portable/Structure/Providers/RegionDirectiveStructureProvider.vb', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '257760'}, {'name': 'Batchfile', 'bytes': '8186'}, {'name': 'C#', 'bytes': '177013904'}, {'name': 'C++', 'bytes': '5602'}, {'name': 'CMake', 'bytes': '12939'}, {'name': 'Dockerfile', 'bytes': '441'}, {'name': 'F#', 'bytes': '549'}, {'name': 'PowerShell', 'bytes': '284790'}, {'name': 'Shell', 'bytes': '134009'}, {'name': 'Vim Snippet', 'bytes': '6353'}, {'name': 'Visual Basic .NET', 'bytes': '74255416'}]} |
package com.slack.api.methods.response.reminders;
import com.slack.api.methods.SlackApiResponse;
import com.slack.api.model.Reminder;
import lombok.Data;
@Data
public class RemindersInfoResponse implements SlackApiResponse {
private boolean ok;
private String warning;
private String error;
private String needed;
private String provided;
private Reminder reminder;
} | {'content_hash': '9f9718daa687d7343ce14a9c80e14a3d', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 64, 'avg_line_length': 23.235294117647058, 'alnum_prop': 0.7772151898734178, 'repo_name': 'seratch/jslack', 'id': '609b71171c47e9c0893868ac1519a724aafe0041', 'size': '395', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'slack-api-client/src/main/java/com/slack/api/methods/response/reminders/RemindersInfoResponse.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '3120'}, {'name': 'Dockerfile', 'bytes': '253'}, {'name': 'Java', 'bytes': '2053529'}, {'name': 'Kotlin', 'bytes': '26226'}, {'name': 'Ruby', 'bytes': '3769'}, {'name': 'Shell', 'bytes': '1133'}]} |
using EME.Infrastructure.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EME.Tests.Stubs
{
internal class EventsDispatcher : IEventsDispatcher
{
public event EventHandler<EventMessageArgs> MessageReceived;
public void Send(string type, string message)
{
if (MessageReceived != null)
MessageReceived(this, new EventMessageArgs { Type = type, Message = message });
}
}
internal class EventMessageArgs : EventArgs
{
public string Type { get; set; }
public string Message { get; set; }
}
}
| {'content_hash': '93aa33dffba9600362e80bc1fb50c4f2', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 95, 'avg_line_length': 26.037037037037038, 'alnum_prop': 0.6699857752489331, 'repo_name': 'jenyayel/ExchangeMatchingEngine', 'id': 'b302ebd0705eee580145c8fb38bfbeffcd86693c', 'size': '705', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'EME.Tests/Stubs/EventsDispatcher.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '72828'}]} |
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<android.support.v7.widget.GridLayout
android:id="@+id/advancedGridLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="144dp"
android:minWidth="144dp"
app:columnCount="3"
app:rowCount="1" >
</android.support.v7.widget.GridLayout>
</HorizontalScrollView>
</ScrollView>
| {'content_hash': '8828423257506ecaf4b1342dccfed79d', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 70, 'avg_line_length': 34.26086956521739, 'alnum_prop': 0.6814720812182741, 'repo_name': 'ekux44/HueMore', 'id': 'c18c24be1654596746a03d47e96ea2b12505256e', 'size': '788', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'mobile/src/main/res/layout/edit_mood_state_grid_fragment.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1611797'}, {'name': 'Makefile', 'bytes': '1048'}]} |
#include <aws/iot/model/CreateKeysAndCertificateResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::IoT::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
CreateKeysAndCertificateResult::CreateKeysAndCertificateResult()
{
}
CreateKeysAndCertificateResult::CreateKeysAndCertificateResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
CreateKeysAndCertificateResult& CreateKeysAndCertificateResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("certificateArn"))
{
m_certificateArn = jsonValue.GetString("certificateArn");
}
if(jsonValue.ValueExists("certificateId"))
{
m_certificateId = jsonValue.GetString("certificateId");
}
if(jsonValue.ValueExists("certificatePem"))
{
m_certificatePem = jsonValue.GetString("certificatePem");
}
if(jsonValue.ValueExists("keyPair"))
{
m_keyPair = jsonValue.GetObject("keyPair");
}
return *this;
}
| {'content_hash': 'de70a275c6ed35852b0bdf1c880d12f9', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 128, 'avg_line_length': 22.509090909090908, 'alnum_prop': 0.7584814216478191, 'repo_name': 'JoyIfBam5/aws-sdk-cpp', 'id': 'bae7589a541ad91cd6c2cc16025b5bc1bb12c293', 'size': '1811', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-iot/source/model/CreateKeysAndCertificateResult.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '11868'}, {'name': 'C++', 'bytes': '167818064'}, {'name': 'CMake', 'bytes': '591577'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '271801'}, {'name': 'Python', 'bytes': '85650'}, {'name': 'Shell', 'bytes': '5277'}]} |
var finalhandler = require('finalhandler'),
http = require('http'),
serveStatic = require('serve-static');
// ---- Local Variables ----
var serve = serveStatic('examples');
// ---- HTTP Server ----
http.createServer(function (req, res) {
var done = finalhandler(req, res);
serve(req, res, done);
}).listen(3000); | {'content_hash': '0ad40700579beb5579947ce27b5e39ff', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 43, 'avg_line_length': 23.428571428571427, 'alnum_prop': 0.6371951219512195, 'repo_name': 'blats002/JLRAssessment', 'id': 'd8e5a80c2daff6115bf12855fb17ad25f21900fc', 'size': '350', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'plugins/es.keensoft.fullscreenimage/keensoft-example/www/lib/ryanmullins-angular-hammer/server.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3033'}, {'name': 'C', 'bytes': '3152'}, {'name': 'C#', 'bytes': '116082'}, {'name': 'C++', 'bytes': '290929'}, {'name': 'CSS', 'bytes': '498979'}, {'name': 'CoffeeScript', 'bytes': '3263'}, {'name': 'HTML', 'bytes': '108018'}, {'name': 'Java', 'bytes': '192679'}, {'name': 'JavaScript', 'bytes': '2846325'}, {'name': 'Objective-C', 'bytes': '226474'}, {'name': 'QML', 'bytes': '4777'}]} |
cask 'shadowsocksx-ng' do
version '1.5.0'
sha256 '62146a2b4ba243983ff555d265514caca3dfa4a8bcda81addd07fd75d2509eeb'
url "https://github.com/shadowsocks/ShadowsocksX-NG/releases/download/v#{version}/ShadowsocksX-NG-#{version}.zip"
appcast 'https://github.com/shadowsocks/ShadowsocksX-NG/releases.atom',
checkpoint: '069a443dab1385e3485126dcd734bfebc6a4ec70dd40b945908c20136afedab7'
name 'ShadowsocksX-NG'
homepage 'https://github.com/shadowsocks/ShadowsocksX-NG/'
conflicts_with cask: 'shadowsocksx'
app 'ShadowsocksX-NG.app'
zap delete: [
'/Library/Application Support/ShadowsocksX-NG',
'~/.ShadowsocksX-NG',
'~/Library/Application Support/ShadowsocksX-NG',
'~/Library/Caches/com.qiuyuzhou.ShadowsocksX-NG',
'~/Library/LaunchAgents/com.qiuyuzhou.shadowsocksX-NG.http.plist',
'~/Library/LaunchAgents/com.qiuyuzhou.shadowsocksX-NG.local.plist',
'~/Library/Preferences/com.qiuyuzhou.ShadowsocksX-NG.plist',
]
end
| {'content_hash': 'e787429bb894d9936dc44a17cd7ffbfa', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 115, 'avg_line_length': 44.5, 'alnum_prop': 0.6900749063670412, 'repo_name': 'KosherBacon/homebrew-cask', 'id': '20a5cb82b11b93736eb2cae9557244ed9fbdf019', 'size': '1068', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Casks/shadowsocksx-ng.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '2031578'}, {'name': 'Shell', 'bytes': '56833'}]} |
<!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.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OxyEngine: Class Members - Functions</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="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(initResizable);
/* @license-end */</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.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="logo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">OxyEngine
 <span id="projectnumber">0.2.0</span>
</div>
<div id="projectbrief">2D full-featured open-source crossplatform game engine</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.14 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */
$(document).ready(function(){initNavTree('functions_func.html','');});
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
 
<h3><a id="index_c"></a>- c -</h3><ul>
<li>Circle()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a48f0e55177245038e5eca3df64cc5ddc">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
<h3><a id="index_d"></a>- d -</h3><ul>
<li>Dispose()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#a551e2c2a18df96670a1fc623a29c6fe7">OxyEngine.Resources.ResourceManager</a>
</li>
<li>Draw()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#af3b5c2d0238f13ce24546d502359a454">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
<h3><a id="index_g"></a>- g -</h3><ul>
<li>GetApi()
: <a class="el" href="class_oxy_engine_1_1_game_instance.html#a1f748c1d60ef1ef37362c3608819e016">OxyEngine.GameInstance</a>
</li>
<li>GetBackgroundColor()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#adce48eecdd0ff39dbf6e0173481f2bac">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>GetColor()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a153afe3cdf4abe412afa930241d54a86">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>GetCursorPosition()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#ab1560bdeee5af0ffdeb651d3f59b55aa">OxyEngine.Input.InputManager</a>
</li>
<li>GetGamePadStick()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a0460ae9c31ac412fec6db59b1dc8f500">OxyEngine.Input.InputManager</a>
</li>
<li>GetGamePadTrigger()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#ac49207da22a7ddadcb4e7975ceb88026">OxyEngine.Input.InputManager</a>
</li>
<li>GetLineWidth()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a435673f4e2a47f3d6542b4419e6725b0">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>GetMouseWheel()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a8835cf218ca877181ce13aa86231cd71">OxyEngine.Input.InputManager</a>
</li>
</ul>
<h3><a id="index_i"></a>- i -</h3><ul>
<li>IsGamePadButtonPressed()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#aa7dcad85c2dbd97392fea51c7bec7429">OxyEngine.Input.InputManager</a>
</li>
<li>IsKeyPressed()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a74631e64ca76355a2ea81bf27f8c03ce">OxyEngine.Input.InputManager</a>
</li>
<li>IsMousePressed()
: <a class="el" href="class_oxy_engine_1_1_input_1_1_input_manager.html#a4a41b342643088a8be3b100129681f0a">OxyEngine.Input.InputManager</a>
</li>
</ul>
<h3><a id="index_l"></a>- l -</h3><ul>
<li>Line()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a21d813d3643a9f5007bdf13d55714840">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>LoadFont()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#a51000e4479350047670f8961a67ffcf2">OxyEngine.Resources.ResourceManager</a>
</li>
<li>LoadSong()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#a196fe1246ff7d355051815eed954b98e">OxyEngine.Resources.ResourceManager</a>
</li>
<li>LoadSoundEffect()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#ac5475294294cff49519c5d3246187861">OxyEngine.Resources.ResourceManager</a>
</li>
<li>LoadTexture()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#ae0b5524ad2bd554f604b9e144e90f298">OxyEngine.Resources.ResourceManager</a>
</li>
</ul>
<h3><a id="index_n"></a>- n -</h3><ul>
<li>NewRect()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a99a363480dd6492f043fb4b9bbf11850">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>NewRenderTexture()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a1805e4f51065d3d2249e8cfb3bd32155">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>NewTexture()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a157cf96a50c30ccf3e96dfcf5b4becaf">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
<h3><a id="index_p"></a>- p -</h3><ul>
<li>Point()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a2e391d0d0391977e2b78aedfc288ecc3">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>Polygon()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#ac3b95105ded683e11e5e348b7e3db470">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>PopMatrix()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#ad2ef81bcf5f528b11884611da84e8eee">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>PushMatrix()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#ae4eb1eb9a32b4fd75f8035e8db6159c5">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
<h3><a id="index_r"></a>- r -</h3><ul>
<li>Rectangle()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#adc17fd349795249afbafd403894dd149">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>ResourceManager()
: <a class="el" href="class_oxy_engine_1_1_resources_1_1_resource_manager.html#a7f854e6652f00c6e62fdadd47bb3609c">OxyEngine.Resources.ResourceManager</a>
</li>
<li>Rotate()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a2e63e68c74835fc6522a93f876b072ce">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
<h3><a id="index_s"></a>- s -</h3><ul>
<li>Scale()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a8b5dfb71c7a5dc060ccca002555abf05">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>SetBackgroundColor()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a3dbf6036baf3b507d89a172812260944">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>SetColor()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#adf692b7704e8816c44cd21da0940e1d9">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>SetLineWidth()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a0db31ef0d4f871f7928138dd54212a43">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>SetRenderTexture()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a15992c2d24964adc034a149e54475974">OxyEngine.Graphics.GraphicsManager</a>
</li>
<li>SetScripting()
: <a class="el" href="class_oxy_engine_1_1_game_instance.html#af46245b8ace1b7ba7de87eda485a4095">OxyEngine.GameInstance</a>
</li>
</ul>
<h3><a id="index_t"></a>- t -</h3><ul>
<li>Translate()
: <a class="el" href="class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a8945c21c560ecfe1bbfb7ec96ce55cbe">OxyEngine.Graphics.GraphicsManager</a>
</li>
</ul>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li>
</ul>
</div>
</body>
</html>
| {'content_hash': 'c547fd55b59915d2330f8afbfd21c270', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 153, 'avg_line_length': 42.636, 'alnum_prop': 0.7266160052537761, 'repo_name': 'OxyTeam/OxyEngine', 'id': 'a0eb1a92a5583fe1c6c25b255bba404141a116e8', 'size': '10659', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'docs/html/functions_func.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '128159'}]} |
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/jquery.gridder.min.css" rel="stylesheet">
<!-- Custom CSS -->
<!--<link href="css/style.css" rel="stylesheet">-->
<link href="css/gridder.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<!-- Gridder navigation -->
<ul class="gridder">
<li class="gridder-list" data-griddercontent="#dianbo">
<div class="gridder-thumb">
<img src="img/dianbo.png" class="img-circle"/>
<span class="title text-center">Dianbo Liu</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#gillian">
<div class="gridder-thumb">
<img src="img/gillian.png" class="img-circle"/>
<span class="title text-center">Gillian Dunphy</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#stefan">
<div class="gridder-thumb">
<img src="img/stefan.png" class="img-circle"/>
<span class="title text-center">Stefan Tomov</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#thiago">
<div class="gridder-thumb">
<img src="img/thiago.png" class="img-circle"/>
<span class="title text-center">Thiago Britto-Borges</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#sarah">
<div class="gridder-thumb">
<img src="img/sarah.png" class="img-circle"/>
<span class="title text-center">Sarah-Lena Offenburger</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#fabio">
<div class="gridder-thumb">
<img src="img/fabio.png" class="img-circle"/>
<span class="title text-center">Fábio Madeira</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#darya">
<div class="gridder-thumb">
<img src="img/darya.png" class="img-circle"/>
<span class="title text-center">Darya Baranovka</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#kushal">
<div class="gridder-thumb">
<img src="img/kushal.png" class="img-circle"/>
<span class="title text-center">Kushal Rugjee</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#sam">
<div class="gridder-thumb">
<img src="img/sam.png" class="img-circle"/>
<span class="title text-center">Sam Watkins</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#dora">
<div class="gridder-thumb">
<img src="img/dora.png" class="img-circle"/>
<span class="title text-center">Teodora Maghear</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#alasdair">
<div class="gridder-thumb">
<img src="img/alasdair.png" class="img-circle"/>
<span class="title text-center">Alasdair McGill</span>
</div>
</li>
<li class="gridder-list" data-griddercontent="#yuri">
<div class="gridder-thumb">
<img src="img/yuri.png" class="img-circle"/>
<span class="title text-center">Yuri Alexandrov</span>
</div>
</li>
</ul>
<!-- Gridder content -->
<div id="dianbo" class="gridder-content">Dianbo Liu is the licence holder for the
upcoming TEDxUniversityofDundee event. He is the leader
of the team and is currently studying for a PhD within the
Computational and Physical Biology department at the
University of Dundee. He is interested in making links
among seemingly unrelated fields, and therefore come up
with innovative and useful inventions.</div>
<div id="gillian" class="gridder-content">Gillian Dunphy was born and raised in Glasgow but was
compelled to make the lengthy journey to Dundee after being
lured by its East Coast charm. She is currently studying for
a PhD in Immunology at the University of Dundee. She is
currently managing a team of student volunteers in the areas
of Graphic Design and Stage Design. She is also involved in
marketing and speaker recruitment.</div>
<div id="stefan" class="gridder-content">Stefan Tomov is a recent University of Dundee
graduate in the field of Economics and Politics. He comes
from Bulgaria and is currently the Deputy President of
Dundee University Students' Association (DUSA). Stefan is
responsible for securing the logistics required to make
TEDxUniversityofDundee a resounding success.</div>
<div id="thiago" class="gridder-content">Thiago Britto-Borges is a Brazilian PhD student within
the Computational Biology department of the University of Dundee
He has an inexhaustible passion for learning and enjoys spreading knowledge. Thiago
is responsible for developing and designing the TEDxUniversityofDundee website.</div>
<div id="sarah" class="gridder-content">Sarah-Lena Offenburger is pursuing a PhD in
Neurobiology at the University of Dundee. When Sarah is not
in the lab, you will probably find her doing sports, taking
pictures or just having a coffee with friends. Sarah is a
curator within our team and is responsible for recruiting
and liasing with the speakers of the event.</div>
<div id="fabio" class="gridder-content">Originally from Portugal, Fábio Madeira is
currently studying for a PhD within the Cell and Molecular
Biology department at the University of Dundee,
specialising in Computational Biology. Alongside with Thiago, he helps managing and developing the website of the event.</div>
<div id="darya" class="gridder-content">is the president of Enterprise
Gym which is a University of Dundee department where
students learn about entrepreneurship. She comes from the
small and pretty town of Liepaya, which is located on the
Latvian coast of the Baltic Sea. Darya is responsible for
the recruitment of volunteers and organising the logistics
of the event.</div>
<div id="kushal" class="gridder-content">moved from the island of
Mauritius to equally sunny Dundee to pursue a PhD in
Microbiology. His role in the team is to co-ordinate the
overall organisation of the TEDx event and to ensure that
progress is being made.</div>
<div id="sam" class="gridder-content">is currently studying Computer Science at the University of Dundee.
He is in his third year now and interested in Web
Programming, Product Development and Entrepreneurship. Sam
is our Social Media Officer, taking care of our Twitter and
Facebook accounts.</div>
<div id="dora" class="gridder-content">is the Enterprise Assistant & Coordinator
at the Enterprise Gym, University of Dundee.
Her perseverance and passion for entrepreneurship and innovation has seen her work her way up in the roles in the department.
She received her BSc in business Economics with marketing from Dundee University in 2014. Dora is actively contributing her
expertise in a number of areas of the project.</div>
<div id="alasdair" class="gridder-content">is Head of Enterprise &
Entrepreneurial Strategy at the University of Dundee.
Not a man to sit about, Alasdair has a brain that's always
busy and he loves thinking of creative ways to make a
difference. As well as his role at the university, Alasdair
is also a director and founder of several companies in
industries as diverse as retail, software, sports and
financial services. He is a formidable adviser within our
team.</div>
<div id="yuri" class="gridder-content">is currently pursuing a master's
degree in Data Engineering. He studies Data because he likes
to observe and find patterns in the environment that
surrounds us. Yuri serves as a curator along with Sarah in
our team. He is involved in the recruitment of speakers.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="js/jquery.gridder.min.js"></script>
<script>
$(function() {
// Call Gridder
$('.gridder').gridderExpander({
scroll: true,
scrollOffset: 30,
scrollTo: "panel", // panel or listitem
animationSpeed: 400,
animationEasing: "easeInOutExpo",
onStart: function(){
console.log("Gridder Inititialized");
},
onContent: function(){
console.log("Gridder Content Loaded");
},
onClosed: function(){
console.log("Gridder Closed");
}
});
});
</script>
</body>
</html> | {'content_hash': '370af85370ded3ea2167690133a70b08', 'timestamp': '', 'source': 'github', 'line_count': 191, 'max_line_length': 146, 'avg_line_length': 51.12041884816754, 'alnum_prop': 0.6084596476853749, 'repo_name': 'tbrittoborges/tedx_uod', 'id': 'fa3d57938197e6fa76539b35a8a81a87cbc91f4c', 'size': '9764', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'gridder.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '133186'}, {'name': 'HTML', 'bytes': '95136'}, {'name': 'JavaScript', 'bytes': '4326'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ip::address_v4</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="ip__address/to_v6.html" title="ip::address::to_v6">
<link rel="next" href="ip__address_v4/address_v4.html" title="ip::address_v4::address_v4">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="ip__address/to_v6.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="ip__address_v4/address_v4.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_asio.reference.ip__address_v4"></a><a class="link" href="ip__address_v4.html" title="ip::address_v4">ip::address_v4</a>
</h3></div></div></div>
<p>
Implements IP version 4 style addresses.
</p>
<pre class="programlisting"><span class="keyword">class</span> <span class="identifier">address_v4</span>
</pre>
<h5>
<a name="boost_asio.reference.ip__address_v4.h0"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.types"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.types">Types</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<a class="link" href="ip__address_v4/bytes_type.html" title="ip::address_v4::bytes_type"><span class="bold"><strong>bytes_type</strong></span></a>
</p>
</td>
<td>
<p>
The type used to represent an address as an array of bytes.
</p>
</td>
</tr></tbody>
</table></div>
<h5>
<a name="boost_asio.reference.ip__address_v4.h1"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.member_functions"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.member_functions">Member Functions</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/address_v4.html" title="ip::address_v4::address_v4"><span class="bold"><strong>address_v4</strong></span></a>
</p>
</td>
<td>
<p>
Default constructor.
</p>
<p>
Construct an address from raw bytes.
</p>
<p>
Construct an address from a unsigned long in host byte order.
</p>
<p>
Copy constructor.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/any.html" title="ip::address_v4::any"><span class="bold"><strong>any</strong></span></a>
</p>
</td>
<td>
<p>
Obtain an address object that represents any address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/broadcast.html" title="ip::address_v4::broadcast"><span class="bold"><strong>broadcast</strong></span></a>
</p>
</td>
<td>
<p>
Obtain an address object that represents the broadcast address.
</p>
<p>
Obtain an address object that represents the broadcast address
that corresponds to the specified address and netmask.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/from_string.html" title="ip::address_v4::from_string"><span class="bold"><strong>from_string</strong></span></a>
</p>
</td>
<td>
<p>
Create an address from an IP address string in dotted decimal form.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_class_a.html" title="ip::address_v4::is_class_a"><span class="bold"><strong>is_class_a</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is a class A address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_class_b.html" title="ip::address_v4::is_class_b"><span class="bold"><strong>is_class_b</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is a class B address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_class_c.html" title="ip::address_v4::is_class_c"><span class="bold"><strong>is_class_c</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is a class C address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_loopback.html" title="ip::address_v4::is_loopback"><span class="bold"><strong>is_loopback</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is a loopback address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_multicast.html" title="ip::address_v4::is_multicast"><span class="bold"><strong>is_multicast</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is a multicast address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/is_unspecified.html" title="ip::address_v4::is_unspecified"><span class="bold"><strong>is_unspecified</strong></span></a>
</p>
</td>
<td>
<p>
Determine whether the address is unspecified.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/loopback.html" title="ip::address_v4::loopback"><span class="bold"><strong>loopback</strong></span></a>
</p>
</td>
<td>
<p>
Obtain an address object that represents the loopback address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/netmask.html" title="ip::address_v4::netmask"><span class="bold"><strong>netmask</strong></span></a>
</p>
</td>
<td>
<p>
Obtain the netmask that corresponds to the address, based on its
address class.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_eq_.html" title="ip::address_v4::operator="><span class="bold"><strong>operator=</strong></span></a>
</p>
</td>
<td>
<p>
Assign from another address.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/to_bytes.html" title="ip::address_v4::to_bytes"><span class="bold"><strong>to_bytes</strong></span></a>
</p>
</td>
<td>
<p>
Get the address in bytes, in network byte order.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/to_string.html" title="ip::address_v4::to_string"><span class="bold"><strong>to_string</strong></span></a>
</p>
</td>
<td>
<p>
Get the address as a string in dotted decimal format.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/to_ulong.html" title="ip::address_v4::to_ulong"><span class="bold"><strong>to_ulong</strong></span></a>
</p>
</td>
<td>
<p>
Get the address as an unsigned long in host byte order.
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="boost_asio.reference.ip__address_v4.h2"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.friends"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.friends">Friends</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_not__eq_.html" title="ip::address_v4::operator!="><span class="bold"><strong>operator!=</strong></span></a>
</p>
</td>
<td>
<p>
Compare two addresses for inequality.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_lt_.html" title="ip::address_v4::operator<"><span class="bold"><strong>operator<</strong></span></a>
</p>
</td>
<td>
<p>
Compare addresses for ordering.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_lt__eq_.html" title="ip::address_v4::operator<="><span class="bold"><strong>operator<=</strong></span></a>
</p>
</td>
<td>
<p>
Compare addresses for ordering.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_eq__eq_.html" title="ip::address_v4::operator=="><span class="bold"><strong>operator==</strong></span></a>
</p>
</td>
<td>
<p>
Compare two addresses for equality.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_gt_.html" title="ip::address_v4::operator>"><span class="bold"><strong>operator></strong></span></a>
</p>
</td>
<td>
<p>
Compare addresses for ordering.
</p>
</td>
</tr>
<tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_gt__eq_.html" title="ip::address_v4::operator>="><span class="bold"><strong>operator>=</strong></span></a>
</p>
</td>
<td>
<p>
Compare addresses for ordering.
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="boost_asio.reference.ip__address_v4.h3"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.related_functions"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.related_functions">Related Functions</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody><tr>
<td>
<p>
<a class="link" href="ip__address_v4/operator_lt__lt_.html" title="ip::address_v4::operator<<"><span class="bold"><strong>operator<<</strong></span></a>
</p>
</td>
<td>
<p>
Output an address as a string.
</p>
</td>
</tr></tbody>
</table></div>
<p>
The <a class="link" href="ip__address_v4.html" title="ip::address_v4"><code class="computeroutput"><span class="identifier">ip</span><span class="special">::</span><span class="identifier">address_v4</span></code></a>
class provides the ability to use and manipulate IP version 4 addresses.
</p>
<h5>
<a name="boost_asio.reference.ip__address_v4.h4"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.thread_safety"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.thread_safety">Thread
Safety</a>
</h5>
<p>
<span class="emphasis"><em>Distinct</em></span> <span class="emphasis"><em>objects:</em></span> Safe.
</p>
<p>
<span class="emphasis"><em>Shared</em></span> <span class="emphasis"><em>objects:</em></span> Unsafe.
</p>
<h5>
<a name="boost_asio.reference.ip__address_v4.h5"></a>
<span class="phrase"><a name="boost_asio.reference.ip__address_v4.requirements"></a></span><a class="link" href="ip__address_v4.html#boost_asio.reference.ip__address_v4.requirements">Requirements</a>
</h5>
<p>
<span class="emphasis"><em>Header: </em></span><code class="literal">boost/asio/ip/address_v4.hpp</code>
</p>
<p>
<span class="emphasis"><em>Convenience header: </em></span><code class="literal">boost/asio.hpp</code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="ip__address/to_v6.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="ip__address_v4/address_v4.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {'content_hash': 'aa8d64ca9e23f813de567d55ad2a88d7', 'timestamp': '', 'source': 'github', 'line_count': 468, 'max_line_length': 434, 'avg_line_length': 34.95940170940171, 'alnum_prop': 0.48829533647087586, 'repo_name': 'BenKeyFSI/poedit', 'id': 'd81937bbffa318fcfcb91ef2726a766fbc20d462', 'size': '16361', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'deps/boost/doc/html/boost_asio/reference/ip__address_v4.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '24827'}, {'name': 'C++', 'bytes': '913779'}, {'name': 'Inno Setup', 'bytes': '11293'}, {'name': 'Makefile', 'bytes': '9174'}, {'name': 'Objective-C', 'bytes': '4693'}, {'name': 'Objective-C++', 'bytes': '15875'}, {'name': 'Python', 'bytes': '3040'}, {'name': 'Ruby', 'bytes': '232'}, {'name': 'Shell', 'bytes': '10607'}]} |
import { Injectable, Pipe, PipeTransform } from '@angular/core';
// libs
import * as _ from 'lodash';
// module
import { I18NRouterService, ROOT_ROUTE_PREFIX } from './i18n-router.service';
@Injectable()
@Pipe({
name: 'i18nRouter',
pure: false
})
export class I18NRouterPipe implements PipeTransform {
constructor(private readonly i18nRouter: I18NRouterService) {
}
transform(value: string | Array<any>): string {
if (typeof value === 'string' && _.get(value, 'length', 0))
throw new Error('Query must be an empty string or an array!');
if (!this.i18nRouter.languageCode || !this.i18nRouter.useLocalizedRoutes)
return `/${typeof value === 'string' ? value : value.join('/')}`;
if (_.get(value, 'length', 0) === 0)
return `/${this.i18nRouter.languageCode}`;
return `/${this.translateQuery(value)}`;
}
private translateQuery(value: string | Array<any>): string {
const translateBatch: Array<any> = [];
let batchKey = '';
(value as Array<any>).forEach((segment: any, index: number) => {
if (typeof segment === 'string') {
let prefix = '';
let currentKey = `${ROOT_ROUTE_PREFIX}.${segment}`;
if (index === 0) {
prefix = this.i18nRouter.getTranslation(currentKey);
if (prefix) {
batchKey = currentKey;
translateBatch.push(this.i18nRouter.languageCode);
}
}
currentKey = index === 0 ? (prefix ? batchKey : segment) : `${batchKey}.${segment}`;
const translatedSegment = this.i18nRouter.getTranslation(currentKey);
if (translatedSegment)
batchKey = currentKey;
translateBatch.push(translatedSegment || segment);
} else
translateBatch.push(segment);
});
return translateBatch.join('/');
}
}
| {'content_hash': 'eddb5d02621dbfcd0fabbbdd0de8ad68', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 92, 'avg_line_length': 28.825396825396826, 'alnum_prop': 0.6172907488986784, 'repo_name': 'fulls1z3/ngx-i18n-router', 'id': 'a4d70e4b49d5a5c9777bc2cfeba7c2e23ed2ea76', 'size': '1827', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/@ngx-i18n-router/core/src/i18n-router.pipe.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'TypeScript', 'bytes': '49150'}]} |
gulp-if 
=======
A ternary gulp plugin: conditionally control the flow of vinyl objects.
**Note**: Badly behaved plugins can often get worse when used with gulp-if. Typically the fix is not in gulp-if.
**Note**: Works great with [lazypipe](https://github.com/OverZealous/lazypipe), see below
## Usage
1: Conditionally filter content
**Condition**
![][condition]
```javascript
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var condition = true; // TODO: add business logic
gulp.task('task', function() {
gulp.src('./src/*.js')
.pipe(gulpif(condition, uglify()))
.pipe(gulp.dest('./dist/'));
});
```
Only uglify the content if the condition is true, but send all the files to the dist folder
2: Ternary filter
**Ternary**
![][ternary]
```javascript
var gulpif = require('gulp-if');
var uglify = require('gulp-uglify');
var beautify = require('gulp-beautify');
var condition = function (file) {
// TODO: add business logic
return true;
}
gulp.task('task', function() {
gulp.src('./src/*.js')
.pipe(gulpif(condition, uglify(), beautify()))
.pipe(gulp.dest('./dist/'));
});
```
If condition returns true, uglify else beautify, then send everything to the dist folder
3: Remove things from the stream
**Remove from here on**
![][exclude]
```javascript
var gulpIgnore = require('gulp-ignore');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var condition = './gulpfile.js';
gulp.task('task', function() {
gulp.src('./*.js')
.pipe(jshint())
.pipe(gulpIgnore.exclude(condition))
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
});
```
Run JSHint on everything, remove gulpfile from the stream, then uglify and write everything else.
4: Exclude things from the stream
**Exclude things from entering the stream**
![][glob]
```javascript
var uglify = require('gulp-uglify');
gulp.task('task', function() {
gulp.src(['./*.js', '!./node_modules/**'])
.pipe(uglify())
.pipe(gulp.dest('./dist/'));
});
```
Grab all JavaScript files that aren't in the node_modules folder, uglify them, and write them.
This is fastest because nothing in node_modules ever leaves `gulp.src()`
## works great with [lazypipe](https://github.com/OverZealous/lazypipe)
Lazypipe creates a function that initializes the pipe chain on use. This allows you to create a chain of events inside the gulp-if condition. This scenario will run jshint analysis and reporter only if the linting flag is true.
```js
var gulpif = require('gulp-if');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var lazypipe = require('lazypipe');
var linting = false;
var compressing = false;
var jshintChannel = lazypipe()
// adding a pipeline step
.pipe(jshint) // notice the stream function has not been called!
.pipe(jshint.reporter)
// adding a step with an argument
.pipe(jshint.reporter, 'fail');
gulp.task('scripts', function () {
return gulp.src(paths.scripts.src)
.pipe(gulpif(linting, jshintChannel()))
.pipe(gulpif(compressing, uglify()))
.pipe(gulp.dest(paths.scripts.dest));
});
```
[source](https://github.com/spenceralger/gulp-jshint/issues/38#issuecomment-40423932)
## works great inside [lazypipe](https://github.com/OverZealous/lazypipe)
Lazypipe assumes that all function parameters are static, gulp-if arguments need to be instantiated inside each lazypipe. This difference can be easily solved by passing a function on the lazypipe step
```js
var gulpif = require('gulp-if');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var lazypipe = require('lazypipe');
var compressing = false;
var jsChannel = lazypipe()
// adding a pipeline step
.pipe(jshint) // notice the stream function has not been called!
.pipe(jshint.reporter)
// adding a step with an argument
.pipe(jshint.reporter, 'fail')
// you can't say: .pipe(gulpif, compressing, uglify)
// because uglify needs to be instantiated separately in each lazypipe instance
// you can say this instead:
.pipe(function () {
return gulpif(compressing, uglify());
});
// why does this work? lazypipe calls the function, passing in the no arguments to it,
// it instantiates a new gulp-if pipe and returns it to lazypipe.
gulp.task('scripts', function () {
return gulp.src(paths.scripts.src)
.pipe(jsChannel())
.pipe(gulp.dest(paths.scripts.dest));
});
```
[source](https://github.com/robrich/gulp-if/issues/32)
## gulp-if API
### gulpif(condition, stream [, elseStream, [, minimatchOptions]])
gulp-if will pipe data to `stream` whenever `condition` is truthy.
If `condition` is falsey and `elseStream` is passed, data will pipe to `elseStream`
After data is piped to `stream` or `elseStream` or neither, data is piped down-stream.
#### Parameters
##### condition
Type: `boolean` or [`stat`](http://nodejs.org/api/fs.html#fs_class_fs_stats) object or `function` that takes in a vinyl file and returns a boolean or `RegularExpression` that works on the `file.path`
The condition parameter is any of the conditions supported by [gulp-match](https://github.com/robrich/gulp-match). The `file.path` is passed into `gulp-match`.
If a function is given, then the function is passed a vinyl `file`. The function should return a `boolean`.
##### stream
Stream for gulp-if to pipe data into when condition is truthy.
##### elseStream
Optional, Stream for gulp-if to pipe data into when condition is falsey.
##### minimatchOptions
Optional, if it's a glob condition, these options are passed to [https://github.com/isaacs/minimatch](minimatch).
LICENSE
-------
(MIT License)
Copyright (c) 2014 [Richardson & Sons, LLC](http://richardsonandsons.com/)
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.
[condition]: https://rawgithub.com/robrich/gulp-if/master/img/condition.svg
[ternary]: https://rawgithub.com/robrich/gulp-if/master/img/ternary.svg
[exclude]: https://rawgithub.com/robrich/gulp-if/master/img/exclude.svg
[glob]: https://rawgithub.com/robrich/gulp-if/master/img/glob.svg
| {'content_hash': 'ff2afaa5110f6f59555e9a960e10f440', 'timestamp': '', 'source': 'github', 'line_count': 231, 'max_line_length': 229, 'avg_line_length': 30.78787878787879, 'alnum_prop': 0.7217379077615298, 'repo_name': 'zhangyue1208/eightcig-shopify-theme', 'id': 'aec5632ce8f171bcf20ac71892b0f49315a283d3', 'size': '7112', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'node_modules/gulp-if/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '102805'}, {'name': 'HTML', 'bytes': '2491'}, {'name': 'JavaScript', 'bytes': '36449'}, {'name': 'Liquid', 'bytes': '1183988'}, {'name': 'Ruby', 'bytes': '6231'}]} |
/******************************************************
* Unbalanced Tree Search v2.1 *
* Based on the implementation available at *
* http://sourceforge.net/projects/uts-benchmark *
******************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h" /* for _GNU_SOURCE */
#endif
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h> /* for INT_MAX */
#include <math.h> /* for floor, log, sin */
#include <omp.h>
#include <qthread/qthread.h>
#include <qthread/qtimer.h>
#define SILENT_ARGPARSING
#include "argparsing.h"
#include "log.h"
#define BRG_RNG // Select RNG
#include "../../utils/rng/rng.h"
#define PRINT_STATS 1
#define MAXNUMCHILDREN 100
static size_t nodecount;
typedef enum {
BIN = 0,
GEO,
HYBRID,
BALANCED
} tree_t;
static char *type_names[] = {
"Binomial",
"Geometric",
"Hybrid",
"Balanced"
};
typedef enum {
LINEAR = 0,
EXPDEC,
CYCLIC,
FIXED
} shape_t;
static char *shape_names[] = {
"Linear decrease",
"Exponential decrease",
"Cyclic",
"Fixed branching factor"
};
typedef struct {
int height; // Depth of node in the tree
struct state_t state; // Local RNG state
int num_children;
} node_t;
// Default values
static tree_t tree_type = GEO;
static double bf_0 = 4.0;
static int root_seed = 0;
static int num_samples = 1;
static int tree_depth = 6;
static shape_t shape_fn = LINEAR;
static int non_leaf_bf = 4;
static double non_leaf_prob = 15.0 / 64.0;
static double shift_depth = 0.5;
// Tree metrics
static uint64_t tree_height = 0;
static uint64_t num_leaves = 0;
static double normalize(int n)
{
if (n < 0) {
printf("*** toProb: rand n = %d out of range\n", n);
}
return ((n < 0) ? 0.0 : ((double)n) / (double)INT_MAX);
}
static int calc_num_children_bin(node_t *parent)
{
int v = rng_rand(parent->state.state);
double d = normalize(v);
return (d < non_leaf_prob) ? non_leaf_bf : 0;
}
static int calc_num_children(node_t *parent)
{
int num_children = 0;
if (parent->height == 0) { num_children = (int)floor(bf_0); } else { num_children = calc_num_children_bin(parent); }
if (parent->height == 0) {
int root_bf = (int)ceil(bf_0);
if (num_children > root_bf) {
printf("*** Number of children truncated from %d to %d\n",
num_children, root_bf);
num_children = root_bf;
}
} else {
if (num_children > MAXNUMCHILDREN) {
printf("*** Number of children truncated from %d to %d\n",
num_children, MAXNUMCHILDREN);
num_children = MAXNUMCHILDREN;
}
}
return num_children;
}
#define BIG_STACKS
// Notes:
// - Each task receives distinct copy of parent
// - Copy of child is shallow, be careful with `state` member
static long visit(node_t *parent,
int num_children)
{
uint64_t num_descendants = 1;
#ifdef BIG_STACKS
uint64_t child_descendants[num_children];
node_t child_nodes[num_children];
#else
uint64_t *child_descendants;
node_t *child_nodes;
if (num_children > 0) {
child_descendants = calloc(sizeof(uint64_t), num_children);
child_nodes = malloc(sizeof(node_t) * num_children);
}
#endif
// Spawn children, if any
for (int i = 0; i < num_children; i++) {
node_t *child = &child_nodes[i];
child->height = parent->height + 1;
for (int j = 0; j < num_samples; j++) {
rng_spawn(parent->state.state, child->state.state, i);
}
child->num_children = calc_num_children(child);
#pragma omp task untied firstprivate(i, child) shared(child_descendants)
child_descendants[i] = visit(child, child->num_children);
}
#pragma omp taskwait
// #pragma omp parallel for reduction(+:num_descendants)
for (int i = 0; i < num_children; i++) {
num_descendants += child_descendants[i];
}
#ifndef BIG_STACKS
if (num_children > 0) {
free(child_descendants);
free(child_nodes);
}
#endif
return num_descendants;
}
#ifdef PRINT_STATS
static void print_stats(void)
{
LOG_UTS_PARAMS_YAML()
fflush(stdout);
}
#else /* ifdef PRINT_STATS */
static void print_banner(void)
{
printf("UTS - Unbalanced Tree Search 2.1 (C/Qthreads)\n");
printf("Tree type:%3d (%s)\n", tree_type, type_names[tree_type]);
printf("Tree shape parameters:\n");
printf(" root branching factor b_0 = %.1f, root seed = %d\n",
bf_0, root_seed);
if ((tree_type == GEO) || (tree_type == HYBRID)) {
printf(" GEO parameters: gen_mx = %d, shape function = %d (%s)\n",
tree_depth, shape_fn, shape_names[shape_fn]);
}
if ((tree_type == BIN) || (tree_type == HYBRID)) {
double q = non_leaf_prob;
int m = non_leaf_bf;
double es = (1.0 / (1.0 - q * m));
printf(" BIN parameters: q = %f, m = %d, E(n) = %f, E(s) = %.2f\n",
q, m, q * m, es);
}
if (tree_type == HYBRID) {
printf(" HYBRID: GEO from root to depth %d, then BIN\n",
(int)ceil(shift_depth * tree_depth));
}
if (tree_type == BALANCED) {
printf(" BALANCED parameters: gen_mx = %d\n", tree_depth);
printf(" Expected size: %llu nodes, %llu leaves\n",
(unsigned long long)((pow(bf_0, tree_depth + 1) - 1.0) / (bf_0 - 1.0)),
(unsigned long long)pow(bf_0, tree_depth));
}
printf("Random number generator: ");
printf("SHA-1 (state size = %ldB)\n", sizeof(struct state_t));
printf("Compute granularity: %d\n", num_samples);
printf("Execution strategy:\n");
printf(" Workers: %d\n", omp_get_num_threads());
printf("\n");
fflush(stdout);
}
#endif /* ifdef PRINT_STATS */
int main(int argc,
char *argv[])
{
uint64_t total_num_nodes = 0;
qtimer_t timer;
double total_time = 0.0;
int threads = 1;
CHECK_VERBOSE();
{
unsigned int tmp = (unsigned int)tree_type;
NUMARG(tmp, "UTS_TREE_TYPE");
if (tmp <= BALANCED) {
tree_type = (tree_t)tmp;
} else {
fprintf(stderr, "invalid tree type\n");
return EXIT_FAILURE;
}
tmp = (unsigned int)shape_fn;
NUMARG(tmp, "UTS_SHAPE_FN");
if (tmp <= FIXED) {
shape_fn = (shape_t)tmp;
} else {
fprintf(stderr, "invalid shape function\n");
return EXIT_FAILURE;
}
}
DBLARG(bf_0, "UTS_BF_0");
NUMARG(root_seed, "UTS_ROOT_SEED");
NUMARG(tree_depth, "UTS_TREE_DEPTH");
DBLARG(non_leaf_prob, "UTS_NON_LEAF_PROB");
NUMARG(non_leaf_bf, "UTS_NON_LEAF_NUM");
NUMARG(shift_depth, "UTS_SHIFT_DEPTH");
NUMARG(num_samples, "UTS_NUM_SAMPLES");
#pragma omp parallel
#pragma omp single
{
#ifdef PRINT_STATS
print_stats();
#else
print_banner();
#endif
threads = omp_get_num_threads();
}
timer = qtimer_create();
qtimer_start(timer);
node_t root;
root.height = 0;
rng_init(root.state.state, root_seed);
root.num_children = calc_num_children(&root);
nodecount = 1;
long retval;
#pragma omp parallel
#pragma omp single nowait
#pragma omp task untied
retval = visit(&root, root.num_children);
total_num_nodes = retval;
qtimer_stop(timer);
total_time = qtimer_secs(timer);
qtimer_destroy(timer);
#ifdef PRINT_STATS
LOG_UTS_RESULTS_YAML(total_num_nodes, total_time)
LOG_ENV_OMP_YAML(threads)
#else
printf("Tree size = %lu, tree depth = %d, num leaves = %llu (%.2f%%)\n",
(unsigned long)total_num_nodes,
(int)tree_height,
(unsigned long long)num_leaves,
num_leaves / (float)total_num_nodes * 100.0);
printf("Wallclock time = %.3f sec, performance = %.0f "
"nodes/sec (%.0f nodes/sec per PE)\n\n",
total_time,
total_num_nodes / total_time,
total_num_nodes / total_time / omp_get_num_threads());
#endif /* ifdef PRINT_STATS */
return 0;
}
/* vim:set expandtab */
| {'content_hash': 'b4419b6a7e395f9c3c8592f2ba96dc69', 'timestamp': '', 'source': 'github', 'line_count': 321, 'max_line_length': 120, 'avg_line_length': 25.869158878504674, 'alnum_prop': 0.5651493256262042, 'repo_name': 'hildeth/chapel', 'id': '5ac3e3ea62bcbcb55ffaf85c90e952709a5cfa28', 'size': '8304', 'binary': False, 'copies': '7', 'ref': 'refs/heads/string-as-rec', 'path': 'third-party/qthread/qthread-1.10/test/benchmarks/sc12/uts_omp.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2072'}, {'name': 'C', 'bytes': '3681629'}, {'name': 'C++', 'bytes': '3658156'}, {'name': 'CSS', 'bytes': '919'}, {'name': 'Chapel', 'bytes': '9885697'}, {'name': 'Cuda', 'bytes': '4304'}, {'name': 'Emacs Lisp', 'bytes': '14304'}, {'name': 'FORTRAN', 'bytes': '18153'}, {'name': 'Gnuplot', 'bytes': '5362'}, {'name': 'HTML', 'bytes': '2419'}, {'name': 'JavaScript', 'bytes': '50663'}, {'name': 'LLVM', 'bytes': '16367'}, {'name': 'Lex', 'bytes': '37800'}, {'name': 'Makefile', 'bytes': '107056'}, {'name': 'Mathematica', 'bytes': '4971'}, {'name': 'Perl', 'bytes': '246208'}, {'name': 'Python', 'bytes': '419394'}, {'name': 'Shell', 'bytes': '172877'}, {'name': 'TeX', 'bytes': '870121'}, {'name': 'VimL', 'bytes': '14876'}, {'name': 'Yacc', 'bytes': '2337'}, {'name': 'Zimpl', 'bytes': '1115'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Unicorn Library: Non-Unicode Encodings</title>
<link type="text/css" rel="stylesheet" href="style.css"/>
</head>
<body>
<h1 id="unicorn-library-non-unicode-encodings"><a href="index.html">Unicorn Library</a>: Non-Unicode Encodings</h1>
<p><em>Unicode library for C++ by Ross Smith</em></p>
<ul>
<li><code>#include "unicorn/mbcs.hpp"</code></li>
</ul>
<p>This module defines functions for conversion between UTF-8 and non-Unicode
encodings, as well as external UTF encodings with a specific byte order.</p>
<h2 id="contents">Contents</h2>
<div class="toc">
<ul>
<li><a href="#unicorn-library-non-unicode-encodings">Unicorn Library: Non-Unicode Encodings</a><ul>
<li><a href="#contents">Contents</a></li>
<li><a href="#constants">Constants</a></li>
<li><a href="#exceptions">Exceptions</a></li>
<li><a href="#conversion-functions">Conversion functions</a></li>
<li><a href="#utility-functions">Utility functions</a></li>
</ul>
</li>
</ul>
</div>
<h2 id="constants">Constants</h2>
<div class="defns">
<ul>
<li><code>constexpr uint32_t Mbcs::</code><strong><code>strict</code></strong></li>
</ul>
<p>Constant used to control how encoding names are interpreted (see below).</p>
</div>
<h2 id="exceptions">Exceptions</h2>
<div class="defns">
<ul>
<li><code>class</code> <strong><code>UnknownEncoding</code></strong><code>: public std::runtime_error</code><ul>
<li><code>UnknownEncoding::</code><strong><code>UnknownEncoding</code></strong><code>()</code></li>
<li><code>explicit UnknownEncoding::</code><strong><code>UnknownEncoding</code></strong><code>(const Ustring& encoding, const Ustring& details = {})</code></li>
<li><code>explicit UnknownEncoding::</code><strong><code>UnknownEncoding</code></strong><code>(uint32_t encoding, const Ustring& details = {})</code></li>
<li><code>const char* UnknownEncoding::</code><strong><code>encoding</code></strong><code>() const noexcept</code></li>
</ul>
</li>
</ul>
<p>Exception thrown to report an unknown encoding name or number.</p>
</div>
<h2 id="conversion-functions">Conversion functions</h2>
<div class="defns">
<ul>
<li><code>void</code> <strong><code>import_string</code></strong><code>(const string& src, Ustring& dst, const Ustring& enc = "", uint32_t flags = 0)</code></li>
<li><code>void</code> <strong><code>import_string</code></strong><code>(const string& src, Ustring& dst, uint32_t enc, uint32_t flags = 0)</code></li>
<li><code>void</code> <strong><code>export_string</code></strong><code>(const Ustring& src, string& dst, const Ustring& enc = "", uint32_t flags = 0)</code></li>
<li><code>void</code> <strong><code>export_string</code></strong><code>(const Ustring& src, string& dst, uint32_t enc, uint32_t flags = 0)</code></li>
</ul>
<p>These functions convert from an external multibyte encoding to UTF-8
(<code>import_string()</code>), and from UTF-8 to an external multibyte encoding
(<code>export_string()</code>). They work by calling the operating system's native code
conversion API (<code>iconv()</code> on Unix; <code>MultiByteToWideChar()</code> and
<code>WideCharToMultiByte()</code> on Windows).</p>
<p>Encodings can be identified either by name or by a Windows "code page" number.
Either kind of identifier can be used on any system; a built-in lookup table
is used to convert to the form required by the native API. Besides the normal
names and numbers associated with standard encodings, the following special
values can be used:</p>
<ul>
<li><code>"char"</code> or an empty string = Use the current locale's default multibyte character encoding.</li>
<li><code>"wchar_t"</code> = Use the operating system's default wide character encoding.</li>
<li><code>"utf"</code> = Inspect the string and try to guess the UTF encoding.</li>
</ul>
<p>The default local encoding is used if no encoding is specified.</p>
<p>An unrecognised encoding name or number will cause an <code>UnknownEncoding</code>
exception to be thrown. The code that parses encoding names allows a good deal
of leeway for variations in punctuation and capitalization, but since we are
relying on system APIs for the actual conversion, no promises can be made
about any particular encoding (other than the UTF encodings) being correctly
recognised and handled.</p>
<p>The <code>flags</code> argument can be <code>Utf::replace</code> (the default) or <code>Utf::throws</code>
(these are defined in <a href="utf.html"><code>unicorn/utf</code></a>). If <code>Utf::replace</code> is
selected, invalid data in the input string will be replaced with a system-
defined replacement character (not necessarily <code>U+FFFD</code>); if <code>Utf::throws</code> is
selected, invalid data will cause an <code>EncodingError</code> exception to be thrown,
if this is detectable (see below).</p>
<p>Ignoring invalid encoding is not allowed here; if any MBCS function that takes
a flags argument is passed the <code>Utf::ignore</code> flags, it will throw
<code>std::invalid_argument</code>.</p>
<p>If the constant <code>Mbcs::strict</code> is included in the flags, no attempt will be
made to translate the encoding name or number supplied into an equivalent
acceptable to the underlying API; the value supplied will simply be passed
unchanged (apart from conversion between string and integer where necessary).
This flag has no effect if no encoding is explicitly supplied.</p>
<p>These functions necessarily inherit some of the limitations of the underlying
native APIs. In particular, the Windows APIs do not reliably report encoding
errors; although the wrapper functions make a good faith attempt to respect
the error handling flags, in some cases the underlying conversion function
will go ahead and replace invalid data without reporting an error.</p>
</div>
<h2 id="utility-functions">Utility functions</h2>
<div class="defns">
<ul>
<li><code>Ustring</code> <strong><code>local_encoding</code></strong><code>(const Ustring& default_encoding = "utf-8")</code></li>
</ul>
<p>Returns the encoding of the current default locale. The default value will be
returned if no encoding information can be obtained from the operating system.</p></body>
</html>
| {'content_hash': '01ae33cefea3d07be433315cf43e4eee', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 173, 'avg_line_length': 58.5, 'alnum_prop': 0.7353652636671505, 'repo_name': 'CaptainCrowbar/unicorn-lib', 'id': 'da6b0e05d6fffbd55cb963d0eb3b3a869faab1a1', 'size': '6201', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/mbcs.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '4970950'}, {'name': 'CSS', 'bytes': '2843'}, {'name': 'Makefile', 'bytes': '23569'}, {'name': 'Python', 'bytes': '33413'}, {'name': 'Shell', 'bytes': '2476'}]} |
package org.springframework.cloud.netflix.ribbon;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.named.NamedContextFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.netflix.client.IClient;
import com.netflix.client.IClientConfigAware;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ILoadBalancer;
/**
* A factory that creates client, load balancer and client configuration instances. It
* creates a Spring ApplicationContext per client name, and extracts the beans that it
* needs from there.
*
* @author Spencer Gibb
* @author Dave Syer
*/
public class SpringClientFactory extends NamedContextFactory<RibbonClientSpecification> {
static final String NAMESPACE = "ribbon";
public SpringClientFactory() {
super(RibbonClientConfiguration.class, NAMESPACE, "ribbon.client.name");
}
/**
* Get the rest client associated with the name.
* @throws RuntimeException if any error occurs
*/
public <C extends IClient<?, ?>> C getClient(String name, Class<C> clientClass) {
return getInstance(name, clientClass);
}
/**
* Get the load balancer associated with the name.
* @throws RuntimeException if any error occurs
*/
public ILoadBalancer getLoadBalancer(String name) {
return getInstance(name, ILoadBalancer.class);
}
/**
* Get the client config associated with the name.
* @throws RuntimeException if any error occurs
*/
public IClientConfig getClientConfig(String name) {
return getInstance(name, IClientConfig.class);
}
/**
* Get the load balancer context associated with the name.
* @throws RuntimeException if any error occurs
*/
public RibbonLoadBalancerContext getLoadBalancerContext(String serviceId) {
return getInstance(serviceId, RibbonLoadBalancerContext.class);
}
static <C> C instantiateWithConfig(Class<C> clazz, IClientConfig config) {
return instantiateWithConfig(null, clazz, config);
}
static <C> C instantiateWithConfig(AnnotationConfigApplicationContext context,
Class<C> clazz, IClientConfig config) {
C result = null;
if (IClientConfigAware.class.isAssignableFrom(clazz)) {
IClientConfigAware obj = (IClientConfigAware) BeanUtils.instantiate(clazz);
obj.initWithNiwsConfig(config);
@SuppressWarnings("unchecked")
C value = (C) obj;
result = value;
}
else {
try {
if (clazz.getConstructor(IClientConfig.class) != null) {
result = clazz.getConstructor(IClientConfig.class)
.newInstance(config);
}
else {
result = BeanUtils.instantiate(clazz);
}
}
catch (Throwable ex) {
// NOPMD
}
}
if (context != null) {
context.getAutowireCapableBeanFactory().autowireBean(result);
}
return result;
}
public <C> C getInstance(String name, Class<C> type) {
C instance = super.getInstance(name, type);
if (instance != null) {
return instance;
}
IClientConfig config = getInstance(name, IClientConfig.class);
return instantiateWithConfig(getContext(name), type, config);
}
}
| {'content_hash': '0b74dcc85d91f50c7bb24a1cfc92d428', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 89, 'avg_line_length': 29.047169811320753, 'alnum_prop': 0.742448847028256, 'repo_name': 'jkschneider/spring-cloud-netflix', 'id': '6dfdd1dffb44e1edf9320ec05b1429862b71ada2', 'size': '3699', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/ribbon/SpringClientFactory.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5150'}, {'name': 'CSS', 'bytes': '52380'}, {'name': 'FreeMarker', 'bytes': '19330'}, {'name': 'HTML', 'bytes': '10448'}, {'name': 'Java', 'bytes': '1339512'}, {'name': 'JavaScript', 'bytes': '33316'}, {'name': 'Ruby', 'bytes': '481'}, {'name': 'Shell', 'bytes': '8280'}]} |
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright (c) 2013 Soichiro Kashima.
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.
-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<corners android:radius="@dimen/rb__radius_button" />
<gradient
android:angle="270"
android:endColor="#FFCCCCCC"
android:startColor="#FFF6F6F6" />
<stroke
android:width="@dimen/rb__stroke_width_button_default"
android:color="#FFCCCCCC" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<corners android:radius="@dimen/rb__radius_button" />
<solid android:color="#CC99CC00" />
<stroke
android:width="@dimen/rb__stroke_width_button_default"
android:color="#99669900" />
</shape>
</item>
</layer-list> | {'content_hash': 'b505a07aae1b718720add772f2221f90', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 79, 'avg_line_length': 39.294117647058826, 'alnum_prop': 0.6651696606786427, 'repo_name': '0359xiaodong/RichButtons', 'id': '305d7509baaceee0604386184b7f68715a683244', 'size': '2004', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'richbuttons/res/drawable/rb__button_green_pressed.xml', 'mode': '33188', 'license': 'mit', 'language': []} |
Audiopia
========
[](https://raw.githubusercontent.com/almightycouch/audiopia/master/LICENSE)
[](http://github.com/almightycouch/audiopia/issues)

[Audiopia][] is a peer-to-peer music streaming platform built with modern Web Standards technologies (such as [WebSockets][] and [WebRTC][]) and APIs ([MediaSource API][], [Web Audio API][]).
No online storage
-----------------
Your songs are not stored anywhere but on your computer. Only meta-informations (title, album, artist, year, etc.) are available online.
When you listen to a song, you stream the audio content directly from an other user.
Streaming is performed by a combination of client-server access and P2P protocol between Web users.
This is done in an adaptive and transparent way in order to reduce server bandwidth costs while ensuring low latency and smooth playback for users.
No installation required
------------------------
Audiopia is entirely built with Web Standards. For you this means no plugins or installation.
You only need one of the supported browsers listed below.
Start your browser, type the URL and you are ready to go.
No registration required
------------------------
You don't have to register to use Audiopia. Go to [audiopia.io](https://audiopia.io) and start listening to the music you love.
In fact, Audiopia is fully anonymous, our service is about music, not users.
__Note:__ We do not collect or store any user specific information.
How it works
------------
We built our platform with [Meteor][] (a complete open source framework for building reactive web and mobile apps in pure JavaScript) and [PeerJS][] (a Javascript library which provides a complete, configurable, and easy-to-use peer-to-peer connection API).
Each time a user accesses [audiopia.io][Audiopia], he gets a new generated id from the server.
This id is used to identify each user as the owner of each song he makes available.
The id is also used to create peer-to-peer data or media stream connections between users.
When the user imports new songs, the browser analyses each file and parses its meta-informations (title, album, artist, year, etc.).
For each valid audio file loaded by the user, a new document is inserted to the server's database:
{"title": "Come closer", "artist: "Guts", ..., "mime": "audio/m4a", "owner": "gd8FMwsTS4T4ejytg"}
The server implements a fully-reactive NoSQL database ([MongoDB][]) to keep track of available songs.
It's data is instantly reflected to every connected user (see [Meteor][] for more details).
When a user exists, the server automatically remove all of his songs on the database.
To stream a song, the browser uses the owner's identifier to create a peer-to-peer media connection ([PeerJS][]) and stream the audio file (see [WebRTC][], [Web Audio API][] and [MediaSource API][]).
Check the code for more details.
Browser support
---------------
We use a set of open standards technologies and apis which are not supported by all browsers.
Before you start, [check](//caniuse.com) if your browser supports following requirements:
* [WebSockets][]
* [WebRTC][]
* [Web Audio API][]
* [MediaSource API][]
* [Filesystem API][] (optional)
* [IndexedDB][] (optional)
License & Warranty
------------------
Copyright (c) 2015 Mario Flach under the MIT License (MIT)
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.
[Audiopia]: //www.audiopia.io/
<!-- third-parties -->
[Meteor]: //www.meteor.com/
[PeerJS]: //www.peerjs.com/
[MongoDB]: //www.mongodb.org/
<!-- w3c web standards -->
[WebSockets]: //www.w3.org/TR/websockets/
[WebRTC]: //www.w3.org/TR/webrtc/
[Web Audio API]: //www.w3.org/TR/webaudio/
[MediaSource API]: //www.w3.org/TR/media-source/
[IndexedDB]: //www.w3.org/TR/indexeddb/
[Filesystem API]: //www.w3.org/TR/file-system-api/
| {'content_hash': '7458d8224f5deed401e47837f76eaf84', 'timestamp': '', 'source': 'github', 'line_count': 105, 'max_line_length': 257, 'avg_line_length': 42.2, 'alnum_prop': 0.727375310313699, 'repo_name': 'redrabbit/audiopia', 'id': 'e7b5540d929a2818224f535f174488641ac2378e', 'size': '4431', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '49'}, {'name': 'Elixir', 'bytes': '69155'}, {'name': 'HTML', 'bytes': '1121'}, {'name': 'JavaScript', 'bytes': '2727'}]} |
#ifndef MGEN_STRINGOUTPUTSTREAM_H_
#define MGEN_STRINGOUTPUTSTREAM_H_
#include <string>
namespace mgen {
/**
* Represents an in-memory data output for MGen writers. A StringOutputStream
* wraps a provided std::string without making a copy, or allocates its own string
* (depending on choice of constructor). When data is written to this
* StringOutputStream it is added to the underlying string.
*/
class StringOutputStream {
public:
/**
* Wraps a provided string in this StringOutputStream. No copy is made,
* so the caller is responsible for keeping the string alive for as long
* as this StringOutputStream exists.
*/
StringOutputStream(std::string& output) :
m_internalString(0),
m_writeTarget(&output) {
}
/**
* Creates a StringOutputStream around an internally allocated std::string.
*/
StringOutputStream() :
m_writeTarget(&m_internalString) {
}
/**
* Writes nBytes bytes to the underlying string. The bytes are pushed back
* at the end of the underlying string.
*/
void write(const void* src, const int nBytes) {
str().insert(
str().end(),
reinterpret_cast<const char*>(src),
reinterpret_cast<const char*>(src) + nBytes);
}
/**
* Clears the underlying wrapped string (std::string::clear())
*/
void reset() {
str().clear();
}
/**
* Gets the underlying string
*/
std::string& str() {
return *m_writeTarget;
}
private:
std::string m_internalString;
std::string * m_writeTarget;
StringOutputStream(const StringOutputStream&);
StringOutputStream& operator=(const StringOutputStream&);
};
} /* namespace mgen */
#endif /* MGEN_STRINGOUTPUTSTREAM_H_ */
| {'content_hash': '474e9b9cc2df623ea5c01a5ca17f0922', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 83, 'avg_line_length': 26.214285714285715, 'alnum_prop': 0.6294277929155313, 'repo_name': 'culvertsoft/mgen', 'id': 'e48fecc0da5dca54e3f22944598ff19157fd13db', 'size': '1835', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mgen-cpplib/src/main/cpp/mgen/serialization/StringOutputStream.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '164'}, {'name': 'C++', 'bytes': '359960'}, {'name': 'CMake', 'bytes': '1778'}, {'name': 'Java', 'bytes': '406413'}, {'name': 'JavaScript', 'bytes': '46839'}, {'name': 'Python', 'bytes': '17644'}, {'name': 'Scala', 'bytes': '349889'}, {'name': 'Shell', 'bytes': '78'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>aac-tactics: 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.13.0 / aac-tactics - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
aac-tactics
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-13 02:27:09 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-13 02:27:09 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.13.0 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.14.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.14.0 Official release 4.14.0
ocaml-config 2 OCaml Switch Configuration
ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-community/aac-tactics"
dev-repo: "git+https://github.com/coq-community/aac-tactics.git"
bug-reports: "https://github.com/coq-community/aac-tactics/issues"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/AAC_tactics"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [
"keyword:reflexive tactic"
"keyword:rewriting"
"keyword:rewriting modulo associativity and commutativity"
"keyword:rewriting modulo ac"
"keyword:decision procedure"
"category:Miscellaneous/Coq Extensions"
"date:2018-10-04"
"logpath:AAC_tactics"
]
authors: [
"Damien Pous <>"
"Thomas Braibant <>"
"Fabian Kunze <>"
]
synopsis: "This Coq plugin provides tactics for rewriting universally quantified equations, modulo associative (and possibly commutative) operators"
flags: light-uninstall
url {
src: "https://github.com/coq-community/aac-tactics/archive/v8.8.0.tar.gz"
checksum: "md5=75de4d507926423e754c55694e826084"
}
</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-aac-tactics.8.8.0 coq.8.13.0</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0).
The following dependencies couldn't be met:
- coq-aac-tactics -> coq < 8.9~ -> ocaml < 4.10
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-aac-tactics.8.8.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': 'ba76f7faa3c5c8191cc03442141e92d7', 'timestamp': '', 'source': 'github', 'line_count': 175, 'max_line_length': 159, 'avg_line_length': 41.497142857142855, 'alnum_prop': 0.549160011016249, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '249a1003c0a2b71f54bb2431261915ed5fa2011a', 'size': '7287', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.14.0-2.0.10/released/8.13.0/aac-tactics/8.8.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
package com.amazonaws.services.organizations.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.organizations.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CreateAccountRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateAccountRequestProtocolMarshaller implements Marshaller<Request<CreateAccountRequest>, CreateAccountRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AWSOrganizationsV20161128.CreateAccount").serviceName("AWSOrganizations").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public CreateAccountRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<CreateAccountRequest> marshall(CreateAccountRequest createAccountRequest) {
if (createAccountRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<CreateAccountRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
createAccountRequest);
protocolMarshaller.startMarshalling();
CreateAccountRequestMarshaller.getInstance().marshall(createAccountRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| {'content_hash': '878f9b19267a6ac9a7ecbcb9499d1537', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 150, 'avg_line_length': 40.627450980392155, 'alnum_prop': 0.7611003861003861, 'repo_name': 'dagnir/aws-sdk-java', 'id': 'd33ec1f1c5290ef3d56d31f7a7229b65fbc66daa', 'size': '2652', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-organizations/src/main/java/com/amazonaws/services/organizations/model/transform/CreateAccountRequestProtocolMarshaller.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '157317'}, {'name': 'Gherkin', 'bytes': '25556'}, {'name': 'Java', 'bytes': '165755153'}, {'name': 'Scilab', 'bytes': '3561'}]} |
/*
* This is a manifest file that'll automatically include all the stylesheets available in this directory
* and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
* the top of the compiled file, but it's generally better to create a new file per style scope.
*= require_self
*= require_tree .
*/
html, body {
background-color: #4B7399;
font-family: Verdana, Helvetica, Arial;
font-size: 14px;
}
a img {
border: none;
}
a {
color: #0000FF;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
#container {
width: 75%;
margin: 0 auto;
background-color: #FFF;
padding: 20px 40px;
border: solid 1px black;
margin-top: 20px;
}
#flash_notice, #flash_error, #flash_alert {
padding: 5px 8px;
margin: 10px 0;
}
#flash_notice {
background-color: #CFC;
border: solid 1px #6C6;
}
#flash_error, #flash_alert {
background-color: #FCC;
border: solid 1px #C66;
}
form label {
display: block;
margin-bottom: 2px;
}
form .field, form .actions {
margin: 12px 0;
}
.fieldWithErrors {
display: inline;
}
.error_messages {
width: 400px;
border: 2px solid #CF0000;
padding: 0px;
margin-bottom: 20px;
background-color: #f0f0f0;
font-size: 12px;
}
.error_messages h2 {
text-align: left;
font-weight: bold;
padding: 5px 10px;
font-size: 12px;
margin: 0;
background-color: #c00;
color: #fff;
}
.error_messages p {
margin: 8px 10px;
}
.error_messages ul {
margin: 15px 0;
}
input[type=checkbox] {
float: left;
margin-right: 8px;
}
| {'content_hash': '2876459e89d1bd0904e80e0f4fc2412f', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 105, 'avg_line_length': 16.21875, 'alnum_prop': 0.6647398843930635, 'repo_name': 'akkyrox/railscasts-episodes', 'id': '047f97108b18e569a5ec6cebde3fb629672a559b', 'size': '1557', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'episode-274/auth-after/app/assets/stylesheets/application.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1251'}, {'name': 'CSS', 'bytes': '683852'}, {'name': 'CoffeeScript', 'bytes': '79141'}, {'name': 'Cucumber', 'bytes': '2789'}, {'name': 'HTML', 'bytes': '1887247'}, {'name': 'JavaScript', 'bytes': '676122'}, {'name': 'Nginx', 'bytes': '1724'}, {'name': 'Python', 'bytes': '4319'}, {'name': 'Ruby', 'bytes': '8058123'}, {'name': 'SQLPL', 'bytes': '10470'}, {'name': 'Shell', 'bytes': '16239'}]} |
using System.Management.Automation.Host;
using Dbg = System.Management.Automation.Diagnostics;
// Stops compiler from warning about unknown warnings
#pragma warning disable 1634, 1691
namespace System.Management.Automation.Remoting
{
/// <summary>
/// The ServerRemoteHostRawUserInterface class.
/// </summary>
internal class ServerRemoteHostRawUserInterface : PSHostRawUserInterface
{
/// <summary>
/// Remote host user interface.
/// </summary>
private ServerRemoteHostUserInterface _remoteHostUserInterface;
/// <summary>
/// Server method executor.
/// </summary>
private ServerMethodExecutor _serverMethodExecutor;
/// <summary>
/// Host default data.
/// </summary>
private HostDefaultData HostDefaultData
{
get
{
return _remoteHostUserInterface.ServerRemoteHost.HostInfo.HostDefaultData;
}
}
/// <summary>
/// Constructor for ServerRemoteHostRawUserInterface.
/// </summary>
internal ServerRemoteHostRawUserInterface(ServerRemoteHostUserInterface remoteHostUserInterface)
{
Dbg.Assert(remoteHostUserInterface != null, "Expected remoteHostUserInterface != null");
_remoteHostUserInterface = remoteHostUserInterface;
Dbg.Assert(!remoteHostUserInterface.ServerRemoteHost.HostInfo.IsHostRawUINull, "Expected !remoteHostUserInterface.ServerRemoteHost.HostInfo.IsHostRawUINull");
_serverMethodExecutor = remoteHostUserInterface.ServerRemoteHost.ServerMethodExecutor;
}
/// <summary>
/// Foreground color.
/// </summary>
public override ConsoleColor ForegroundColor
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.ForegroundColor))
{
return (ConsoleColor)this.HostDefaultData.GetValue(HostDefaultDataId.ForegroundColor);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetForegroundColor);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.ForegroundColor, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetForegroundColor, new object[] { value });
}
}
/// <summary>
/// Background color.
/// </summary>
public override ConsoleColor BackgroundColor
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.BackgroundColor))
{
return (ConsoleColor)this.HostDefaultData.GetValue(HostDefaultDataId.BackgroundColor);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetBackgroundColor);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.BackgroundColor, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetBackgroundColor, new object[] { value });
}
}
/// <summary>
/// Cursor position.
/// </summary>
public override Coordinates CursorPosition
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.CursorPosition))
{
return (Coordinates)this.HostDefaultData.GetValue(HostDefaultDataId.CursorPosition);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetCursorPosition);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.CursorPosition, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetCursorPosition, new object[] { value });
}
}
/// <summary>
/// Window position.
/// </summary>
public override Coordinates WindowPosition
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowPosition))
{
return (Coordinates)this.HostDefaultData.GetValue(HostDefaultDataId.WindowPosition);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetWindowPosition);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.WindowPosition, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetWindowPosition, new object[] { value });
}
}
/// <summary>
/// Cursor size.
/// </summary>
public override int CursorSize
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.CursorSize))
{
return (int)this.HostDefaultData.GetValue(HostDefaultDataId.CursorSize);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetCursorSize);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.CursorSize, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetCursorSize, new object[] { value });
}
}
/// <summary>
/// Buffer size.
/// </summary>
public override Size BufferSize
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.BufferSize))
{
return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.BufferSize);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetBufferSize);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.BufferSize, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetBufferSize, new object[] { value });
}
}
/// <summary>
/// Window size.
/// </summary>
public override Size WindowSize
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowSize))
{
return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.WindowSize);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetWindowSize);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.WindowSize, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetWindowSize, new object[] { value });
}
}
/// <summary>
/// Window title.
/// </summary>
public override string WindowTitle
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.WindowTitle))
{
return (string)this.HostDefaultData.GetValue(HostDefaultDataId.WindowTitle);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetWindowTitle);
}
}
set
{
this.HostDefaultData.SetValue(HostDefaultDataId.WindowTitle, value);
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetWindowTitle, new object[] { value });
}
}
/// <summary>
/// Max window size.
/// </summary>
public override Size MaxWindowSize
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.MaxWindowSize))
{
return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.MaxWindowSize);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetMaxWindowSize);
}
}
}
/// <summary>
/// Max physical window size.
/// </summary>
public override Size MaxPhysicalWindowSize
{
get
{
if (this.HostDefaultData.HasValue(HostDefaultDataId.MaxPhysicalWindowSize))
{
return (Size)this.HostDefaultData.GetValue(HostDefaultDataId.MaxPhysicalWindowSize);
}
else
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetMaxPhysicalWindowSize);
}
}
}
/// <summary>
/// Key available.
/// </summary>
public override bool KeyAvailable
{
#pragma warning disable 56503
get
{
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetKeyAvailable);
}
#pragma warning restore 56503
}
/// <summary>
/// Read key.
/// </summary>
public override KeyInfo ReadKey(ReadKeyOptions options)
{
return _serverMethodExecutor.ExecuteMethod<KeyInfo>(RemoteHostMethodId.ReadKey, new object[] { options });
}
/// <summary>
/// Flush input buffer.
/// </summary>
public override void FlushInputBuffer()
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.FlushInputBuffer);
}
/// <summary>
/// Scroll buffer contents.
/// </summary>
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.ScrollBufferContents, new object[] { source, destination, clip, fill });
}
/// <summary>
/// Set buffer contents.
/// </summary>
public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetBufferContents1, new object[] { rectangle, fill });
}
/// <summary>
/// Set buffer contents.
/// </summary>
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
_serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.SetBufferContents2, new object[] { origin, contents });
}
/// <summary>
/// Get buffer contents.
/// </summary>
public override BufferCell[,] GetBufferContents(Rectangle rectangle)
{
// This method had an implementation earlier. However, owing
// to a potential security risk of a malicious server scrapping
// the screen contents of a client, this is now removed
throw RemoteHostExceptions.NewNotImplementedException(RemoteHostMethodId.GetBufferContents);
}
// same as the implementation in the base class; included here to make it easier
// to keep the other overload in sync: LengthInBufferCells(string, int)
public override int LengthInBufferCells(string source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return source.Length;
}
// more performant than the default implementation provided by PSHostRawUserInterface
public override int LengthInBufferCells(string source, int offset)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
Dbg.Assert(offset >= 0, "offset >= 0");
Dbg.Assert(string.IsNullOrEmpty(source) || (offset < source.Length), "offset < source.Length");
return source.Length - offset;
}
}
}
| {'content_hash': '3cdbeda8093b270dc58b432c74b1e16b', 'timestamp': '', 'source': 'github', 'line_count': 365, 'max_line_length': 170, 'avg_line_length': 34.726027397260275, 'alnum_prop': 0.5609467455621302, 'repo_name': 'KarolKaczmarek/PowerShell', 'id': 'a6cfc7b111ccaf09f84c526cff922180fda8299d', 'size': '12877', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5425'}, {'name': 'C#', 'bytes': '37154119'}, {'name': 'C++', 'bytes': '304638'}, {'name': 'CMake', 'bytes': '23659'}, {'name': 'PowerShell', 'bytes': '2521451'}, {'name': 'Python', 'bytes': '492'}, {'name': 'Shell', 'bytes': '3521'}, {'name': 'XSLT', 'bytes': '14407'}]} |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ },
/* 1 */
/***/ function(module, exports) {
console.log("I am alive.");
/***/ }
/******/ ]); | {'content_hash': '8bae97fbd8cd9accbaadff36744369a8', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 95, 'avg_line_length': 26.448275862068964, 'alnum_prop': 0.4973924380704042, 'repo_name': 'betoesquivel/client_server', 'id': '12ed7ef569349197b28665941c56f1efe1c2a031', 'size': '1534', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dist/bundle.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '173'}, {'name': 'JavaScript', 'bytes': '8536'}]} |
/*Quicksort.java*/
/*Java*/
/*https://github.com/jonstaff/JavaDataStructures/blob/master/src/com/jonstaff/java/sort/QuickSort.java*/
public class QuickSort {
public static void sort(int[] list, int first, int last) {
if (first >= last) return;
int pivot = partition(list, first, last);
sort(list, first, pivot);
sort(list, pivot + 1, last);
}
public static int partition(int[] list, int first, int last) {
int pivot = list[first];
while (first < last) {
while (list[first] < pivot) {
first++;
}
while (list[last] > pivot) {
last--;
}
swap(list, first, last);
}
return first;
}
public static void swap(int[] list, int x, int y) {
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
}
| {'content_hash': '958eb03ac30e2534282264def376696f', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 104, 'avg_line_length': 23.128205128205128, 'alnum_prop': 0.5144124168514412, 'repo_name': 'nplexity/coderacer-samples', 'id': 'd27acdb6b6511ba401310c08120fce98b6178fe4', 'size': '902', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'java/QuickSort.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '911'}, {'name': 'Java', 'bytes': '4583'}, {'name': 'JavaScript', 'bytes': '1227'}, {'name': 'Python', 'bytes': '559'}, {'name': 'Ruby', 'bytes': '2623'}]} |
NAME='transformation_template'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['tt']
| {'content_hash': '4bbcbfff852458f27c077ac5e11f5cc8', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 30, 'avg_line_length': 14.166666666666666, 'alnum_prop': 0.611764705882353, 'repo_name': 'jyotikamboj/container', 'id': '7a0c07dec6074c34e95ee8de14ea8411e6fe8408', 'size': '85', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'uw-plugins/transformation_template/uwsgiplugin.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '130'}, {'name': 'Assembly', 'bytes': '1050'}, {'name': 'C', 'bytes': '6984025'}, {'name': 'C#', 'bytes': '5011'}, {'name': 'C++', 'bytes': '76346'}, {'name': 'CSS', 'bytes': '332655'}, {'name': 'Clojure', 'bytes': '4018'}, {'name': 'CoffeeScript', 'bytes': '260'}, {'name': 'Erlang', 'bytes': '693'}, {'name': 'Go', 'bytes': '7990'}, {'name': 'Java', 'bytes': '854529'}, {'name': 'JavaScript', 'bytes': '1142584'}, {'name': 'Lua', 'bytes': '4142'}, {'name': 'Makefile', 'bytes': '6026'}, {'name': 'Objective-C', 'bytes': '2621'}, {'name': 'PHP', 'bytes': '6012'}, {'name': 'Perl', 'bytes': '33126'}, {'name': 'Perl6', 'bytes': '2994'}, {'name': 'Python', 'bytes': '10715733'}, {'name': 'Ruby', 'bytes': '654838'}, {'name': 'Scala', 'bytes': '2829497'}, {'name': 'Shell', 'bytes': '28228'}, {'name': 'TeX', 'bytes': '7441'}, {'name': 'VimL', 'bytes': '37498'}, {'name': 'XSLT', 'bytes': '4275'}]} |
class MockExpectationError < StandardError; end
module MiniTest
class Mock
def initialize
@expected_calls = {}
@actual_calls = Hash.new {|h,k| h[k] = [] }
end
def expect(name, retval, args=[])
n, r, a = name, retval, args # for the closure below
@expected_calls[name] = { :retval => retval, :args => args }
self.class.__send__ :remove_method, name if respond_to? name
self.class.__send__(:define_method, name) { |*x|
raise ArgumentError unless @expected_calls[n][:args].size == x.size
@actual_calls[n] << { :retval => r, :args => x }
retval
}
self
end
def verify
@expected_calls.each_key do |name|
expected = @expected_calls[name]
msg = "expected #{name}, #{expected.inspect}"
raise MockExpectationError, msg unless
@actual_calls.has_key? name and @actual_calls[name].include?(expected)
end
true
end
end
end
| {'content_hash': '5225e45404a48f7714ab6a98e4dc4d8f', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 80, 'avg_line_length': 30.09375, 'alnum_prop': 0.5877466251298027, 'repo_name': 'rifraf/IronRubyEmbeddedApps', 'id': 'ed44164448bbb885aed6dc2e6d6ebd7794dd1e78', 'size': '1229', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'IREmbeddedLibraries/Files/1.9.1/minitest/mock.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '17358'}, {'name': 'Ruby', 'bytes': '4774669'}]} |
package de.hsbremen.chat.core;
import java.awt.*;
import java.io.Serializable;
/**
* Created by cschaf on 23.04.2015.
*/
public class ClientJListItem implements Serializable {
private String ip;
private int port;
private String name;
private Image pic;
public ClientJListItem(String ip, int port, String name, Image pic) {
this.ip = ip;
this.port = port;
this.name = name;
this.pic = pic;
}
@Override
public String toString() {
return this.name + " (" + this.port + ")";
}
public String getIp() {
return ip;
}
public int getPort() {
return port;
}
public Image getPic() {
return pic;
}
public String getName() {
return this.name;
}
}
| {'content_hash': '7a5931466d63de70ef2d9c33dfb2a900', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 73, 'avg_line_length': 18.69047619047619, 'alnum_prop': 0.575796178343949, 'repo_name': 'cschaf/java-multithreaded-chat', 'id': 'e6f0ddcc24e34dda5a2be8f1e2ac55e0dd51b92d', 'size': '785', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/de/hsbremen/chat/core/ClientJListItem.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '66762'}]} |
/**
*
*/
package com.thinkbiganalytics.metadata.api.catalog;
/*-
* #%L
* kylo-metadata-api
* %%
* Copyright (C) 2017 - 2018 ThinkBig Analytics, a Teradata Company
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.thinkbiganalytics.metadata.api.MetadataException;
/**
*
*/
public class DataSetNotFoundException extends MetadataException {
private static final long serialVersionUID = 1L;
private final DataSet.ID id;
public DataSetNotFoundException(DataSet.ID id) {
super("No data set exists with ID: " + id);
this.id = id;
}
public DataSetNotFoundException(String message, DataSet.ID id) {
super(message);
this.id = id;
}
/**
* @return the id
*/
public DataSet.ID getId() {
return id;
}
}
| {'content_hash': '2cde6bdd8bd778b8a52b5704030d9c0c', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 75, 'avg_line_length': 25.18867924528302, 'alnum_prop': 0.6704119850187266, 'repo_name': 'Teradata/kylo', 'id': '2b972cdc4fa3f9dae174335479b904d0f4d431a2', 'size': '1335', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'metadata/metadata-api/src/main/java/com/thinkbiganalytics/metadata/api/catalog/DataSetNotFoundException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '206880'}, {'name': 'FreeMarker', 'bytes': '785'}, {'name': 'HTML', 'bytes': '1076578'}, {'name': 'Java', 'bytes': '13931541'}, {'name': 'JavaScript', 'bytes': '1956411'}, {'name': 'PLpgSQL', 'bytes': '46248'}, {'name': 'SQLPL', 'bytes': '8898'}, {'name': 'Scala', 'bytes': '72686'}, {'name': 'Shell', 'bytes': '124425'}, {'name': 'TypeScript', 'bytes': '3763974'}]} |
dojo.provide("dojox.gfx.svg");
dojo.require("dojox.gfx._base");
dojo.require("dojox.gfx.shape");
dojo.require("dojox.gfx.path");
(function(){
var d = dojo, g = dojox.gfx, gs = g.shape, svg = g.svg;
svg.useSvgWeb = (typeof(window.svgweb)!=='undefined');
var _createElementNS = function(ns, nodeType){
// summary:
// Internal helper to deal with creating elements that
// are namespaced. Mainly to get SVG markup output
// working on IE.
if(dojo.doc.createElementNS){
return dojo.doc.createElementNS(ns,nodeType);
}else{
return dojo.doc.createElement(nodeType);
}
}
var _createTextNode = function(text) {
if (svg.useSvgWeb) {
return dojo.doc.createTextNode(text, true);
} else {
return dojo.doc.createTextNode(text);
}
}
var _createFragment = function() {
if (svg.useSvgWeb) {
return dojo.doc.createDocumentFragment(true);
} else {
return dojo.doc.createDocumentFragment();
}
}
svg.xmlns = {
xlink: "http://www.w3.org/1999/xlink",
svg: "http://www.w3.org/2000/svg"
};
svg.getRef = function(name){
// summary: returns a DOM Node specified by the name argument or null
// name: String: an SVG external reference
if(!name || name == "none") return null;
if(name.match(/^url\(#.+\)$/)){
return d.byId(name.slice(5, -1)); // Node
}
// alternative representation of a reference
if(name.match(/^#dojoUnique\d+$/)){
// we assume here that a reference was generated by dojox.gfx
return d.byId(name.slice(1)); // Node
}
return null; // Node
};
svg.dasharray = {
solid: "none",
shortdash: [4, 1],
shortdot: [1, 1],
shortdashdot: [4, 1, 1, 1],
shortdashdotdot: [4, 1, 1, 1, 1, 1],
dot: [1, 3],
dash: [4, 3],
longdash: [8, 3],
dashdot: [4, 3, 1, 3],
longdashdot: [8, 3, 1, 3],
longdashdotdot: [8, 3, 1, 3, 1, 3]
};
d.extend(g.Shape, {
// summary: SVG-specific implementation of dojox.gfx.Shape methods
setFill: function(fill){
// summary: sets a fill object (SVG)
// fill: Object: a fill object
// (see dojox.gfx.defaultLinearGradient,
// dojox.gfx.defaultRadialGradient,
// dojox.gfx.defaultPattern,
// or dojo.Color)
if(!fill){
// don't fill
this.fillStyle = null;
this.rawNode.setAttribute("fill", "none");
this.rawNode.setAttribute("fill-opacity", 0);
return this;
}
var f;
// FIXME: slightly magical. We're using the outer scope's "f", but setting it later
var setter = function(x){
// we assume that we're executing in the scope of the node to mutate
this.setAttribute(x, f[x].toFixed(8));
};
if(typeof(fill) == "object" && "type" in fill){
// gradient
switch(fill.type){
case "linear":
f = g.makeParameters(g.defaultLinearGradient, fill);
var gradient = this._setFillObject(f, "linearGradient");
d.forEach(["x1", "y1", "x2", "y2"], setter, gradient);
break;
case "radial":
f = g.makeParameters(g.defaultRadialGradient, fill);
var gradient = this._setFillObject(f, "radialGradient");
d.forEach(["cx", "cy", "r"], setter, gradient);
break;
case "pattern":
f = g.makeParameters(g.defaultPattern, fill);
var pattern = this._setFillObject(f, "pattern");
d.forEach(["x", "y", "width", "height"], setter, pattern);
break;
}
this.fillStyle = f;
return this;
}
// color object
var f = g.normalizeColor(fill);
this.fillStyle = f;
this.rawNode.setAttribute("fill", f.toCss());
this.rawNode.setAttribute("fill-opacity", f.a);
this.rawNode.setAttribute("fill-rule", "evenodd");
return this; // self
},
setStroke: function(stroke){
// summary:
// sets a stroke object (SVG)
// stroke: Object
// a stroke object (see dojox.gfx.defaultStroke)
var rn = this.rawNode;
if(!stroke){
// don't stroke
this.strokeStyle = null;
rn.setAttribute("stroke", "none");
rn.setAttribute("stroke-opacity", 0);
return this;
}
// normalize the stroke
if(typeof stroke == "string" || d.isArray(stroke) || stroke instanceof d.Color){
stroke = { color: stroke };
}
var s = this.strokeStyle = g.makeParameters(g.defaultStroke, stroke);
s.color = g.normalizeColor(s.color);
// generate attributes
if(s){
rn.setAttribute("stroke", s.color.toCss());
rn.setAttribute("stroke-opacity", s.color.a);
rn.setAttribute("stroke-width", s.width);
rn.setAttribute("stroke-linecap", s.cap);
if(typeof s.join == "number"){
rn.setAttribute("stroke-linejoin", "miter");
rn.setAttribute("stroke-miterlimit", s.join);
}else{
rn.setAttribute("stroke-linejoin", s.join);
}
var da = s.style.toLowerCase();
if(da in svg.dasharray){
da = svg.dasharray[da];
}
if(da instanceof Array){
da = d._toArray(da);
for(var i = 0; i < da.length; ++i){
da[i] *= s.width;
}
if(s.cap != "butt"){
for(var i = 0; i < da.length; i += 2){
da[i] -= s.width;
if(da[i] < 1){ da[i] = 1; }
}
for(var i = 1; i < da.length; i += 2){
da[i] += s.width;
}
}
da = da.join(",");
}
rn.setAttribute("stroke-dasharray", da);
rn.setAttribute("dojoGfxStrokeStyle", s.style);
}
return this; // self
},
_getParentSurface: function(){
var surface = this.parent;
for(; surface && !(surface instanceof g.Surface); surface = surface.parent);
return surface;
},
_setFillObject: function(f, nodeType){
var svgns = svg.xmlns.svg;
this.fillStyle = f;
var surface = this._getParentSurface(),
defs = surface.defNode,
fill = this.rawNode.getAttribute("fill"),
ref = svg.getRef(fill);
if(ref){
fill = ref;
if(fill.tagName.toLowerCase() != nodeType.toLowerCase()){
var id = fill.id;
fill.parentNode.removeChild(fill);
fill = _createElementNS(svgns, nodeType);
fill.setAttribute("id", id);
defs.appendChild(fill);
}else{
while(fill.childNodes.length){
fill.removeChild(fill.lastChild);
}
}
}else{
fill = _createElementNS(svgns, nodeType);
fill.setAttribute("id", g._base._getUniqueId());
defs.appendChild(fill);
}
if(nodeType == "pattern"){
fill.setAttribute("patternUnits", "userSpaceOnUse");
var img = _createElementNS(svgns, "image");
img.setAttribute("x", 0);
img.setAttribute("y", 0);
img.setAttribute("width", f.width .toFixed(8));
img.setAttribute("height", f.height.toFixed(8));
img.setAttributeNS(svg.xmlns.xlink, "xlink:href", f.src);
fill.appendChild(img);
}else{
fill.setAttribute("gradientUnits", "userSpaceOnUse");
for(var i = 0; i < f.colors.length; ++i){
var c = f.colors[i], t = _createElementNS(svgns, "stop"),
cc = c.color = g.normalizeColor(c.color);
t.setAttribute("offset", c.offset.toFixed(8));
t.setAttribute("stop-color", cc.toCss());
t.setAttribute("stop-opacity", cc.a);
fill.appendChild(t);
}
}
this.rawNode.setAttribute("fill", "url(#" + fill.getAttribute("id") +")");
this.rawNode.removeAttribute("fill-opacity");
this.rawNode.setAttribute("fill-rule", "evenodd");
return fill;
},
_applyTransform: function() {
var matrix = this.matrix;
if(matrix){
var tm = this.matrix;
this.rawNode.setAttribute("transform", "matrix(" +
tm.xx.toFixed(8) + "," + tm.yx.toFixed(8) + "," +
tm.xy.toFixed(8) + "," + tm.yy.toFixed(8) + "," +
tm.dx.toFixed(8) + "," + tm.dy.toFixed(8) + ")");
}else{
this.rawNode.removeAttribute("transform");
}
return this;
},
setRawNode: function(rawNode){
// summary:
// assigns and clears the underlying node that will represent this
// shape. Once set, transforms, gradients, etc, can be applied.
// (no fill & stroke by default)
var r = this.rawNode = rawNode;
if(this.shape.type!="image"){
r.setAttribute("fill", "none");
}
r.setAttribute("fill-opacity", 0);
r.setAttribute("stroke", "none");
r.setAttribute("stroke-opacity", 0);
r.setAttribute("stroke-width", 1);
r.setAttribute("stroke-linecap", "butt");
r.setAttribute("stroke-linejoin", "miter");
r.setAttribute("stroke-miterlimit", 4);
},
setShape: function(newShape){
// summary: sets a shape object (SVG)
// newShape: Object: a shape object
// (see dojox.gfx.defaultPath,
// dojox.gfx.defaultPolyline,
// dojox.gfx.defaultRect,
// dojox.gfx.defaultEllipse,
// dojox.gfx.defaultCircle,
// dojox.gfx.defaultLine,
// or dojox.gfx.defaultImage)
this.shape = g.makeParameters(this.shape, newShape);
for(var i in this.shape){
if(i != "type"){ this.rawNode.setAttribute(i, this.shape[i]); }
}
this.bbox = null;
return this; // self
},
// move family
_moveToFront: function(){
// summary: moves a shape to front of its parent's list of shapes (SVG)
this.rawNode.parentNode.appendChild(this.rawNode);
return this; // self
},
_moveToBack: function(){
// summary: moves a shape to back of its parent's list of shapes (SVG)
this.rawNode.parentNode.insertBefore(this.rawNode, this.rawNode.parentNode.firstChild);
return this; // self
}
});
dojo.declare("dojox.gfx.Group", g.Shape, {
// summary: a group shape (SVG), which can be used
// to logically group shapes (e.g, to propagate matricies)
constructor: function(){
svg.Container._init.call(this);
},
setRawNode: function(rawNode){
// summary: sets a raw SVG node to be used by this shape
// rawNode: Node: an SVG node
this.rawNode = rawNode;
}
});
g.Group.nodeType = "g";
dojo.declare("dojox.gfx.Rect", gs.Rect, {
// summary: a rectangle shape (SVG)
setShape: function(newShape){
// summary: sets a rectangle shape object (SVG)
// newShape: Object: a rectangle shape object
this.shape = g.makeParameters(this.shape, newShape);
this.bbox = null;
for(var i in this.shape){
if(i != "type" && i != "r"){ this.rawNode.setAttribute(i, this.shape[i]); }
}
if(this.shape.r){
this.rawNode.setAttribute("ry", this.shape.r);
this.rawNode.setAttribute("rx", this.shape.r);
}
return this; // self
}
});
g.Rect.nodeType = "rect";
g.Ellipse = gs.Ellipse;
g.Ellipse.nodeType = "ellipse";
g.Circle = gs.Circle;
g.Circle.nodeType = "circle";
g.Line = gs.Line;
g.Line.nodeType = "line";
dojo.declare("dojox.gfx.Polyline", gs.Polyline, {
// summary: a polyline/polygon shape (SVG)
setShape: function(points, closed){
// summary: sets a polyline/polygon shape object (SVG)
// points: Object: a polyline/polygon shape object
if(points && points instanceof Array){
// branch
// points: Array: an array of points
this.shape = g.makeParameters(this.shape, { points: points });
if(closed && this.shape.points.length){
this.shape.points.push(this.shape.points[0]);
}
}else{
this.shape = g.makeParameters(this.shape, points);
}
this.bbox = null;
this._normalizePoints();
var attr = [], p = this.shape.points;
for(var i = 0; i < p.length; ++i){
attr.push(p[i].x.toFixed(8), p[i].y.toFixed(8));
}
this.rawNode.setAttribute("points", attr.join(" "));
return this; // self
}
});
g.Polyline.nodeType = "polyline";
dojo.declare("dojox.gfx.Image", gs.Image, {
// summary: an image (SVG)
setShape: function(newShape){
// summary: sets an image shape object (SVG)
// newShape: Object: an image shape object
this.shape = g.makeParameters(this.shape, newShape);
this.bbox = null;
var rawNode = this.rawNode;
for(var i in this.shape){
if(i != "type" && i != "src"){ rawNode.setAttribute(i, this.shape[i]); }
}
rawNode.setAttribute("preserveAspectRatio", "none");
rawNode.setAttributeNS(svg.xmlns.xlink, "xlink:href", this.shape.src);
return this; // self
}
});
g.Image.nodeType = "image";
dojo.declare("dojox.gfx.Text", gs.Text, {
// summary: an anchored text (SVG)
setShape: function(newShape){
// summary: sets a text shape object (SVG)
// newShape: Object: a text shape object
this.shape = g.makeParameters(this.shape, newShape);
this.bbox = null;
var r = this.rawNode, s = this.shape;
r.setAttribute("x", s.x);
r.setAttribute("y", s.y);
r.setAttribute("text-anchor", s.align);
r.setAttribute("text-decoration", s.decoration);
r.setAttribute("rotate", s.rotated ? 90 : 0);
r.setAttribute("kerning", s.kerning ? "auto" : 0);
r.setAttribute("text-rendering", "optimizeLegibility");
// update the text content
if(r.firstChild){
r.firstChild.nodeValue = s.text;
}else{
r.appendChild(_createTextNode(s.text));
}
return this; // self
},
getTextWidth: function(){
// summary: get the text width in pixels
var rawNode = this.rawNode,
oldParent = rawNode.parentNode,
_measurementNode = rawNode.cloneNode(true);
_measurementNode.style.visibility = "hidden";
// solution to the "orphan issue" in FF
var _width = 0, _text = _measurementNode.firstChild.nodeValue;
oldParent.appendChild(_measurementNode);
// solution to the "orphan issue" in Opera
// (nodeValue == "" hangs firefox)
if(_text!=""){
while(!_width){
//Yang: work around svgweb bug 417 -- http://code.google.com/p/svgweb/issues/detail?id=417
if (_measurementNode.getBBox)
_width = parseInt(_measurementNode.getBBox().width);
else
_width = 68;
}
}
oldParent.removeChild(_measurementNode);
return _width;
}
});
g.Text.nodeType = "text";
dojo.declare("dojox.gfx.Path", g.path.Path, {
// summary: a path shape (SVG)
_updateWithSegment: function(segment){
// summary: updates the bounding box of path with new segment
// segment: Object: a segment
g.Path.superclass._updateWithSegment.apply(this, arguments);
if(typeof(this.shape.path) == "string"){
this.rawNode.setAttribute("d", this.shape.path);
}
},
setShape: function(newShape){
// summary: forms a path using a shape (SVG)
// newShape: Object: an SVG path string or a path object (see dojox.gfx.defaultPath)
g.Path.superclass.setShape.apply(this, arguments);
this.rawNode.setAttribute("d", this.shape.path);
return this; // self
}
});
g.Path.nodeType = "path";
dojo.declare("dojox.gfx.TextPath", g.path.TextPath, {
// summary: a textpath shape (SVG)
_updateWithSegment: function(segment){
// summary: updates the bounding box of path with new segment
// segment: Object: a segment
g.Path.superclass._updateWithSegment.apply(this, arguments);
this._setTextPath();
},
setShape: function(newShape){
// summary: forms a path using a shape (SVG)
// newShape: Object: an SVG path string or a path object (see dojox.gfx.defaultPath)
g.Path.superclass.setShape.apply(this, arguments);
this._setTextPath();
return this; // self
},
_setTextPath: function(){
if(typeof this.shape.path != "string"){ return; }
var r = this.rawNode;
if(!r.firstChild){
var tp = _createElementNS(svg.xmlns.svg, "textPath"),
tx = _createTextNode("");
tp.appendChild(tx);
r.appendChild(tp);
}
var ref = r.firstChild.getAttributeNS(svg.xmlns.xlink, "href"),
path = ref && svg.getRef(ref);
if(!path){
var surface = this._getParentSurface();
if(surface){
var defs = surface.defNode;
path = _createElementNS(svg.xmlns.svg, "path");
var id = g._base._getUniqueId();
path.setAttribute("id", id);
defs.appendChild(path);
r.firstChild.setAttributeNS(svg.xmlns.xlink, "xlink:href", "#" + id);
}
}
if(path){
path.setAttribute("d", this.shape.path);
}
},
_setText: function(){
var r = this.rawNode;
if(!r.firstChild){
var tp = _createElementNS(svg.xmlns.svg, "textPath"),
tx = _createTextNode("");
tp.appendChild(tx);
r.appendChild(tp);
}
r = r.firstChild;
var t = this.text;
r.setAttribute("alignment-baseline", "middle");
switch(t.align){
case "middle":
r.setAttribute("text-anchor", "middle");
r.setAttribute("startOffset", "50%");
break;
case "end":
r.setAttribute("text-anchor", "end");
r.setAttribute("startOffset", "100%");
break;
default:
r.setAttribute("text-anchor", "start");
r.setAttribute("startOffset", "0%");
break;
}
//r.parentNode.setAttribute("alignment-baseline", "central");
//r.setAttribute("dominant-baseline", "central");
r.setAttribute("baseline-shift", "0.5ex");
r.setAttribute("text-decoration", t.decoration);
r.setAttribute("rotate", t.rotated ? 90 : 0);
r.setAttribute("kerning", t.kerning ? "auto" : 0);
r.firstChild.data = t.text;
}
});
g.TextPath.nodeType = "text";
dojo.declare("dojox.gfx.Surface", gs.Surface, {
// summary: a surface object to be used for drawings (SVG)
constructor: function(){
svg.Container._init.call(this);
},
destroy: function(){
this.defNode = null; // release the external reference
this.inherited(arguments);
},
setDimensions: function(width, height){
// summary: sets the width and height of the rawNode
// width: String: width of surface, e.g., "100px"
// height: String: height of surface, e.g., "100px"
if(!this.rawNode){ return this; }
this.rawNode.setAttribute("width", width);
this.rawNode.setAttribute("height", height);
return this; // self
},
getDimensions: function(){
// summary: returns an object with properties "width" and "height"
var t = this.rawNode ? {
width: g.normalizedLength(this.rawNode.getAttribute("width")),
height: g.normalizedLength(this.rawNode.getAttribute("height"))} : null;
return t; // Object
}
});
g.createSurface = function(parentNode, width, height){
// summary: creates a surface (SVG)
// parentNode: Node: a parent node
// width: String: width of surface, e.g., "100px"
// height: String: height of surface, e.g., "100px"
var s = new g.Surface();
s.rawNode = _createElementNS(svg.xmlns.svg, "svg");
s.rawNode.setAttribute("overflow", "hidden");
if(width){
s.rawNode.setAttribute("width", width);
}
if(height){
s.rawNode.setAttribute("height", height);
}
var defNode = _createElementNS(svg.xmlns.svg, "defs");
s.rawNode.appendChild(defNode);
s.defNode = defNode;
s._parent = d.byId(parentNode);
s._parent.appendChild(s.rawNode);
return s; // dojox.gfx.Surface
};
// Extenders
svg.Font = {
_setFont: function(){
// summary: sets a font object (SVG)
var f = this.fontStyle;
// next line doesn't work in Firefox 2 or Opera 9
//this.rawNode.setAttribute("font", dojox.gfx.makeFontString(this.fontStyle));
this.rawNode.setAttribute("font-style", f.style);
this.rawNode.setAttribute("font-variant", f.variant);
this.rawNode.setAttribute("font-weight", f.weight);
this.rawNode.setAttribute("font-size", f.size);
this.rawNode.setAttribute("font-family", f.family);
}
};
svg.Container = {
_init: function(){
gs.Container._init.call(this);
},
openBatch: function() {
// summary: starts a new batch, subsequent new child shapes will be held in
// the batch instead of appending to the container directly
this.fragment = _createFragment();
},
closeBatch: function() {
// summary: submits the current batch, append all pending child shapes to DOM
if (this.fragment) {
this.rawNode.appendChild(this.fragment);
delete this.fragment;
}
},
add: function(shape){
// summary: adds a shape to a group/surface
// shape: dojox.gfx.Shape: an VML shape object
if(this != shape.getParent()){
if (this.fragment) {
this.fragment.appendChild(shape.rawNode);
} else {
this.rawNode.appendChild(shape.rawNode);
}
//dojox.gfx.Group.superclass.add.apply(this, arguments);
//this.inherited(arguments);
gs.Container.add.apply(this, arguments);
}
return this; // self
},
remove: function(shape, silently){
// summary: remove a shape from a group/surface
// shape: dojox.gfx.Shape: an VML shape object
// silently: Boolean?: if true, regenerate a picture
if(this == shape.getParent()){
if(this.rawNode == shape.rawNode.parentNode){
this.rawNode.removeChild(shape.rawNode);
}
if(this.fragment && this.fragment == shape.rawNode.parentNode){
this.fragment.removeChild(shape.rawNode);
}
//dojox.gfx.Group.superclass.remove.apply(this, arguments);
//this.inherited(arguments);
gs.Container.remove.apply(this, arguments);
}
return this; // self
},
clear: function(){
// summary: removes all shapes from a group/surface
var r = this.rawNode;
while(r.lastChild){
r.removeChild(r.lastChild);
}
var defNode = this.defNode;
if(defNode){
while(defNode.lastChild){
defNode.removeChild(defNode.lastChild);
}
r.appendChild(defNode);
}
//return this.inherited(arguments); // self
return gs.Container.clear.apply(this, arguments);
},
_moveChildToFront: gs.Container._moveChildToFront,
_moveChildToBack: gs.Container._moveChildToBack
};
d.mixin(gs.Creator, {
// summary: SVG shape creators
createObject: function(shapeType, rawShape){
// summary: creates an instance of the passed shapeType class
// shapeType: Function: a class constructor to create an instance of
// rawShape: Object: properties to be passed in to the classes "setShape" method
if(!this.rawNode){ return null; }
var shape = new shapeType(),
node = _createElementNS(svg.xmlns.svg, shapeType.nodeType);
shape.setRawNode(node);
shape.setShape(rawShape);
// rawNode.appendChild() will be done inside this.add(shape) below
this.add(shape);
return shape; // dojox.gfx.Shape
}
});
d.extend(g.Text, svg.Font);
d.extend(g.TextPath, svg.Font);
d.extend(g.Group, svg.Container);
d.extend(g.Group, gs.Creator);
d.extend(g.Surface, svg.Container);
d.extend(g.Surface, gs.Creator);
// some specific override for svgweb + flash
if (svg.useSvgWeb) {
// override createSurface()
g.createSurface = function(parentNode, width, height) {
var s = new g.Surface();
// ensure width / height
if (!width || !height) {
var pos = d.position(parentNode);
width = width || pos.w;
height = height || pos.h;
}
// ensure id
parentNode = d.byId(parentNode);
var id = parentNode.id ? parentNode.id+'_svgweb' : g._base._getUniqueId();
// create dynamic svg root
var mockSvg = _createElementNS(svg.xmlns.svg, 'svg');
mockSvg.id = id;
mockSvg.setAttribute('width', width);
mockSvg.setAttribute('height', height);
svgweb.appendChild(mockSvg, parentNode);
// notice: any call to the raw node before flash init will fail.
mockSvg.addEventListener('SVGLoad', function() {
// become loaded
s.rawNode = this;
s.isLoaded = true;
// init defs
var defNode = _createElementNS(svg.xmlns.svg, "defs");
s.rawNode.appendChild(defNode);
s.defNode = defNode;
// notify application
if (s.onLoad)
s.onLoad(s);
}, false);
// flash not loaded yet
s.isLoaded = false;
return s;
}
// override Surface.destroy()
dojo.extend(dojox.gfx.shape.Surface, {
destroy: function() {
var mockSvg = this.rawNode;
svgweb.removeChild(mockSvg, mockSvg.parentNode);
}
});
// override connect() & disconnect() for Shape & Surface event processing
gs._eventsProcessing.connect = function(name, object, method) {
// connect events using the mock addEventListener() provided by svgweb
if (name.substring(0, 2)==='on') { name = name.substring(2); }
if (arguments.length == 2) {
method = object;
} else {
method = d.hitch(object, method);
}
this.getEventSource().addEventListener(name, method, false);
return [this, name, method];
}
gs._eventsProcessing.disconnect = function(token) {
// disconnect events using the mock removeEventListener() provided by svgweb
this.getEventSource().removeEventListener(token[1], token[2], false);
delete token[0];
}
dojo.extend(dojox.gfx.Shape, dojox.gfx.shape._eventsProcessing);
dojo.extend(dojox.gfx.shape.Surface, dojox.gfx.shape._eventsProcessing);
}
})();
| {'content_hash': '199ffc8b2d66809e61051f25a41ddab6', 'timestamp': '', 'source': 'github', 'line_count': 783, 'max_line_length': 90, 'avg_line_length': 30.877394636015325, 'alnum_prop': 0.6427596475989577, 'repo_name': 'Bad-Hack/Zend-Socket', 'id': '367d613b734b8dcb5904b108322f3a7a2a116b7a', 'size': '24177', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'public/js/dojo/dojox/gfx/svg.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '19954'}, {'name': 'Java', 'bytes': '123492'}, {'name': 'JavaScript', 'bytes': '7913018'}, {'name': 'PHP', 'bytes': '15967534'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Ruby', 'bytes': '911'}, {'name': 'Shell', 'bytes': '16299'}]} |
class Breakfast {
public static void main(String[] args){
Person hungryHungryBob = new Person();
System.out.println(hungryHungryBob.wakeUp());
Bacon bacon = new Bacon();
System.out.println(bacon.unwrap());
Pan pan = new Pan();
if (bacon.oink()){
// This bacon isn't bacon yet!
System.out.println(-1);
} else {
while (bacon.isTasty()){
System.out.println(hungryHungryBob.fry(bacon, pan));
}
System.out.println(hungryHungryBob.eat(bacon));
}
}
}
class Bacon {
int tasty;
public int unwrap(){
tasty = 0;
return tasty;
}
public boolean isTasty(){
return tasty > 10;
}
public int sizzle(){
tasty = tasty + 1;
return tasty;
}
public boolean oink(){
return tasty < 0;
}
}
class Pan{
public int fry(Bacon bacon){
return bacon.sizzle();
}
}
class Person{
int hunger;
public int wakeUp(){
hunger = 10;
return hunger;
}
public int fry(Bacon bacon, Pan pan){
return pan.fry(bacon);
}
public int eat(Bacon bacon){
hunger = hunger - 10;
return hunger;
}
public int hungerLevel(){
return hunger;
}
} | {'content_hash': '4a70050aac9ed46da76a3eb997d09ced', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 68, 'avg_line_length': 20.91176470588235, 'alnum_prop': 0.48874824191279886, 'repo_name': 'aj-michael/minijavac', 'id': '69749615e903fc9aefa7039b28035f5408148783', 'size': '1422', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/test/resources/typechecker/java/testcase96_04.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '244692'}, {'name': 'Lex', 'bytes': '7785'}]} |
#include "config.h"
#include "core/rendering/svg/SVGRenderSupport.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/SubtreeLayoutScope.h"
#include "core/rendering/svg/RenderSVGInlineText.h"
#include "core/rendering/svg/RenderSVGResourceClipper.h"
#include "core/rendering/svg/RenderSVGResourceFilter.h"
#include "core/rendering/svg/RenderSVGResourceMasker.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/rendering/svg/RenderSVGShape.h"
#include "core/rendering/svg/RenderSVGText.h"
#include "core/rendering/svg/RenderSVGViewportContainer.h"
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGElement.h"
#include "platform/geometry/TransformState.h"
#include "platform/graphics/Path.h"
namespace blink {
LayoutRect SVGRenderSupport::clippedOverflowRectForPaintInvalidation(const RenderObject* object, const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState)
{
// Return early for any cases where we don't actually paint
if (object->style()->visibility() != VISIBLE && !object->enclosingLayer()->hasVisibleContent())
return LayoutRect();
// Pass our local paint rect to computeRectForPaintInvalidation() which will
// map to parent coords and recurse up the parent chain.
FloatRect paintInvalidationRect = object->paintInvalidationRectInLocalCoordinates();
paintInvalidationRect.inflate(object->style()->outlineWidth());
object->computeFloatRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationRect, paintInvalidationState);
return enclosingLayoutRect(paintInvalidationRect);
}
void SVGRenderSupport::computeFloatRectForPaintInvalidation(const RenderObject* object, const RenderLayerModelObject* paintInvalidationContainer, FloatRect& paintInvalidationRect, const PaintInvalidationState* paintInvalidationState)
{
// Translate to coords in our parent renderer, and then call computeFloatRectForPaintInvalidation() on our parent.
paintInvalidationRect = object->localToParentTransform().mapRect(paintInvalidationRect);
object->parent()->computeFloatRectForPaintInvalidation(paintInvalidationContainer, paintInvalidationRect, paintInvalidationState);
}
void SVGRenderSupport::mapLocalToContainer(const RenderObject* object, const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, bool* wasFixed, const PaintInvalidationState* paintInvalidationState)
{
transformState.applyTransform(object->localToParentTransform());
RenderObject* parent = object->parent();
// At the SVG/HTML boundary (aka RenderSVGRoot), we apply the localToBorderBoxTransform
// to map an element from SVG viewport coordinates to CSS box coordinates.
// RenderSVGRoot's mapLocalToContainer method expects CSS box coordinates.
if (parent->isSVGRoot())
transformState.applyTransform(toRenderSVGRoot(parent)->localToBorderBoxTransform());
MapCoordinatesFlags mode = UseTransforms;
parent->mapLocalToContainer(paintInvalidationContainer, transformState, mode, wasFixed, paintInvalidationState);
}
const RenderObject* SVGRenderSupport::pushMappingToContainer(const RenderObject* object, const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap)
{
ASSERT_UNUSED(ancestorToStopAt, ancestorToStopAt != object);
RenderObject* parent = object->parent();
// At the SVG/HTML boundary (aka RenderSVGRoot), we apply the localToBorderBoxTransform
// to map an element from SVG viewport coordinates to CSS box coordinates.
// RenderSVGRoot's mapLocalToContainer method expects CSS box coordinates.
if (parent->isSVGRoot()) {
TransformationMatrix matrix(object->localToParentTransform());
matrix.multiply(toRenderSVGRoot(parent)->localToBorderBoxTransform());
geometryMap.push(object, matrix);
} else
geometryMap.push(object, object->localToParentTransform());
return parent;
}
// Update a bounding box taking into account the validity of the other bounding box.
inline void SVGRenderSupport::updateObjectBoundingBox(FloatRect& objectBoundingBox, bool& objectBoundingBoxValid, RenderObject* other, FloatRect otherBoundingBox)
{
bool otherValid = other->isSVGContainer() ? toRenderSVGContainer(other)->isObjectBoundingBoxValid() : true;
if (!otherValid)
return;
if (!objectBoundingBoxValid) {
objectBoundingBox = otherBoundingBox;
objectBoundingBoxValid = true;
return;
}
objectBoundingBox.uniteEvenIfEmpty(otherBoundingBox);
}
void SVGRenderSupport::computeContainerBoundingBoxes(const RenderObject* container, FloatRect& objectBoundingBox, bool& objectBoundingBoxValid, FloatRect& strokeBoundingBox, FloatRect& paintInvalidationBoundingBox)
{
objectBoundingBox = FloatRect();
objectBoundingBoxValid = false;
strokeBoundingBox = FloatRect();
// When computing the strokeBoundingBox, we use the paintInvalidationRects of the container's children so that the container's stroke includes
// the resources applied to the children (such as clips and filters). This allows filters applied to containers to correctly bound
// the children, and also improves inlining of SVG content, as the stroke bound is used in that situation also.
for (RenderObject* current = container->slowFirstChild(); current; current = current->nextSibling()) {
if (current->isSVGHiddenContainer())
continue;
// Don't include elements in the union that do not render.
if (current->isSVGShape() && toRenderSVGShape(current)->isShapeEmpty())
continue;
const AffineTransform& transform = current->localToParentTransform();
updateObjectBoundingBox(objectBoundingBox, objectBoundingBoxValid, current,
transform.mapRect(current->objectBoundingBox()));
strokeBoundingBox.unite(transform.mapRect(current->paintInvalidationRectInLocalCoordinates()));
}
paintInvalidationBoundingBox = strokeBoundingBox;
}
bool SVGRenderSupport::paintInfoIntersectsPaintInvalidationRect(const FloatRect& localPaintInvalidationRect, const AffineTransform& localTransform, const PaintInfo& paintInfo)
{
return localTransform.mapRect(localPaintInvalidationRect).intersects(paintInfo.rect);
}
const RenderSVGRoot* SVGRenderSupport::findTreeRootObject(const RenderObject* start)
{
while (start && !start->isSVGRoot())
start = start->parent();
ASSERT(start);
ASSERT(start->isSVGRoot());
return toRenderSVGRoot(start);
}
inline bool SVGRenderSupport::layoutSizeOfNearestViewportChanged(const RenderObject* start)
{
while (start && !start->isSVGRoot() && !start->isSVGViewportContainer())
start = start->parent();
ASSERT(start);
ASSERT(start->isSVGRoot() || start->isSVGViewportContainer());
if (start->isSVGViewportContainer())
return toRenderSVGViewportContainer(start)->isLayoutSizeChanged();
return toRenderSVGRoot(start)->isLayoutSizeChanged();
}
bool SVGRenderSupport::transformToRootChanged(RenderObject* ancestor)
{
while (ancestor && !ancestor->isSVGRoot()) {
if (ancestor->isSVGTransformableContainer())
return toRenderSVGContainer(ancestor)->didTransformToRootUpdate();
if (ancestor->isSVGViewportContainer())
return toRenderSVGViewportContainer(ancestor)->didTransformToRootUpdate();
ancestor = ancestor->parent();
}
return false;
}
void SVGRenderSupport::layoutChildren(RenderObject* start, bool selfNeedsLayout)
{
// When hasRelativeLengths() is false, no descendants have relative lengths
// (hence no one is interested in viewport size changes).
bool layoutSizeChanged = toSVGElement(start->node())->hasRelativeLengths()
&& layoutSizeOfNearestViewportChanged(start);
bool transformChanged = transformToRootChanged(start);
for (RenderObject* child = start->slowFirstChild(); child; child = child->nextSibling()) {
bool forceLayout = selfNeedsLayout;
if (transformChanged) {
// If the transform changed we need to update the text metrics (note: this also happens for layoutSizeChanged=true).
if (child->isSVGText())
toRenderSVGText(child)->setNeedsTextMetricsUpdate();
forceLayout = true;
}
if (layoutSizeChanged) {
// When selfNeedsLayout is false and the layout size changed, we have to check whether this child uses relative lengths
if (SVGElement* element = child->node()->isSVGElement() ? toSVGElement(child->node()) : 0) {
if (element->hasRelativeLengths()) {
// FIXME: this should be done on invalidation, not during layout.
// When the layout size changed and when using relative values tell the RenderSVGShape to update its shape object
if (child->isSVGShape()) {
toRenderSVGShape(child)->setNeedsShapeUpdate();
} else if (child->isSVGText()) {
toRenderSVGText(child)->setNeedsTextMetricsUpdate();
toRenderSVGText(child)->setNeedsPositioningValuesUpdate();
}
forceLayout = true;
}
}
}
SubtreeLayoutScope layoutScope(*child);
// Resource containers are nasty: they can invalidate clients outside the current SubtreeLayoutScope.
// Since they only care about viewport size changes (to resolve their relative lengths), we trigger
// their invalidation directly from SVGSVGElement::svgAttributeChange() or at a higher
// SubtreeLayoutScope (in RenderView::layout()).
if (forceLayout && !child->isSVGResourceContainer())
layoutScope.setNeedsLayout(child);
// Lay out any referenced resources before the child.
layoutResourcesIfNeeded(child);
child->layoutIfNeeded();
}
}
void SVGRenderSupport::layoutResourcesIfNeeded(const RenderObject* object)
{
ASSERT(object);
SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(object);
if (resources)
resources->layoutIfNeeded();
}
bool SVGRenderSupport::isOverflowHidden(const RenderObject* object)
{
// RenderSVGRoot should never query for overflow state - it should always clip itself to the initial viewport size.
ASSERT(!object->isDocumentElement());
return object->style()->overflowX() == OHIDDEN || object->style()->overflowX() == OSCROLL;
}
void SVGRenderSupport::intersectPaintInvalidationRectWithResources(const RenderObject* renderer, FloatRect& paintInvalidationRect)
{
ASSERT(renderer);
SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(renderer);
if (!resources)
return;
if (RenderSVGResourceFilter* filter = resources->filter())
paintInvalidationRect = filter->resourceBoundingBox(renderer);
if (RenderSVGResourceClipper* clipper = resources->clipper())
paintInvalidationRect.intersect(clipper->resourceBoundingBox(renderer));
if (RenderSVGResourceMasker* masker = resources->masker())
paintInvalidationRect.intersect(masker->resourceBoundingBox(renderer));
}
bool SVGRenderSupport::filtersForceContainerLayout(RenderObject* object)
{
// If any of this container's children need to be laid out, and a filter is applied
// to the container, we need to issue paint invalidations the entire container.
if (!object->normalChildNeedsLayout())
return false;
SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(object);
if (!resources || !resources->filter())
return false;
return true;
}
bool SVGRenderSupport::pointInClippingArea(RenderObject* object, const FloatPoint& point)
{
ASSERT(object);
// We just take clippers into account to determine if a point is on the node. The Specification may
// change later and we also need to check maskers.
SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(object);
if (!resources)
return true;
if (RenderSVGResourceClipper* clipper = resources->clipper())
return clipper->hitTestClipContent(object->objectBoundingBox(), point);
return true;
}
bool SVGRenderSupport::transformToUserSpaceAndCheckClipping(RenderObject* object, const AffineTransform& localTransform, const FloatPoint& pointInParent, FloatPoint& localPoint)
{
if (!localTransform.isInvertible())
return false;
localPoint = localTransform.inverse().mapPoint(pointInParent);
return pointInClippingArea(object, localPoint);
}
void SVGRenderSupport::applyStrokeStyleToContext(GraphicsContext* context, const RenderStyle* style, const RenderObject* object)
{
ASSERT(context);
ASSERT(style);
ASSERT(object);
ASSERT(object->node());
ASSERT(object->node()->isSVGElement());
const SVGRenderStyle& svgStyle = style->svgStyle();
SVGLengthContext lengthContext(toSVGElement(object->node()));
context->setStrokeThickness(svgStyle.strokeWidth()->value(lengthContext));
context->setLineCap(svgStyle.capStyle());
context->setLineJoin(svgStyle.joinStyle());
context->setMiterLimit(svgStyle.strokeMiterLimit());
RefPtr<SVGLengthList> dashes = svgStyle.strokeDashArray();
if (dashes->isEmpty())
return;
DashArray dashArray;
SVGLengthList::ConstIterator it = dashes->begin();
SVGLengthList::ConstIterator itEnd = dashes->end();
for (; it != itEnd; ++it)
dashArray.append(it->value(lengthContext));
context->setLineDash(dashArray, svgStyle.strokeDashOffset()->value(lengthContext));
}
void SVGRenderSupport::applyStrokeStyleToStrokeData(StrokeData* strokeData, const RenderStyle* style, const RenderObject* object)
{
ASSERT(strokeData);
ASSERT(style);
ASSERT(object);
ASSERT(object->node());
ASSERT(object->node()->isSVGElement());
const SVGRenderStyle& svgStyle = style->svgStyle();
SVGLengthContext lengthContext(toSVGElement(object->node()));
strokeData->setThickness(svgStyle.strokeWidth()->value(lengthContext));
strokeData->setLineCap(svgStyle.capStyle());
strokeData->setLineJoin(svgStyle.joinStyle());
strokeData->setMiterLimit(svgStyle.strokeMiterLimit());
RefPtr<SVGLengthList> dashes = svgStyle.strokeDashArray();
if (dashes->isEmpty())
return;
DashArray dashArray;
size_t length = dashes->length();
for (size_t i = 0; i < length; ++i)
dashArray.append(dashes->at(i)->value(lengthContext));
strokeData->setLineDash(dashArray, svgStyle.strokeDashOffset()->value(lengthContext));
}
void SVGRenderSupport::fillOrStrokePath(GraphicsContext* context, unsigned short resourceMode, const Path& path)
{
ASSERT(resourceMode != ApplyToDefaultMode);
if (resourceMode & ApplyToFillMode)
context->fillPath(path);
if (resourceMode & ApplyToStrokeMode)
context->strokePath(path);
}
bool SVGRenderSupport::isRenderableTextNode(const RenderObject* object)
{
ASSERT(object->isText());
// <br> is marked as text, but is not handled by the SVG rendering code-path.
return object->isSVGInlineText() && !toRenderSVGInlineText(object)->hasEmptyText();
}
}
| {'content_hash': 'd8a128540f182a7f7f31a33c45eb8835', 'timestamp': '', 'source': 'github', 'line_count': 363, 'max_line_length': 233, 'avg_line_length': 42.65564738292011, 'alnum_prop': 0.736695944200465, 'repo_name': 'hgl888/blink-crosswalk-efl', 'id': 'f0a9cee861f40d10acd9c1ed29debfaf0265d3b3', 'size': '16617', 'binary': False, 'copies': '9', 'ref': 'refs/heads/efl/crosswalk-10/39.0.2171.19', 'path': 'Source/core/rendering/svg/SVGRenderSupport.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '1835'}, {'name': 'Assembly', 'bytes': '14584'}, {'name': 'Batchfile', 'bytes': '35'}, {'name': 'C', 'bytes': '113661'}, {'name': 'C++', 'bytes': '41933223'}, {'name': 'CSS', 'bytes': '525836'}, {'name': 'GLSL', 'bytes': '11578'}, {'name': 'Groff', 'bytes': '28067'}, {'name': 'HTML', 'bytes': '54848115'}, {'name': 'Java', 'bytes': '100403'}, {'name': 'JavaScript', 'bytes': '26269146'}, {'name': 'Makefile', 'bytes': '653'}, {'name': 'Objective-C', 'bytes': '111951'}, {'name': 'Objective-C++', 'bytes': '377325'}, {'name': 'PHP', 'bytes': '167892'}, {'name': 'Perl', 'bytes': '583834'}, {'name': 'Python', 'bytes': '3855349'}, {'name': 'Ruby', 'bytes': '141818'}, {'name': 'Shell', 'bytes': '8888'}, {'name': 'XSLT', 'bytes': '49099'}, {'name': 'Yacc', 'bytes': '64128'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<meta charset="utf-8"/>
<title>API Documentation</title>
<meta name="author" content=""/>
<meta name="description" content=""/>
<link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="../css/font-awesome.min.css" rel="stylesheet">
<link href="../css/prism.css" rel="stylesheet" media="all"/>
<link href="../css/template.css" rel="stylesheet" media="all"/>
<!--[if lt IE 9]>
<script src="../js/html5.js"></script>
<![endif]-->
<script src="../js/jquery-1.11.0.min.js"></script>
<script src="../js/ui/1.10.4/jquery-ui.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery.smooth-scroll.js"></script>
<script src="../js/prism.min.js"></script>
<!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit-->
<link rel="shortcut icon" href="../images/favicon.ico"/>
<link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
<link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
<link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="icon-ellipsis-vertical"></i>
</a>
<a class="brand" href="../index.html">API Documentation</a>
<div class="nav-collapse">
<ul class="nav pull-right">
<li class="dropdown">
<a href="../index.html" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="../namespaces/Services.html">\Services</a></li>
</ul>
</li>
<li class="dropdown" id="charts-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../graphs/class.html">
<i class="icon-list-alt"></i> Class hierarchy diagram
</a>
</li>
</ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i> Errors <span class="label label-info pull-right">0</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i> Markers <span class="label label-info pull-right">0</span>
</a>
</li>
<li>
<a href="../reports/deprecated.html">
<i class="icon-list-alt"></i> Deprecated <span class="label label-info pull-right">0</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<!--<div class="go_to_top">-->
<!--<a href="#___" style="color: inherit">Back to top  <i class="icon-upload icon-white"></i></a>-->
<!--</div>-->
</div>
<div id="___" class="container-fluid">
<section class="row-fluid">
<div class="span2 sidebar">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-935316169"></a>
<a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a>
</div>
<div id="namespace-935316169" class="accordion-body collapse in">
<div class="accordion-inner">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-28502641"></a>
<a href="../namespaces/Services.html" style="margin-left: 30px; padding-left: 0">Services</a>
</div>
<div id="namespace-28502641" class="accordion-body collapse ">
<div class="accordion-inner">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-928460265"></a>
<a href="../namespaces/Services.Bundle.html" style="margin-left: 30px; padding-left: 0">Bundle</a>
</div>
<div id="namespace-928460265" class="accordion-body collapse ">
<div class="accordion-inner">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-168012072"></a>
<a href="../namespaces/Services.Bundle.Rest.html" style="margin-left: 30px; padding-left: 0">Rest</a>
</div>
<div id="namespace-168012072" class="accordion-body collapse ">
<div class="accordion-inner">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-571083761"></a>
<a href="../namespaces/Services.Bundle.Rest.Controller.html" style="margin-left: 30px; padding-left: 0">Controller</a>
</div>
<div id="namespace-571083761" class="accordion-body collapse ">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/Services.Bundle.Rest.Controller.DefaultController.html">DefaultController</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-1051158327"></a>
<a href="../namespaces/Services.Bundle.Rest.Entity.html" style="margin-left: 30px; padding-left: 0">Entity</a>
</div>
<div id="namespace-1051158327" class="accordion-body collapse ">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/Services.Bundle.Rest.Entity.ChiamataRest.html">ChiamataRest</a></li>
<li class="class"><a href="../classes/Services.Bundle.Rest.Entity.Risultato.html">Risultato</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-1074530520"></a>
<a href="../namespaces/Services.Bundle.Rest.Tests.html" style="margin-left: 30px; padding-left: 0">Tests</a>
</div>
<div id="namespace-1074530520" class="accordion-body collapse ">
<div class="accordion-inner">
<div class="accordion" style="margin-bottom: 0">
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-1591670099"></a>
<a href="../namespaces/Services.Bundle.Rest.Tests.Controller.html" style="margin-left: 30px; padding-left: 0">Controller</a>
</div>
<div id="namespace-1591670099" class="accordion-body collapse ">
<div class="accordion-inner">
<ul>
<li class="class"><a href="../classes/Services.Bundle.Rest.Tests.Controller.DefaultControllerTest.html">DefaultControllerTest</a></li>
</ul>
</div>
</div>
</div>
</div>
<ul>
</ul>
</div>
</div>
</div>
</div>
<ul>
<li class="class"><a href="../classes/Services.Bundle.Rest.ServicesRestBundle.html">ServicesRestBundle</a></li>
</ul>
</div>
</div>
</div>
</div>
<ul>
</ul>
</div>
</div>
</div>
</div>
<ul>
</ul>
</div>
</div>
</div>
</div>
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
</section>
<section class="row-fluid">
<div class="span10 offset2">
<div class="row-fluid">
<div class="span8 content namespace">
<nav>
<a href="../namespaces/Services.Bundle.Rest.html">\Services\Bundle\Rest</a>
</nav>
<h1><small>\Services\Bundle\Rest</small>Entity</h1>
<h2>Classes</h2>
<table class="table table-hover">
<tr>
<td><a href="../classes/Services.Bundle.Rest.Entity.ChiamataRest.html">ChiamataRest</a></td>
<td><em>This class permit to call rest resources</em></td>
</tr>
<tr>
<td><a href="../classes/Services.Bundle.Rest.Entity.Risultato.html">Risultato</a></td>
<td><em>This class contains the format for the json response</em></td>
</tr>
</table>
</div>
<aside class="span4 detailsbar">
<dl>
<dt>Namespace hierarchy</dt>
<dd class="hierarchy">
<div class="namespace-wrapper"><a href="../namespaces/default.html">\</a></div>
<div class="namespace-wrapper"><a href="../namespaces/Services.html">\Services</a></div>
<div class="namespace-wrapper"><a href="../namespaces/Services.Bundle.html">\Services\Bundle</a></div>
<div class="namespace-wrapper"><a href="../namespaces/Services.Bundle.Rest.html">\Services\Bundle\Rest</a></div>
<div class="namespace-wrapper">\Services\Bundle\Rest\Entity</div>
</dd>
</dl>
</aside>
</div>
</div>
</section>
<footer class="row-fluid">
<section class="span10 offset2">
<section class="row-fluid">
<section class="span10 offset1">
<section class="row-fluid footer-sections">
<section class="span4">
<h1><i class="icon-code"></i></h1>
<div>
<ul>
<li><a href="../namespaces/Services.html">\Services</a></li>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-bar-chart"></i></h1>
<div>
<ul>
<li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-pushpin"></i></h1>
<div>
<ul>
<li><a href="../reports/errors.html">Errors</a></li>
<li><a href="../reports/markers.html">Markers</a></li>
</ul>
</div>
</section>
</section>
</section>
</section>
<section class="row-fluid">
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on March 3rd, 2017 at 08:19.
</section>
</section>
</section>
</footer>
</div>
</body>
</html>
| {'content_hash': '4808ec74eef50b5af89001dcf842cdcb', 'timestamp': '', 'source': 'github', 'line_count': 332, 'max_line_length': 676, 'avg_line_length': 54.56325301204819, 'alnum_prop': 0.3615788020977091, 'repo_name': 'brunopicci/call-rest-api', 'id': '79d4d3b8ad76550bd45060094e687cf135f27b53', 'size': '18115', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Resources/doc/namespaces/Services.Bundle.Rest.Entity.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14643'}, {'name': 'HTML', 'bytes': '471986'}, {'name': 'JavaScript', 'bytes': '58657'}, {'name': 'PHP', 'bytes': '24425'}]} |
/*jshint node: true, -W106 */
'use strict';
/*
* Name : lineChartModel.js
* Module : Lib::DataTier::LineChartModel
* Location : /lib/dataTier/graph
*
* History :
*
* Version Date Programmer Description
* =========================================================
* 0.0.1 2015-05-13 Samuele Zanella Initial code
* =========================================================
*/
var GraphModel = require('./graphModel.js');
var LineChartFlowModel = require('../flow/lineChartFlowModel.js');
var AxisModel = require('../graph/axisModel.js');
var Helper = require('../../helpers/functionHelper.js');
//if params are valid build object else return error
function LineChartModel(params) {
if(params===undefined || params.ID===undefined || typeof params.ID !== 'string'|| params.ID.trim() === ''){ // ID field is required
console.log('Error: 322');
return;
}
params.type = 'LineChart';
this.parent.constructor.call(this, params);
this._xAxis=new AxisModel();
this._yAxis=new AxisModel();
this._backgroundColor='#FFFFFF';
this._flows=[];
this._viewFinder=false;
this._interpolation='linear';//linear, step, basis, cardinal, monotone
this._horizontalGrid=true;
this._verticalGrid=true;
this._legendOnPoint=false;
this.updateProperties(params);
}
LineChartModel.prototype = Object.create(GraphModel.prototype);
LineChartModel.prototype.constructor = LineChartModel;
LineChartModel.prototype.parent = GraphModel.prototype;
//if flow is valid, add it to flows
LineChartModel.prototype.addFlow = function(flow) {
if(flow instanceof LineChartFlowModel) {
this._flows.push(flow);
}
};
LineChartModel.prototype.addRecord = function(flowID, record) {
var filteredFlows = this._flows.filter(function(flow) {return flow.getProperties().ID === flowID;});
if(filteredFlows.length > 0) {
var flow = filteredFlows[0];
return flow.addRecord(record);
}
else {
console.log('Error: 221');
return 221;
}
};
//delete all flows
LineChartModel.prototype.deleteAllFlows = function() {
this._flows = [];
};
//delete flow specified
LineChartModel.prototype.deleteFlow = function(ID) {
if(typeof ID === 'string') {
for(var i=0; i < this._flows.length; i++) {
if(this._flows[i].getProperties().ID === ID) {
this._flows.splice(i, 1);
}
}
}
};
//return JSON with all data
LineChartModel.prototype.getData = function() {
var graphData=[];
var flows= this._flows.length;
//build graphData by iterating every flow in _flows
for(var i=0; i<flows; i++){
graphData[i]={
properties: this._flows[i].getProperties(),
data: this._flows[i].getData()
};
}//for flows
return graphData;
};
//return JSON with properties
LineChartModel.prototype.getProperties = function() {
var res = this.parent.getProperties.call(this);
res.horizontalGrid = this._horizontalGrid;
res.verticalGrid = this._verticalGrid;
res.viewFinder = this._viewFinder;
res.xAxis = this._xAxis.getProperties();
res.yAxis = this._yAxis.getProperties();
res.interpolation=this._interpolation;
res.backgroundColor = this._backgroundColor;
res.legendOnPoint = this._legendOnPoint;
return res;
};
//updates valid properties
LineChartModel.prototype.updateProperties = function(params) {
if (params !== undefined){
var prop=this.parent.updateBaseProperties.call(this, params);
if(params.xAxis!==undefined){
this._xAxis.updateProperties(params.xAxis);
prop.xAxis=this._xAxis.getProperties();
}
if(params.yAxis!==undefined){
this._yAxis.updateProperties(params.yAxis);
prop.yAxis=this._yAxis.getProperties();
}
if(params.backgroundColor!==undefined && (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(params.backgroundColor))){
this._backgroundColor=prop.backgroundColor=params.backgroundColor;
}
if(params.horizontalGrid!==undefined && typeof params.horizontalGrid === 'boolean'){
this._horizontalGrid=prop.horizontalGrid=params.horizontalGrid;
}
if(params.verticalGrid!==undefined && typeof params.verticalGrid === 'boolean'){
this._verticalGrid=prop.verticalGrid=params.verticalGrid;
}
if(params.viewFinder!==undefined && typeof params.viewFinder === 'boolean'){
this._viewFinder=prop.viewFinder=params.viewFinder;
}
if(params.interpolation!==undefined && Helper.isValidInterpolation(params.interpolation)){
this._interpolation=prop.interpolation=params.interpolation;
}
if(params.legendOnPoint!==undefined && typeof params.legendOnPoint === 'boolean'){
this._legendOnPoint=prop.legendOnPoint=params.legendOnPoint;
}
return prop;
}
//return error;
};
//update record specified
LineChartModel.prototype.updateRecord = function(flowID, index, newRecord) {
var filteredFlows = this._flows.filter(function(flow) {return flow.getProperties().ID === flowID;});
if(filteredFlows.length > 0) {
var flow = filteredFlows[0];
return flow.updateRecord(index, newRecord);
}
else {
console.log('Error: 221');
return 221;
}
};
module.exports = LineChartModel; | {'content_hash': '6504a8e17f6996d6f8e6687f673a693d', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 132, 'avg_line_length': 30.1030303030303, 'alnum_prop': 0.6963962150191262, 'repo_name': 'DeltaGraphs/norris-nrti', 'id': '38d5ee968916858943619e0e2d4af727fa7cd8ab', 'size': '4967', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/dataTier/graph/lineChartModel.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '27353'}, {'name': 'HTML', 'bytes': '3126'}, {'name': 'JavaScript', 'bytes': '3436730'}, {'name': 'Makefile', 'bytes': '5018'}, {'name': 'Shell', 'bytes': '1565'}]} |
<!--
Copyright 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<polymer-element name="ct-commit" attributes="data" noscript>
<template>
<style>
:host {
display: flex;
align-items: center;
}
:host > * {
flex-shrink: 0;
}
a {
padding: 5px;
margin-right: 5px;
border-radius: 4px;
}
div {
flex: 1;
}
:host(:hover) a {
background-color: #555;
color: white;
}
</style>
<a href="{{ data.url }}">{{ data.revision }}</a>
<div>{{ data.summary }} <em>{{ data.author }}</em></div>
</template>
</polymer-element>
| {'content_hash': '5ea7835fb231f862e974e8258e5ea3aa', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 70, 'avg_line_length': 22.87878787878788, 'alnum_prop': 0.5311258278145695, 'repo_name': 'crosswalk-project/blink-crosswalk-efl', 'id': '1a2650b4eef26b2e055ae7f8ed0d59dc560218ce', 'size': '755', 'binary': False, 'copies': '11', 'ref': 'refs/heads/efl/crosswalk-10/39.0.2171.19', 'path': 'Tools/GardeningServer/ui/ct-commit.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '14584'}, {'name': 'Bison', 'bytes': '64128'}, {'name': 'C', 'bytes': '1509300'}, {'name': 'C++', 'bytes': '40536721'}, {'name': 'CSS', 'bytes': '531170'}, {'name': 'Java', 'bytes': '66510'}, {'name': 'JavaScript', 'bytes': '26453909'}, {'name': 'Makefile', 'bytes': '653'}, {'name': 'Objective-C', 'bytes': '31620'}, {'name': 'Objective-C++', 'bytes': '377325'}, {'name': 'PHP', 'bytes': '167892'}, {'name': 'Perl', 'bytes': '583834'}, {'name': 'Python', 'bytes': '3857224'}, {'name': 'Ruby', 'bytes': '141818'}, {'name': 'Shell', 'bytes': '8923'}, {'name': 'XSLT', 'bytes': '49099'}]} |
<?php
namespace spec\maxwilms\BloomFilter;
use maxwilms\BloomFilter\IntBitField;
use maxwilms\BloomFilter\Hash\MultiHash;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class BloomFilterSpec extends ObjectBehavior
{
function let(IntBitField $bitField, MultiHash $multiHash)
{
$this->beConstructedWith($bitField, $multiHash);
}
function it_uses_multiHash_to_add_items(IntBitField $bitField, MultiHash $multiHash)
{
$multiHash->hash('123')->willReturn([1, 4, 8]);
$bitField->set(1)->shouldBeCalled();
$bitField->set(4)->shouldBeCalled();
$bitField->set(8)->shouldBeCalled();
$this->add('123');
}
function it_confirms_existence_of_valid_items(IntBitField $bitField, MultiHash $multiHash)
{
$multiHash->hash('my string')->willReturn([1, 2]);
$bitField->has(1)->willReturn(true);
$bitField->has(2)->willReturn(true);
$this->contains('my string')->shouldReturn(true);
}
function it_denies_existence_of_items_not_in_set(IntBitField $bitField, MultiHash $multiHash)
{
$multiHash->hash('my string')->willReturn([1, 4]);
$bitField->has(1)->willReturn(false);
$bitField->has(4)->willReturn(true);
$this->contains('my string')->shouldReturn(false);
}
}
| {'content_hash': '4612d51d71cef0af2e060c2455a42074', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 97, 'avg_line_length': 27.458333333333332, 'alnum_prop': 0.650227617602428, 'repo_name': 'maxwilms/bloom-filter', 'id': '0ada4832b94415b32194c204e30444530e8525f1', 'size': '1318', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/BloomFilterSpec.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Gherkin', 'bytes': '634'}, {'name': 'PHP', 'bytes': '12096'}]} |
using System.Text.Json;
using Azure.Core;
namespace Azure.Media.VideoAnalyzer.Edge.Models
{
public partial class OnvifDeviceGetRequest : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("endpoint");
writer.WriteObjectValue(Endpoint);
if (Optional.IsDefined(ApiVersion))
{
writer.WritePropertyName("@apiVersion");
writer.WriteStringValue(ApiVersion);
}
writer.WriteEndObject();
}
internal static OnvifDeviceGetRequest DeserializeOnvifDeviceGetRequest(JsonElement element)
{
EndpointBase endpoint = default;
string methodName = default;
Optional<string> apiVersion = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("endpoint"))
{
endpoint = EndpointBase.DeserializeEndpointBase(property.Value);
continue;
}
if (property.NameEquals("methodName"))
{
methodName = property.Value.GetString();
continue;
}
if (property.NameEquals("@apiVersion"))
{
apiVersion = property.Value.GetString();
continue;
}
}
return new OnvifDeviceGetRequest(methodName, apiVersion.Value, endpoint);
}
}
}
| {'content_hash': 'c8c122c7df7519deacc87cb2685a3c42', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 99, 'avg_line_length': 34.59574468085106, 'alnum_prop': 0.544280442804428, 'repo_name': 'Azure/azure-sdk-for-net', 'id': '65ba44275567c8848c6e88d5bc8ebb7a6d2a20a9', 'size': '1764', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/videoanalyzer/Azure.Media.VideoAnalyzer.Edge/src/Generated/Models/OnvifDeviceGetRequest.Serialization.cs', 'mode': '33188', 'license': 'mit', 'language': []} |
#import "AWSRequest.h"
@class NSString, NSNumber;
@interface AWSEC2AttachVolumeRequest : AWSRequest {
NSString* _device;
NSNumber* _dryRun;
NSString* _instanceId;
NSString* _volumeId;
}
@property(retain, nonatomic) NSString* device;
@property(retain, nonatomic) NSNumber* dryRun;
@property(retain, nonatomic) NSString* instanceId;
@property(retain, nonatomic) NSString* volumeId;
+ (id)JSONKeyPathsByPropertyKey;
- (void).cxx_destruct;
@end
| {'content_hash': 'c7cc7c24fc7728b678d81f8d0f51ee8b', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 51, 'avg_line_length': 22.5, 'alnum_prop': 0.7622222222222222, 'repo_name': 'ZaneH/ChineseSkill-Hack', 'id': '7c88a75471d5b2edfff99c4dd7477400df570541', 'size': '601', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ChineseSkill-Headers/AWSEC2AttachVolumeRequest.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3263'}, {'name': 'Groff', 'bytes': '2'}, {'name': 'Logos', 'bytes': '6437'}, {'name': 'Makefile', 'bytes': '293'}, {'name': 'Objective-C', 'bytes': '2563544'}]} |
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var Event = (function () {
function Event(config) {
_classCallCheck(this, Event);
var me = this;
me.action = config.action;
me.executing = false;
me.listeners = config.listeners;
me.payload = config.payload;
me.type = config.type;
}
_createClass(Event, [{
key: 'execute',
value: function execute() {
var me = this;
if (me.executing) {
return me.promise;
}
me.executing = true;
return me.promise = new Promise(function (resolve, reject) {
var listeners = me.listeners;
listeners.forEach(function (listener) {
if (!me.executing) {
reject();
return;
}
var callback = listener.callback;
if (callback) {
callback(me, listener);
}
});
resolve();
me.executing = false;
me.promise = null;
});
}
}, {
key: 'stop',
value: function stop() {
var me = this;
if (me.executing) {
var promise = me.promise;
if (promise) {
promise.reject();
}
me.executing = false;
me.promise = null;
}
}
}, {
key: 'action',
get: function get() {
return this._action;
},
set: function set(action) {
this._action = action;
return this;
}
}, {
key: 'executing',
get: function get() {
return this._executing;
},
set: function set(executing) {
this._executing = executing;
return this;
}
}, {
key: 'listeners',
get: function get() {
return this._listeners;
},
set: function set(listeners) {
this._listeners = listeners;
return this;
}
}, {
key: 'payload',
get: function get() {
return this._payload;
},
set: function set(payload) {
this._payload = payload;
return this;
}
}, {
key: 'promise',
get: function get() {
return this._promise;
},
set: function set(promise) {
this._promise = promise;
return this;
}
}, {
key: 'type',
get: function get() {
return this._type;
},
set: function set(type) {
this._type = type;
return this;
}
}]);
return Event;
})();
module.exports = Event;
| {'content_hash': 'd2167ef09387605e4afda56d5fd3ec3e', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 566, 'avg_line_length': 26.5, 'alnum_prop': 0.47780244173140957, 'repo_name': 'mitchellsimoens/react-idispatcher', 'id': '41359cdba8fab2e77d66c0e307c2dfee8eeefca5', 'size': '3604', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Event.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '15021'}]} |
#ifndef SKY_ENGINE_PLATFORM_FONTS_FONTFALLBACKLIST_H_
#define SKY_ENGINE_PLATFORM_FONTS_FONTFALLBACKLIST_H_
#include "sky/engine/platform/fonts/FontSelector.h"
#include "sky/engine/platform/fonts/SimpleFontData.h"
#include "sky/engine/platform/fonts/WidthCache.h"
#include "sky/engine/wtf/Forward.h"
#include "sky/engine/wtf/MainThread.h"
namespace blink {
class GlyphPageTreeNode;
class FontDescription;
const int cAllFamiliesScanned = -1;
class PLATFORM_EXPORT FontFallbackList : public RefCounted<FontFallbackList> {
WTF_MAKE_NONCOPYABLE(FontFallbackList);
public:
typedef HashMap<int, GlyphPageTreeNode*, DefaultHash<int>::Hash> GlyphPages;
class GlyphPagesStateSaver {
public:
GlyphPagesStateSaver(FontFallbackList& fallbackList)
: m_fallbackList(fallbackList)
, m_pages(fallbackList.m_pages)
, m_pageZero(fallbackList.m_pageZero)
{
}
~GlyphPagesStateSaver()
{
m_fallbackList.m_pages = m_pages;
m_fallbackList.m_pageZero = m_pageZero;
}
private:
FontFallbackList& m_fallbackList;
GlyphPages& m_pages;
GlyphPageTreeNode* m_pageZero;
};
static PassRefPtr<FontFallbackList> create() { return adoptRef(new FontFallbackList()); }
~FontFallbackList() { releaseFontData(); }
void invalidate(PassRefPtr<FontSelector>);
bool isFixedPitch(const FontDescription& fontDescription) const
{
if (m_pitch == UnknownPitch)
determinePitch(fontDescription);
return m_pitch == FixedPitch;
}
void determinePitch(const FontDescription&) const;
bool loadingCustomFonts() const;
bool shouldSkipDrawing() const;
FontSelector* fontSelector() const { return m_fontSelector.get(); }
// FIXME: It should be possible to combine fontSelectorVersion and generation.
unsigned fontSelectorVersion() const { return m_fontSelectorVersion; }
unsigned generation() const { return m_generation; }
WidthCache& widthCache() const { return m_widthCache; }
const SimpleFontData* primarySimpleFontData(const FontDescription& fontDescription)
{
ASSERT(isMainThread());
if (!m_cachedPrimarySimpleFontData)
m_cachedPrimarySimpleFontData = determinePrimarySimpleFontData(fontDescription);
return m_cachedPrimarySimpleFontData;
}
const FontData* fontDataAt(const FontDescription&, unsigned index) const;
GlyphPageTreeNode* getPageNode(unsigned pageNumber) const
{
return pageNumber ? m_pages.get(pageNumber) : m_pageZero;
}
void setPageNode(unsigned pageNumber, GlyphPageTreeNode* node)
{
if (pageNumber)
m_pages.set(pageNumber, node);
else
m_pageZero = node;
}
private:
FontFallbackList();
PassRefPtr<FontData> getFontData(const FontDescription&, int& familyIndex) const;
const SimpleFontData* determinePrimarySimpleFontData(const FontDescription&) const;
void releaseFontData();
mutable Vector<RefPtr<FontData>, 1> m_fontList;
GlyphPages m_pages;
GlyphPageTreeNode* m_pageZero;
mutable const SimpleFontData* m_cachedPrimarySimpleFontData;
RefPtr<FontSelector> m_fontSelector;
mutable WidthCache m_widthCache;
unsigned m_fontSelectorVersion;
mutable int m_familyIndex;
unsigned short m_generation;
mutable unsigned m_pitch : 3; // Pitch
mutable bool m_hasLoadingFallback : 1;
};
} // namespace blink
#endif // SKY_ENGINE_PLATFORM_FONTS_FONTFALLBACKLIST_H_
| {'content_hash': 'c4fc66b917e15313b825ea76be1de0fa', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 93, 'avg_line_length': 31.263157894736842, 'alnum_prop': 0.7048260381593715, 'repo_name': 'iansf/sky_engine', 'id': 'bf2b668cad718943bbe30321ddaad769431d952c', 'size': '4408', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'sky/engine/platform/fonts/FontFallbackList.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2706'}, {'name': 'C', 'bytes': '1517722'}, {'name': 'C++', 'bytes': '28072121'}, {'name': 'Dart', 'bytes': '959402'}, {'name': 'Groff', 'bytes': '29030'}, {'name': 'HTML', 'bytes': '41854'}, {'name': 'Java', 'bytes': '771021'}, {'name': 'JavaScript', 'bytes': '27365'}, {'name': 'Makefile', 'bytes': '402'}, {'name': 'Objective-C', 'bytes': '104718'}, {'name': 'Objective-C++', 'bytes': '440295'}, {'name': 'Protocol Buffer', 'bytes': '1048'}, {'name': 'Python', 'bytes': '4827402'}, {'name': 'Shell', 'bytes': '173505'}, {'name': 'Yacc', 'bytes': '31141'}, {'name': 'nesC', 'bytes': '18347'}]} |
There are
### Appendix: Module.Exports and Exports
Module.exports and exports [are not the same thing](https://stackoverflow.com/questions/16383795/difference-between-module-exports-and-exports-in-the-commonjs-module-system).
'''
var module = { exports: {} };
var exports = module.exports;
```
## Supporting all Possible Implementations in CommonJS
While in theory the CommonJS specification requires support for `exports` as a variable and not `module.exports` I am not aware of any [CommonJS implementation which does not support `module.exports`]](
https://stackoverflow.com/questions/41345087/is-there-a-commonjs-require-implementation-that-doesnt-use-module-exports?noredirect=1&lq=1)
Nonetheless, If you want to have all of your bases covered then you can add the following line to your module:
```
// Support all Common.JS modules
else if (exports != undefined) exports = myModule;```
```
| {'content_hash': '3fa0ba54dd3b1dd5cad4b2a000f579b0', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 202, 'avg_line_length': 40.130434782608695, 'alnum_prop': 0.752979414951246, 'repo_name': 'cdiggins/cdiggins.github.io', 'id': '6ee7ddcb89acb8fe042f23ad39aae5611bf1c285', 'size': '945', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/articles/common-js.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '255'}, {'name': 'HTML', 'bytes': '259069'}, {'name': 'JavaScript', 'bytes': '17601'}]} |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
c44b9155-1936-47af-b45a-3e67d3b46f3e
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#Library.Net.IoC.StructureMap">Library.Net.IoC.StructureMap</a></strong></td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
</div>
</div>
</body>
</html> | {'content_hash': 'e4f2514a5c6dcc2053b44477a269168a', 'timestamp': '', 'source': 'github', 'line_count': 240, 'max_line_length': 562, 'avg_line_length': 40.295833333333334, 'alnum_prop': 0.5741908799503671, 'repo_name': 'kuhlenh/port-to-core', 'id': '04126d6628529177ce627ebc3bccc0f2aac65653', 'size': '9671', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'Reports/li/library.net.ioc.structuremap.1.0.0.1/Library.Net.IoC.StructureMap-net45.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2323514650'}]} |
<?php
/**
* Created by PhpStorm.
* User: kenny
* Date: 12/19/16
* Time: 10:23 AM
*/
namespace PayU\Test\Api;
use PayU\Api\Response;
class ResponseTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Object Instance with Json data filled in
* @return Response
*/
public static function getObject()
{
return new Response(self::getJson());
}
/**
* Gets Json String of Object Address
* @return string
*/
public static function getJson()
{
return '{"displayMessage":"TestSample","merchantReference":"TestSample","payUReference":"TestSample","resultCode":"TestSample","resultMessage":"TestSample","successful":"TestSample","transactionType":"TestSample","transactionState":"TestSample","basket":' . BasketTest::getJson() . ',"secure3D":' . Secure3DTest::getJson() . ',"customFields":' . CustomFieldsTest::getJson() . ',"lookupData":' . LookupDataTest::getJson() . ',"paymentMethodsUsed":' . PaymentMethodTest::getJson() . ',"recurringDetails":' . RecurringDetailsTest::getJson() . ',"redirect":' . EFTBaseTest::getJson() . ',"fraud":' . FmDetailsTest::getJson() . '}';
}
/**
* Tests for Serialization and Deserialization Issues
* @return Response
*/
public function testSerializationDeserialization()
{
$obj = new Response(self::getJson());
$this->assertNotNull($obj);
$this->assertNotNull($obj->getDisplayMessage());
$this->assertNotNull($obj->getMerchantReference());
$this->assertNotNull($obj->getPayUReference());
$this->assertNotNull($obj->getResultCode());
$this->assertNotNull($obj->getResultMessage());
$this->assertNotNull($obj->getSuccessful());
$this->assertNotNull($obj->getTransactionType());
$this->assertNotNull($obj->getTransactionState());
$this->assertNotNull($obj->getBasket());
$this->assertNotNull($obj->getSecure3D());
$this->assertNotNull($obj->getCustomFields());
$this->assertNotNull($obj->getLookupData());
$this->assertNotNull($obj->getPaymentMethodsUsed());
$this->assertNotNull($obj->getRecurringDetails());
$this->assertNotNull($obj->getRedirect());
$this->assertNotNull($obj->getFraud());
$this->assertEquals(self::getJson(), $obj->toJson());
return $obj;
}
/**
* @depends testSerializationDeserialization
* @param Response $obj
*/
public function testGetters($obj)
{
$this->assertEquals($obj->getDisplayMessage(), "TestSample");
$this->assertEquals($obj->getMerchantReference(), "TestSample");
$this->assertEquals($obj->getPayUReference(), "TestSample");
$this->assertEquals($obj->getResultCode(), "TestSample");
$this->assertEquals($obj->getResultMessage(), "TestSample");
$this->assertEquals($obj->getSuccessful(), "TestSample");
$this->assertEquals($obj->getTransactionType(), "TestSample");
$this->assertEquals($obj->getTransactionState(), "TestSample");
$this->assertEquals($obj->getBasket(), BasketTest::getObject());
$this->assertEquals($obj->getSecure3D(), Secure3DTest::getObject());
$this->assertEquals($obj->getCustomFields(), CustomFieldsTest::getObject());
$this->assertEquals($obj->getLookupData(), LookupDataTest::getObject());
$this->assertEquals($obj->getPaymentMethodsUsed(), PaymentMethodTest::getObject());
$this->assertEquals($obj->getRecurringDetails(), RecurringDetailsTest::getObject());
$this->assertEquals($obj->getRedirect(), EFTBaseTest::getObject());
$this->assertEquals($obj->getFraud(), FmDetailsTest::getObject());
}
}
| {'content_hash': '1a4219dd05e4ae75f01ec63682e9424f', 'timestamp': '', 'source': 'github', 'line_count': 84, 'max_line_length': 635, 'avg_line_length': 44.25, 'alnum_prop': 0.6464891041162227, 'repo_name': 'netcraft-devops/payu-sdk-php', 'id': 'e356576b5683a4938adacf7302fb1301acc875ea', 'size': '3717', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/PayU/Test/Api/ResponseTest.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '389026'}]} |
package ru.cloudinfosys.isComboBox;
import java.io.Serializable;
public class ComboBoxConstants implements Serializable {
public static final String ATTR_INPUTPROMPT = "prompt";
public static final String ATTR_NO_TEXT_INPUT = "noInput";
public static final String ATTR_OPEN_BY_CLICK = "openByClick";
public static final String ATTR_HAS_SELECT_BUTTON = "hasSelectBtn";
public static final String ATTR_HAS_CLEAR_BUTTON = "hasClearBtn";
public static final String ATTR_HAS_OPEN_BUTTON = "hasOpenBtn";
}
| {'content_hash': 'b5b5ebd766f9e0e2e20719ed449d1cb6', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 71, 'avg_line_length': 35.266666666666666, 'alnum_prop': 0.7542533081285444, 'repo_name': 'nicolasDmit/isComboBox', 'id': '52a7f77ee807b56946ba7747a278ace0153e1348', 'size': '1124', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'isComboBox-addon/src/main/java/ru/cloudinfosys/isComboBox/ComboBoxConstants.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '308663'}, {'name': 'Java', 'bytes': '193735'}]} |
from bottle import route, default_app
@route('/')
def home():
"""Home page."""
return 'home'
@route('/<user>')
def user(user):
"""User profile page.
:param user: user login name
:status 200: when user exists
:status 404: when user doesn't exist
"""
return 'hi, ' + user
@route('/<user>/posts/<post_id:int>')
def post(user, post_id):
"""User's post.
:param user: user login name
:param post_id: post unique id
:status 200: when user and post exists
:status 404: when user and post doesn't exist
"""
return str(post_id), 'by', user
app = default_app()
| {'content_hash': '2066ace726bb73c7b0596408c56d829f', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 49, 'avg_line_length': 17.771428571428572, 'alnum_prop': 0.6012861736334405, 'repo_name': 'superduper/sphinxcontrib-httpdomain', 'id': '3fdf2656dede34ec4cffadea767f0a3357909c86', 'size': '622', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'doc/autobottle_sampleapp.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Python', 'bytes': '45166'}, {'name': 'Shell', 'bytes': '9304'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ask open-ended questions • Habitry Source</title>
<meta name="description" content="In order to check for understanding, we’re going to practice offer reflections.
">
<meta name="keywords" content="">
<!-- Twitter Cards -->
<meta name="twitter:title" content="Ask open-ended questions">
<meta name="twitter:description" content="In order to check for understanding, we’re going to practice offer reflections.
">
<meta name="twitter:creator" content="@omarganai">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://localhost:4000/images/Habitry-120x120-transparent.png">
<!-- Open Graph -->
<meta property="og:locale" content="en">
<meta property="og:type" content="article">
<meta property="og:title" content="Ask open-ended questions">
<meta property="og:description" content="In order to check for understanding, we’re going to practice offer reflections.
">
<meta property="og:url" content="http://localhost:4000/habits/oeqs/">
<meta property="og:site_name" content="Habitry Source">
<link rel="canonical" href="http://localhost:4000/habits/oeqs/">
<link href="http://localhost:4000/atom.xml" type="application/atom+xml" rel="alternate" title="Habitry Source Atom Feed">
<link href="http://localhost:4000/sitemap.xml" type="application/xml" rel="sitemap" title="Sitemap">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="http://localhost:4000/css/main.css">
<!-- HTML5 Shiv and Media Query Support for IE -->
<!--[if lt IE 9]>
<script src="http://localhost:4000/js/vendor/html5shiv.min.js"></script>
<script src="http://localhost:4000/js/vendor/respond.min.js"></script>
<![endif]-->
</head>
<body id="js-body">
<!--[if lt IE 9]><div class="upgrade notice-warning"><strong>Your browser is quite old!</strong> Why not <a href="http://whatbrowser.org/">upgrade to a newer one</a> to better enjoy this site?</div><![endif]-->
<header id="masthead">
<div class="inner-wrap">
<a href="http://localhost:4000/" class="site-title">Habitry Source</a>
<nav role="navigation" class="menu top-menu">
<ul class="menu-item">
<li class="home"><a href="/">Habitry Source</a></li>
<li><a href="http://localhost:4000/about/" >About</a></li>
<li><a href="http://localhost:4000/habits/" >Habits</a></li>
</ul>
</nav>
</div><!-- /.inner-wrap -->
</header><!-- /.masthead -->
<nav role="navigation" id="js-menu" class="sliding-menu-content">
<h5>Habitry Source <span>Table of Contents</span></h5>
<ul class="menu-item">
<li>
<a href="http://localhost:4000/about/">
<div class="title">About</div>
</a>
</li><li>
<a href="http://localhost:4000/habits/">
<div class="title">Habits</div>
</a>
</li>
</ul>
</nav>
<button type="button" id="js-menu-trigger" class="sliding-menu-button lines-button x2" role="button" aria-label="Toggle Navigation">
<span class="nav-lines"></span>
</button>
<div id="js-menu-screen" class="menu-screen"></div>
<div id="page-wrapper">
<div id="main" role="main">
<article class="wrap" itemscope itemtype="http://schema.org/Article">
<div class="page-title">
<h1>Ask open-ended questions</h1>
</div>
<div class="inner-wrap">
<div id="content" class="page-content" itemprop="articleBody">
<p>In order to check for understanding, we’re going to practice offer reflections.</p>
<h3 id="why">Why</h3>
<p>By offering reflections, you paraphrase back what the client is thinking and feeling. You express your understanding of their thoughts and feelings back to them. Reflections help us bridge the gap between what the client is communicating and the coach hears, and allow coaches to check for their understanding of what was said.</p>
<h3 id="how">How</h3>
<p>Take a guess at how your client is feeling. Then say that.</p>
<p>You might use the following preambles to start your reflections to let your client know you’re about to take a guess.</p>
<ul>
<li>It sounds like…</li>
<li>I get the sense that…</li>
<li>It feels as though…</li>
<li>You seem to be saying…</li>
</ul>
<p>After saying one of those preambles, you could then add the reflection. For example, if you wanted to offer a reflection about a client feeling frustrated, it might look like:</p>
<ul>
<li>You seem to be saying… you’re not happy with how you’re handling social events</li>
</ul>
<h3 id="when">When:</h3>
<p>To get into the habit of offering reflections, it’s a good idea to figure out a trigger ahead of time for when you’ll make them. That way you’ll remember to offer them.</p>
<p>What specific situation do you want to offer reflections? For example, you could offer a reflection after a client answers an OEQ. Other situations you may want to offer reflections include when you hear clients express frustration, or when they express reasons to change.</p>
<hr />
<div class="habit-metadata">
<h4>Level: <span style="font-weight:200;">2</span></h4>
<h4>Skills</h4>
<ul class="skillcloud">
<li><a>motivational interviewing</a></li>
<li><a>active listening</a></li>
</ul>
<h4>Tags</h4>
<ul class="tagcloud">
</ul>
<div>
<footer class="page-footer">
<div class="author-image">
<img src="http://localhost:4000/images/bio-photo.jpg" alt="Omar Ganai">
</div><!-- ./author-image -->
<div class="author-content">
<h3 class="author-name" >Written by <span itemprop="author">Omar Ganai</span></h3>
<p class="author-bio">Omar Ganai is the Head of Coaching Success at Habitry</p>
</div><!-- ./author-content -->
<div class="inline-btn">
<a class="btn-social twitter" href="https://twitter.com/intent/tweet?text=Ask%20open-ended%20questions&url=http://localhost:4000/habits/oeqs/&via=" target="_blank"><i class="fa fa-twitter" aria-hidden="true"></i> Share on Twitter</a>
<a class="btn-social facebook" href="https://www.facebook.com/sharer/sharer.php?u=http://localhost:4000/habits/oeqs/" target="_blank"><i class="fa fa-facebook" aria-hidden="true"></i> Share on Facebook</a>
<a class="btn-social google-plus" href="https://plus.google.com/share?url=http://localhost:4000/habits/oeqs/" target="_blank"><i class="fa fa-google-plus" aria-hidden="true"></i> Share on Google+</a>
</div><!-- /.share-this -->
<div class="page-meta">
<p>Updated <time datetime="2016-03-21T08:35:36Z" itemprop="datePublished">March 21, 2016</time></p>
</div><!-- /.page-meta -->
</footer><!-- /.footer -->
<aside>
<hr />
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
*/
/*
var disqus_config = function () {
this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//habitry-source.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript" rel="nofollow">comments powered by Disqus.</a></noscript>
</aside>
</div><!-- /.content -->
</div><!-- /.inner-wrap -->
</article><!-- ./wrap -->
</div><!-- /#main -->
<footer role="contentinfo" id="site-footer">
<nav role="navigation" class="menu bottom-menu">
<ul class="menu-item">
<li><a href="http://localhost:4000" ></a></li>
</ul>
</nav><!-- /.bottom-menu -->
<p class="copyright">© 2016 <a href="http://localhost:4000">Habitry Source</a> powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> + <a href="http://mmistakes.github.io/skinny-bones-jekyll/" rel="nofollow">Skinny Bones</a>.</p>
</footer>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:4000/js/main.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.isotope/2.2.2/isotope.pkgd.min.js"></script>
<script>
$( function() {
// init Isotope
var $grid = $('.grid-items').isotope({
itemSelector: '.grid-item',
layoutMode: 'fitRows'
});
// bind filter on radio button click
$('.filters-button-group').on( 'click', 'input', function() {
var filterValue = $( this ).attr('data-filter');
});
});
</script>
</body>
</html>
| {'content_hash': '47fd1ee19b878ed15dfbfdf1027577f4', 'timestamp': '', 'source': 'github', 'line_count': 239, 'max_line_length': 334, 'avg_line_length': 37.95397489539749, 'alnum_prop': 0.6604563995149377, 'repo_name': 'smledbetter/habitry_source', 'id': 'ec72fd899522dcafe4643050ae00e82e3f655e93', 'size': '9103', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_site/habits/oeqs/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '70643'}, {'name': 'HTML', 'bytes': '358484'}, {'name': 'JavaScript', 'bytes': '30934'}, {'name': 'Ruby', 'bytes': '1653'}]} |
namespace Microsoft.Azure.Management.DataFactory.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The Deflate compression method used on a dataset.
/// </summary>
[Newtonsoft.Json.JsonObject("Deflate")]
public partial class DatasetDeflateCompression : DatasetCompression
{
/// <summary>
/// Initializes a new instance of the DatasetDeflateCompression class.
/// </summary>
public DatasetDeflateCompression()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the DatasetDeflateCompression class.
/// </summary>
/// <param name="additionalProperties">Unmatched properties from the
/// message are deserialized this collection</param>
/// <param name="level">The Deflate compression level. Possible values
/// include: 'Optimal', 'Fastest'</param>
public DatasetDeflateCompression(IDictionary<string, object> additionalProperties = default(IDictionary<string, object>), string level = default(string))
: base(additionalProperties)
{
Level = level;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the Deflate compression level. Possible values
/// include: 'Optimal', 'Fastest'
/// </summary>
[JsonProperty(PropertyName = "level")]
public string Level { get; set; }
}
}
| {'content_hash': '97f1b35feca1e823206691eabe26d1f4', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 161, 'avg_line_length': 34.795918367346935, 'alnum_prop': 0.6193548387096774, 'repo_name': 'pilor/azure-sdk-for-net', 'id': '8daa38fae676dc2bc05a9e7d7f3ca00b55cecf5d', 'size': '2058', 'binary': False, 'copies': '8', 'ref': 'refs/heads/psSdkJson6', 'path': 'src/SDKs/DataFactory/Management.DataFactory/Generated/Models/DatasetDeflateCompression.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '18102'}, {'name': 'C#', 'bytes': '117130489'}, {'name': 'JavaScript', 'bytes': '7875'}, {'name': 'PowerShell', 'bytes': '105037'}, {'name': 'Shell', 'bytes': '31578'}, {'name': 'XSLT', 'bytes': '6114'}]} |
package org.apache.hadoop.hbase.rest;
import java.io.IOException;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.ServerName;
import org.apache.hadoop.hbase.TableNotFoundException;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.MetaScanner;
import org.apache.hadoop.hbase.rest.model.TableInfoModel;
import org.apache.hadoop.hbase.rest.model.TableRegionModel;
@InterfaceAudience.Private
public class RegionsResource extends ResourceBase {
private static final Log LOG = LogFactory.getLog(RegionsResource.class);
static CacheControl cacheControl;
static {
cacheControl = new CacheControl();
cacheControl.setNoCache(true);
cacheControl.setNoTransform(false);
}
TableResource tableResource;
/**
* Constructor
* @param tableResource
* @throws IOException
*/
public RegionsResource(TableResource tableResource) throws IOException {
super();
this.tableResource = tableResource;
}
@GET
@Produces({MIMETYPE_TEXT, MIMETYPE_XML, MIMETYPE_JSON, MIMETYPE_PROTOBUF,
MIMETYPE_PROTOBUF_IETF})
public Response get(final @Context UriInfo uriInfo) {
if (LOG.isDebugEnabled()) {
LOG.debug("GET " + uriInfo.getAbsolutePath());
}
servlet.getMetrics().incrementRequests(1);
try {
TableName tableName = TableName.valueOf(tableResource.getName());
TableInfoModel model = new TableInfoModel(tableName.getNameAsString());
Connection connection = ConnectionFactory.createConnection(servlet.getConfiguration());
Map<HRegionInfo, ServerName> regions = MetaScanner.allTableRegions(connection, tableName);
connection.close();
for (Map.Entry<HRegionInfo,ServerName> e: regions.entrySet()) {
HRegionInfo hri = e.getKey();
ServerName addr = e.getValue();
model.add(
new TableRegionModel(tableName.getNameAsString(), hri.getRegionId(),
hri.getStartKey(), hri.getEndKey(), addr.getHostAndPort()));
}
ResponseBuilder response = Response.ok(model);
response.cacheControl(cacheControl);
servlet.getMetrics().incrementSucessfulGetRequests(1);
return response.build();
} catch (TableNotFoundException e) {
servlet.getMetrics().incrementFailedGetRequests(1);
return Response.status(Response.Status.NOT_FOUND)
.type(MIMETYPE_TEXT).entity("Not found" + CRLF)
.build();
} catch (IOException e) {
servlet.getMetrics().incrementFailedGetRequests(1);
return Response.status(Response.Status.SERVICE_UNAVAILABLE)
.type(MIMETYPE_TEXT).entity("Unavailable" + CRLF)
.build();
}
}
}
| {'content_hash': 'ba496371aeaac8ec7614379958245d48', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 96, 'avg_line_length': 34.967032967032964, 'alnum_prop': 0.7363293526084224, 'repo_name': 'StackVista/hbase', 'id': '001c6b5718ffe99998bef3974e3914b433127d05', 'size': '3990', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'hbase-rest/src/main/java/org/apache/hadoop/hbase/rest/RegionsResource.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '351'}, {'name': 'C', 'bytes': '28617'}, {'name': 'C++', 'bytes': '770077'}, {'name': 'CMake', 'bytes': '10933'}, {'name': 'CSS', 'bytes': '68278'}, {'name': 'HTML', 'bytes': '70900'}, {'name': 'Java', 'bytes': '25236473'}, {'name': 'JavaScript', 'bytes': '2694'}, {'name': 'Makefile', 'bytes': '1409'}, {'name': 'PHP', 'bytes': '413443'}, {'name': 'Perl', 'bytes': '383793'}, {'name': 'Protocol Buffer', 'bytes': '134453'}, {'name': 'Python', 'bytes': '539649'}, {'name': 'Ruby', 'bytes': '504872'}, {'name': 'Shell', 'bytes': '224374'}, {'name': 'Thrift', 'bytes': '39026'}, {'name': 'XSLT', 'bytes': '2892'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>broadleaf</artifactId>
<groupId>org.broadleafcommerce</groupId>
<version>4.0.0-GA</version>
</parent>
<artifactId>core</artifactId>
<packaging>pom</packaging>
<name>BroadleafCommerce Core</name>
<description>BroadleafCommerce Core Mid Level Project</description>
<url>http://www.broadleafcommerce.org</url>
<properties>
<project.uri>${project.baseUri}/../</project.uri>
</properties>
<licenses>
<license>
<name>Apache 2</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
<comments>A business-friendly OSS license</comments>
</license>
</licenses>
<developers>
<developer>
<id>jeff</id>
<name>Jeff Fischer</name>
<email>[email protected]</email>
<organization>Broadleaf Commerce</organization>
<organizationUrl>http://www.broadleafcommerce.org</organizationUrl>
<roles>
<role>cto</role>
<role>architect</role>
<role>developer</role>
</roles>
<timezone>-6</timezone>
</developer>
<developer>
<id>brian</id>
<name>Brian Polster</name>
<email>[email protected]</email>
<organization>Broadleaf Commerce</organization>
<organizationUrl>http://www.broadleafcommerce.org</organizationUrl>
<roles>
<role>president</role>
<role>architect</role>
<role>developer</role>
</roles>
<timezone>-6</timezone>
</developer>
</developers>
<modules>
<module>broadleaf-profile</module>
<module>broadleaf-profile-web</module>
<module>broadleaf-framework</module>
<module>broadleaf-framework-web</module>
</modules>
</project>
| {'content_hash': 'a460d5b3767639ecdfb0fd60ddbb1013', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 201, 'avg_line_length': 38.69491525423729, 'alnum_prop': 0.5900131406044679, 'repo_name': 'cogitoboy/BroadleafCommerce', 'id': '20de1af1dd2a1eb92686ec0cbedd7b69f1c96328', 'size': '2283', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'core/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '104632'}, {'name': 'Groovy', 'bytes': '249879'}, {'name': 'HTML', 'bytes': '98240'}, {'name': 'Java', 'bytes': '10528396'}, {'name': 'JavaScript', 'bytes': '827665'}]} |
LAB-Sample-App
==============
Sample web app that is intended to be used for testing/teaching
The Aim of this project was to access the following points amongst other things:
- Data manipulation
- Basic statistical ability
- Understanding of JavaScript, HTML and CSS
- Ability to use external libraries
Here are the questions this project answers
-------------------------------------------
Create a webpage on that uses to following two libraries to answer the three questions below:
**Question 1:**
Create a webpage that uses the data from the Sample Data URL below and displays the data as a pie chart that shows the total number of medals separated out by country.
**Question 2:**
Create a webpage that uses the data from the Sample Data URL below and displays the data as a bar chart that shows the type of sports based on the number of bronze medals.
**Question 3:**
Using a HTML table, list the type of sports based on total medal count (descending order - highest to lowest total number of medals) for which there was an athlete between the age of 22 and 29 (inclusive). The table should have as columns, Sports Name, Number of Gold Medals, Number of Silver Medals, Number of Bronze Medals and the Total Number of Medals.
**Libraries:**
- Twitter Bootstrap [http://getbootstrap.com](http://getbootstrap.com) (Web Template Tool)
- D3JS [http://d3js.org](http://d3js.org) (Visualization Tool)
**Important Links:**
- Sample Data URL [https://apps.mathbiol.org/sdata](https://apps.mathbiol.org/sdata) | {'content_hash': '839f2e170d5efc8b1afee29f01daf2d8', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 357, 'avg_line_length': 47.53125, 'alnum_prop': 0.7396449704142012, 'repo_name': 'ebadedude/LAB-Sample-App', 'id': '3758573cc5ca6b0aab8929d3359040e22d3acf62', 'size': '1521', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '322'}, {'name': 'JavaScript', 'bytes': '8719'}]} |
// -----------------------------------------------------------------------------
// struct
// -----------------------------------------------------------------------------
struct optics_packed lens_dist_epoch
{
struct slock lock;
size_t n;
double max;
double samples[optics_dist_samples];
};
struct optics_packed lens_dist
{
struct lens_dist_epoch epochs[2];
};
// -----------------------------------------------------------------------------
// impl
// -----------------------------------------------------------------------------
static struct lens *
lens_dist_alloc(struct optics *optics, const char *name)
{
return lens_alloc(optics, optics_dist, sizeof(struct lens_dist), name);
}
static bool
lens_dist_record(struct optics_lens* lens, optics_epoch_t epoch, double value)
{
struct lens_dist *dist_head = lens_sub_ptr(lens->lens, optics_dist);
if (!dist_head) return false;
struct lens_dist_epoch *dist = &dist_head->epochs[epoch];
{
slock_lock(&dist->lock);
size_t i = dist->n;
if (i >= optics_dist_samples)
i = rng_gen_range(rng_global(), 0, dist->n);
if (i < optics_dist_samples)
dist->samples[i] = value;
dist->n++;
if (value > dist->max) dist->max = value;
slock_unlock(&dist->lock);
}
return true;
}
static int lens_dist_value_cmp(const void *lhs, const void *rhs)
{
return *((double *) lhs) - *((double *) rhs);
}
static inline size_t lens_dist_p(size_t percentile, size_t n)
{
return (n * percentile) / 100;
}
static size_t lens_dist_reservoir_len(size_t len)
{
return len > optics_dist_samples ? optics_dist_samples : len;
}
static size_t lens_dist_merge(
double *dst,
const double *lhs, size_t lhs_len,
const double *rhs, size_t rhs_len)
{
size_t dst_len = 0;
const double *to_merge = NULL; size_t to_merge_len = 0;
if (lhs_len >= rhs_len) {
dst_len = lhs_len;
memcpy(dst, lhs, lens_dist_reservoir_len(lhs_len) * sizeof(*lhs));
to_merge = rhs;
to_merge_len = rhs_len;
}
else {
dst_len = rhs_len;
memcpy(dst, rhs, lens_dist_reservoir_len(rhs_len) * sizeof(*rhs));
to_merge = lhs;
to_merge_len = lhs_len;
}
assert(to_merge_len <= dst_len);
if (!to_merge_len) return lens_dist_reservoir_len(dst_len);
// Fill up our reservoir if not already full.
if (dst_len < optics_dist_samples) {
size_t to_copy = optics_dist_samples - dst_len;
if (to_copy > to_merge_len) to_copy = to_merge_len;
memcpy(dst + dst_len, to_merge, to_copy * sizeof(*lhs));
dst_len += to_copy;
to_merge += to_copy;
to_merge_len -= to_copy;
if (!to_merge_len) return dst_len;
}
// We have non-sampled data so use the regular sampling method
if (to_merge_len <= optics_dist_samples) {
for (size_t i = 0; i < to_merge_len; ++i) {
size_t index = rng_gen_range(rng_global(), 0, dst_len);
if (index < optics_dist_samples)
dst[index] = to_merge[i];
dst_len++;
}
}
// We have two sampled set so pick from each set with proportion equal to
// the number of values they represent.
else {
const double rate = (double) to_merge_len / (double) (to_merge_len + dst_len);
for (size_t i = 0; i < optics_dist_samples; ++i) {
if (rng_gen_prob(rng_global(), rate))
dst[i] = to_merge[i];
}
}
return optics_dist_samples;
}
static enum optics_ret
lens_dist_read(struct optics_lens *lens, optics_epoch_t epoch, struct optics_dist *value)
{
struct lens_dist *dist_head = lens_sub_ptr(lens->lens, optics_dist);
if (!dist_head) return optics_err;
struct lens_dist_epoch *dist = &dist_head->epochs[epoch];
size_t samples_len = 0;
double samples[optics_dist_samples];
{
// Since we're not locking the active epoch, we should only contend
// with straglers which can be dealt with by the poller.
if (slock_is_locked(&dist->lock)) return optics_busy;
samples_len = dist->n;
if (value->max < dist->max) value->max = dist->max;
size_t to_copy = lens_dist_reservoir_len(samples_len);
memcpy(samples, dist->samples, to_copy * sizeof(samples[0]));
dist->max = 0;
dist->n = 0;
slock_unlock(&dist->lock);
}
if (!samples_len) return optics_ok;
double result[optics_dist_samples];
size_t result_len = lens_dist_merge(result, samples, samples_len, value->samples, value->n);
memcpy(value->samples, result, optics_dist_samples * sizeof(double));
qsort(result, result_len, sizeof(double), lens_dist_value_cmp);
value->n += samples_len;
value->p50 = result[lens_dist_p(50, result_len)];
value->p90 = result[lens_dist_p(90, result_len)];
value->p99 = result[lens_dist_p(99, result_len)];
return optics_ok;
}
static bool
lens_dist_normalize(
const struct optics_poll *poll, optics_normalize_cb_t cb, void *ctx)
{
bool ret = false;
size_t old;
struct optics_key key = {0};
optics_key_push(&key, poll->key);
old = optics_key_push(&key, "count");
ret = cb(ctx, poll->ts, key.data, lens_rescale(poll, poll->value.dist.n));
optics_key_pop(&key, old);
if (!ret) return false;
old = optics_key_push(&key, "p50");
ret = cb(ctx, poll->ts, key.data, poll->value.dist.p50);
optics_key_pop(&key, old);
if (!ret) return false;
old = optics_key_push(&key, "p90");
ret = cb(ctx, poll->ts, key.data, poll->value.dist.p90);
optics_key_pop(&key, old);
if (!ret) return false;
old = optics_key_push(&key, "p99");
ret = cb(ctx, poll->ts, key.data, poll->value.dist.p99);
optics_key_pop(&key, old);
if (!ret) return false;
old = optics_key_push(&key, "max");
ret = cb(ctx, poll->ts, key.data, poll->value.dist.max);
optics_key_pop(&key, old);
if (!ret) return false;
return true;
}
| {'content_hash': '3707d293e732538a642d751a0c4ff996', 'timestamp': '', 'source': 'github', 'line_count': 215, 'max_line_length': 96, 'avg_line_length': 28.27906976744186, 'alnum_prop': 0.5625, 'repo_name': 'RAttab/optics', 'id': 'd6a7232ea4f52cc2c5cdebac095360ff3de0ab4a', 'size': '6196', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/lens_dist.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '346590'}, {'name': 'C++', 'bytes': '2136'}, {'name': 'CMake', 'bytes': '8606'}, {'name': 'Dockerfile', 'bytes': '1452'}, {'name': 'Shell', 'bytes': '1193'}]} |
> "I came here to chew bubblegum and install Font Awesome 6 - and I'm all out of bubblegum"
[](https://www.npmjs.com/package/@fortawesome/free-brands-svg-icons)
## Installation
```
$ npm i --save @fortawesome/free-brands-svg-icons
```
Or
```
$ yarn add @fortawesome/free-brands-svg-icons
```
## Documentation
Get started [here](https://fontawesome.com/how-to-use/on-the-web/setup/getting-started). Continue your journey [here](https://fontawesome.com/how-to-use/on-the-web/advanced).
Or go straight to the [API documentation](https://fontawesome.com/how-to-use/with-the-api).
## Issues and support
Start with [GitHub issues](https://github.com/FortAwesome/Font-Awesome/issues) and ping us on [Twitter](https://twitter.com/fontawesome) if you need to.
| {'content_hash': 'a87b850b3fc74c88aa41e37d682c6ba6', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 174, 'avg_line_length': 34.16, 'alnum_prop': 0.7365339578454333, 'repo_name': 'victorbrodsky/order-lab', 'id': '595f8763808ce0a466c24375134abbdb6c5ea7b2', 'size': '922', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'orderflex/public/orderassets/AppUserdirectoryBundle/fontawesome/js-packages/@fortawesome/free-brands-svg-icons/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '29'}, {'name': 'C++', 'bytes': '5768'}, {'name': 'CSS', 'bytes': '421734'}, {'name': 'EJS', 'bytes': '1868'}, {'name': 'HTML', 'bytes': '4395237'}, {'name': 'JavaScript', 'bytes': '33901027'}, {'name': 'Less', 'bytes': '160320'}, {'name': 'Makefile', 'bytes': '4438'}, {'name': 'PHP', 'bytes': '19666485'}, {'name': 'Perl', 'bytes': '2570'}, {'name': 'PostScript', 'bytes': '915057'}, {'name': 'Python', 'bytes': '43841'}, {'name': 'Ruby', 'bytes': '5029'}, {'name': 'SCSS', 'bytes': '79869'}, {'name': 'Shell', 'bytes': '113247'}, {'name': 'Stylus', 'bytes': '7850'}, {'name': 'TSQL', 'bytes': '6675'}, {'name': 'Twig', 'bytes': '3845422'}, {'name': 'TypeScript', 'bytes': '50736'}]} |
package org.innovateuk.ifs.publiccontent.security;
import org.innovateuk.ifs.BaseServiceSecurityTest;
import org.innovateuk.ifs.competition.resource.CompetitionCompositeId;
import org.innovateuk.ifs.competition.security.CompetitionLookupStrategy;
import org.innovateuk.ifs.publiccontent.transactional.PublicContentItemService;
import org.innovateuk.ifs.publiccontent.transactional.PublicContentItemServiceImpl;
import org.innovateuk.ifs.user.resource.Role;
import org.junit.Before;
import org.junit.Test;
import java.util.Optional;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.innovateuk.ifs.user.resource.Role.SYSTEM_REGISTRATION_USER;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class PublicContentItemServiceSecurityTest extends BaseServiceSecurityTest<PublicContentItemService> {
private PublicContentItemPermissionRules rules;
private CompetitionLookupStrategy competitionLookupStrategies;
@Before
public void setUp() throws Exception {
rules = getMockPermissionRulesBean(PublicContentItemPermissionRules.class);
competitionLookupStrategies = getMockPermissionEntityLookupStrategiesBean(CompetitionLookupStrategy.class);
initMocks(this);
}
@Override
protected Class<? extends PublicContentItemService> getClassUnderTest() {
return PublicContentItemServiceImpl.class;
}
@Test
public void testFindFilteredItemsByCompetitionId() {
runAsRole(SYSTEM_REGISTRATION_USER, () -> classUnderTest.findFilteredItems(Optional.of(1L), Optional.of("test"), Optional.of(1), 1));
}
@Test
public void testGetByCompetitionId() {
when(competitionLookupStrategies.getCompetitionCompositeId(1L)).thenReturn(CompetitionCompositeId.id(1L));
assertAccessDenied(() -> classUnderTest.byCompetitionId(1L), this::verifyPermissionRules);
}
private void verifyPermissionRules() {
verify(rules).allUsersCanViewPublishedContent(any(), any());
}
private void runAsRole(Role roleType, Runnable serviceCall) {
setLoggedInUser(
newUserResource()
.withRoleGlobal(roleType)
.build());
serviceCall.run();
}
}
| {'content_hash': '70e933f66eda998436d20da1a3b5477e', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 141, 'avg_line_length': 40.74576271186441, 'alnum_prop': 0.7683028286189684, 'repo_name': 'InnovateUKGitHub/innovation-funding-service', 'id': 'b99f6148fbd507d714cafa340f8c9679a90930df', 'size': '2404', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/publiccontent/security/PublicContentItemServiceSecurityTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '1972'}, {'name': 'HTML', 'bytes': '6342985'}, {'name': 'Java', 'bytes': '26591674'}, {'name': 'JavaScript', 'bytes': '269444'}, {'name': 'Python', 'bytes': '58983'}, {'name': 'RobotFramework', 'bytes': '3317394'}, {'name': 'SCSS', 'bytes': '100274'}, {'name': 'Shell', 'bytes': '60248'}]} |
package org.apache.solr.handler.dataimport;
import org.apache.solr.common.SolrException;
import org.apache.solr.core.SolrCore;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.util.SystemIdResolver;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.XMLErrorLogger;
import org.apache.solr.handler.dataimport.config.ConfigNameConstants;
import org.apache.solr.handler.dataimport.config.ConfigParseUtil;
import org.apache.solr.handler.dataimport.config.DIHConfiguration;
import org.apache.solr.handler.dataimport.config.Entity;
import org.apache.solr.handler.dataimport.config.PropertyWriter;
import org.apache.solr.handler.dataimport.config.Script;
import static org.apache.solr.handler.dataimport.DataImportHandlerException.wrapAndThrow;
import static org.apache.solr.handler.dataimport.DataImportHandlerException.SEVERE;
import static org.apache.solr.handler.dataimport.DocBuilder.loadClass;
import static org.apache.solr.handler.dataimport.config.ConfigNameConstants.CLASS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.apache.commons.io.IOUtils;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
/**
* <p> Stores all configuration information for pulling and indexing data. </p>
* <p>
* <b>This API is experimental and subject to change</b>
*
* @since solr 1.3
*/
public class DataImporter {
public enum Status {
IDLE, RUNNING_FULL_DUMP, RUNNING_DELTA_DUMP, JOB_FAILED
}
private static final Logger LOG = LoggerFactory.getLogger(DataImporter.class);
private static final XMLErrorLogger XMLLOG = new XMLErrorLogger(LOG);
private Status status = Status.IDLE;
private DIHConfiguration config;
private Date indexStartTime;
private Properties store = new Properties();
private Map<String, Map<String,String>> requestLevelDataSourceProps = new HashMap<>();
private IndexSchema schema;
public DocBuilder docBuilder;
public DocBuilder.Statistics cumulativeStatistics = new DocBuilder.Statistics();
private SolrCore core;
private Map<String, Object> coreScopeSession = new ConcurrentHashMap<>();
private ReentrantLock importLock = new ReentrantLock();
private boolean isDeltaImportSupported = false;
private final String handlerName;
/**
* Only for testing purposes
*/
DataImporter() {
this.handlerName = "dataimport" ;
}
DataImporter(SolrCore core, String handlerName) {
this.handlerName = handlerName;
this.core = core;
this.schema = core.getLatestSchema();
}
boolean maybeReloadConfiguration(RequestInfo params,
NamedList<?> defaultParams) throws IOException {
if (importLock.tryLock()) {
boolean success = false;
try {
if (null != params.getRequest()) {
if (schema != params.getRequest().getSchema()) {
schema = params.getRequest().getSchema();
}
}
String dataConfigText = params.getDataConfig();
String dataconfigFile = params.getConfigFile();
InputSource is = null;
if(dataConfigText!=null && dataConfigText.length()>0) {
is = new InputSource(new StringReader(dataConfigText));
} else if(dataconfigFile!=null) {
is = new InputSource(core.getResourceLoader().openResource(dataconfigFile));
is.setSystemId(SystemIdResolver.createSystemIdFromResourceName(dataconfigFile));
LOG.info("Loading DIH Configuration: " + dataconfigFile);
}
if(is!=null) {
config = loadDataConfig(is);
success = true;
}
Map<String,Map<String,String>> dsProps = new HashMap<>();
if(defaultParams!=null) {
int position = 0;
while (position < defaultParams.size()) {
if (defaultParams.getName(position) == null) {
break;
}
String name = defaultParams.getName(position);
if (name.equals("datasource")) {
success = true;
NamedList dsConfig = (NamedList) defaultParams.getVal(position);
LOG.info("Getting configuration for Global Datasource...");
Map<String,String> props = new HashMap<>();
for (int i = 0; i < dsConfig.size(); i++) {
props.put(dsConfig.getName(i), dsConfig.getVal(i).toString());
}
LOG.info("Adding properties to datasource: " + props);
dsProps.put((String) dsConfig.get("name"), props);
}
position++;
}
}
requestLevelDataSourceProps = Collections.unmodifiableMap(dsProps);
} catch(IOException ioe) {
throw ioe;
} finally {
importLock.unlock();
}
return success;
} else {
return false;
}
}
public String getHandlerName() {
return handlerName;
}
public IndexSchema getSchema() {
return schema;
}
/**
* Used by tests
*/
public void loadAndInit(String configStr) {
config = loadDataConfig(new InputSource(new StringReader(configStr)));
}
public void loadAndInit(InputSource configFile) {
config = loadDataConfig(configFile);
}
public DIHConfiguration loadDataConfig(InputSource configFile) {
DIHConfiguration dihcfg = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// only enable xinclude, if a a SolrCore and SystemId is present (makes no sense otherwise)
if (core != null && configFile.getSystemId() != null) {
try {
dbf.setXIncludeAware(true);
dbf.setNamespaceAware(true);
} catch( UnsupportedOperationException e ) {
LOG.warn( "XML parser doesn't support XInclude option" );
}
}
DocumentBuilder builder = dbf.newDocumentBuilder();
if (core != null)
builder.setEntityResolver(new SystemIdResolver(core.getResourceLoader()));
builder.setErrorHandler(XMLLOG);
Document document;
try {
document = builder.parse(configFile);
} finally {
// some XML parsers are broken and don't close the byte stream (but they should according to spec)
IOUtils.closeQuietly(configFile.getByteStream());
}
dihcfg = readFromXml(document);
LOG.info("Data Configuration loaded successfully");
} catch (Exception e) {
throw new DataImportHandlerException(SEVERE,
"Data Config problem: " + e.getMessage(), e);
}
for (Entity e : dihcfg.getEntities()) {
if (e.getAllAttributes().containsKey(SqlEntityProcessor.DELTA_QUERY)) {
isDeltaImportSupported = true;
break;
}
}
return dihcfg;
}
public DIHConfiguration readFromXml(Document xmlDocument) {
DIHConfiguration config;
List<Map<String, String >> functions = new ArrayList<>();
Script script = null;
Map<String, Map<String,String>> dataSources = new HashMap<>();
NodeList dataConfigTags = xmlDocument.getElementsByTagName("dataConfig");
if(dataConfigTags == null || dataConfigTags.getLength() == 0) {
throw new DataImportHandlerException(SEVERE, "the root node '<dataConfig>' is missing");
}
Element e = (Element) dataConfigTags.item(0);
List<Element> documentTags = ConfigParseUtil.getChildNodes(e, "document");
if (documentTags.isEmpty()) {
throw new DataImportHandlerException(SEVERE, "DataImportHandler " +
"configuration file must have one <document> node.");
}
List<Element> scriptTags = ConfigParseUtil.getChildNodes(e, ConfigNameConstants.SCRIPT);
if (!scriptTags.isEmpty()) {
script = new Script(scriptTags.get(0));
}
// Add the provided evaluators
List<Element> functionTags = ConfigParseUtil.getChildNodes(e, ConfigNameConstants.FUNCTION);
if (!functionTags.isEmpty()) {
for (Element element : functionTags) {
String func = ConfigParseUtil.getStringAttribute(element, NAME, null);
String clz = ConfigParseUtil.getStringAttribute(element, ConfigNameConstants.CLASS, null);
if (func == null || clz == null){
throw new DataImportHandlerException(
SEVERE,
"<function> must have a 'name' and 'class' attributes");
} else {
functions.add(ConfigParseUtil.getAllAttributes(element));
}
}
}
List<Element> dataSourceTags = ConfigParseUtil.getChildNodes(e, ConfigNameConstants.DATA_SRC);
if (!dataSourceTags.isEmpty()) {
for (Element element : dataSourceTags) {
Map<String,String> p = new HashMap<>();
HashMap<String, String> attrs = ConfigParseUtil.getAllAttributes(element);
for (Map.Entry<String, String> entry : attrs.entrySet()) {
p.put(entry.getKey(), entry.getValue());
}
dataSources.put(p.get("name"), p);
}
}
if(dataSources.get(null) == null){
for (Map<String,String> properties : dataSources.values()) {
dataSources.put(null,properties);
break;
}
}
PropertyWriter pw = null;
List<Element> propertyWriterTags = ConfigParseUtil.getChildNodes(e, ConfigNameConstants.PROPERTY_WRITER);
if (propertyWriterTags.isEmpty()) {
boolean zookeeper = false;
if (this.core != null
&& this.core.getCoreDescriptor().getCoreContainer()
.isZooKeeperAware()) {
zookeeper = true;
}
pw = new PropertyWriter(zookeeper ? "ZKPropertiesWriter"
: "SimplePropertiesWriter", Collections.<String,String> emptyMap());
} else if (propertyWriterTags.size() > 1) {
throw new DataImportHandlerException(SEVERE, "Only one "
+ ConfigNameConstants.PROPERTY_WRITER + " can be configured.");
} else {
Element pwElement = propertyWriterTags.get(0);
String type = null;
Map<String,String> params = new HashMap<>();
for (Map.Entry<String,String> entry : ConfigParseUtil.getAllAttributes(
pwElement).entrySet()) {
if (TYPE.equals(entry.getKey())) {
type = entry.getValue();
} else {
params.put(entry.getKey(), entry.getValue());
}
}
if (type == null) {
throw new DataImportHandlerException(SEVERE, "The "
+ ConfigNameConstants.PROPERTY_WRITER + " element must specify "
+ TYPE);
}
pw = new PropertyWriter(type, params);
}
return new DIHConfiguration(documentTags.get(0), this, functions, script, dataSources, pw);
}
@SuppressWarnings("unchecked")
private DIHProperties createPropertyWriter() {
DIHProperties propWriter = null;
PropertyWriter configPw = config.getPropertyWriter();
try {
Class<DIHProperties> writerClass = DocBuilder.loadClass(configPw.getType(), this.core);
propWriter = writerClass.newInstance();
propWriter.init(this, configPw.getParameters());
} catch (Exception e) {
throw new DataImportHandlerException(DataImportHandlerException.SEVERE, "Unable to PropertyWriter implementation:" + configPw.getType(), e);
}
return propWriter;
}
public DIHConfiguration getConfig() {
return config;
}
Date getIndexStartTime() {
return indexStartTime;
}
void setIndexStartTime(Date indextStartTime) {
this.indexStartTime = indextStartTime;
}
void store(Object key, Object value) {
store.put(key, value);
}
Object retrieve(Object key) {
return store.get(key);
}
public DataSource getDataSourceInstance(Entity key, String name, Context ctx) {
Map<String,String> p = requestLevelDataSourceProps.get(name);
if (p == null)
p = config.getDataSources().get(name);
if (p == null)
p = requestLevelDataSourceProps.get(null);// for default data source
if (p == null)
p = config.getDataSources().get(null);
if (p == null)
throw new DataImportHandlerException(SEVERE,
"No dataSource :" + name + " available for entity :" + key.getName());
String type = p.get(TYPE);
DataSource dataSrc = null;
if (type == null) {
dataSrc = new JdbcDataSource();
} else {
try {
dataSrc = (DataSource) DocBuilder.loadClass(type, getCore()).newInstance();
} catch (Exception e) {
wrapAndThrow(SEVERE, e, "Invalid type for data source: " + type);
}
}
try {
Properties copyProps = new Properties();
copyProps.putAll(p);
Map<String, Object> map = ctx.getRequestParameters();
if (map.containsKey("rows")) {
int rows = Integer.parseInt((String) map.get("rows"));
if (map.containsKey("start")) {
rows += Integer.parseInt((String) map.get("start"));
}
copyProps.setProperty("maxRows", String.valueOf(rows));
}
dataSrc.init(ctx, copyProps);
} catch (Exception e) {
wrapAndThrow(SEVERE, e, "Failed to initialize DataSource: " + key.getDataSourceName());
}
return dataSrc;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public boolean isBusy() {
return importLock.isLocked();
}
public void doFullImport(DIHWriter writer, RequestInfo requestParams) {
LOG.info("Starting Full Import");
setStatus(Status.RUNNING_FULL_DUMP);
try {
DIHProperties dihPropWriter = createPropertyWriter();
setIndexStartTime(dihPropWriter.getCurrentTimestamp());
docBuilder = new DocBuilder(this, writer, dihPropWriter, requestParams);
checkWritablePersistFile(writer, dihPropWriter);
docBuilder.execute();
if (!requestParams.isDebug())
cumulativeStatistics.add(docBuilder.importStatistics);
} catch (Exception e) {
SolrException.log(LOG, "Full Import failed", e);
docBuilder.handleError("Full Import failed", e);
} finally {
setStatus(Status.IDLE);
DocBuilder.INSTANCE.set(null);
}
}
private void checkWritablePersistFile(DIHWriter writer, DIHProperties dihPropWriter) {
if (isDeltaImportSupported && !dihPropWriter.isWritable()) {
throw new DataImportHandlerException(SEVERE,
"Properties is not writable. Delta imports are supported by data config but will not work.");
}
}
public void doDeltaImport(DIHWriter writer, RequestInfo requestParams) {
LOG.info("Starting Delta Import");
setStatus(Status.RUNNING_DELTA_DUMP);
try {
DIHProperties dihPropWriter = createPropertyWriter();
setIndexStartTime(dihPropWriter.getCurrentTimestamp());
docBuilder = new DocBuilder(this, writer, dihPropWriter, requestParams);
checkWritablePersistFile(writer, dihPropWriter);
docBuilder.execute();
if (!requestParams.isDebug())
cumulativeStatistics.add(docBuilder.importStatistics);
} catch (Exception e) {
LOG.error("Delta Import Failed", e);
docBuilder.handleError("Delta Import Failed", e);
} finally {
setStatus(Status.IDLE);
DocBuilder.INSTANCE.set(null);
}
}
public void runAsync(final RequestInfo reqParams, final DIHWriter sw) {
new Thread() {
@Override
public void run() {
runCmd(reqParams, sw);
}
}.start();
}
void runCmd(RequestInfo reqParams, DIHWriter sw) {
String command = reqParams.getCommand();
if (command.equals(ABORT_CMD)) {
if (docBuilder != null) {
docBuilder.abort();
}
return;
}
if (!importLock.tryLock()){
LOG.warn("Import command failed . another import is running");
return;
}
try {
if (FULL_IMPORT_CMD.equals(command) || IMPORT_CMD.equals(command)) {
doFullImport(sw, reqParams);
} else if (command.equals(DELTA_IMPORT_CMD)) {
doDeltaImport(sw, reqParams);
}
} finally {
importLock.unlock();
}
}
@SuppressWarnings("unchecked")
Map<String, String> getStatusMessages() {
//this map object is a Collections.synchronizedMap(new LinkedHashMap()). if we
// synchronize on the object it must be safe to iterate through the map
Map statusMessages = (Map) retrieve(STATUS_MSGS);
Map<String, String> result = new LinkedHashMap<>();
if (statusMessages != null) {
synchronized (statusMessages) {
for (Object o : statusMessages.entrySet()) {
Map.Entry e = (Map.Entry) o;
//the toString is taken because some of the Objects create the data lazily when toString() is called
result.put((String) e.getKey(), e.getValue().toString());
}
}
}
return result;
}
public DocBuilder getDocBuilder() {
return docBuilder;
}
public DocBuilder getDocBuilder(DIHWriter writer, RequestInfo requestParams) {
DIHProperties dihPropWriter = createPropertyWriter();
return new DocBuilder(this, writer, dihPropWriter, requestParams);
}
Map<String, Evaluator> getEvaluators() {
return getEvaluators(config.getFunctions());
}
/**
* used by tests.
*/
Map<String, Evaluator> getEvaluators(List<Map<String,String>> fn) {
Map<String, Evaluator> evaluators = new HashMap<>();
evaluators.put(Evaluator.DATE_FORMAT_EVALUATOR, new DateFormatEvaluator());
evaluators.put(Evaluator.SQL_ESCAPE_EVALUATOR, new SqlEscapingEvaluator());
evaluators.put(Evaluator.URL_ENCODE_EVALUATOR, new UrlEvaluator());
evaluators.put(Evaluator.ESCAPE_SOLR_QUERY_CHARS, new SolrQueryEscapingEvaluator());
SolrCore core = docBuilder == null ? null : docBuilder.dataImporter.getCore();
for (Map<String, String> map : fn) {
try {
evaluators.put(map.get(NAME), (Evaluator) loadClass(map.get(CLASS), core).newInstance());
} catch (Exception e) {
wrapAndThrow(SEVERE, e, "Unable to instantiate evaluator: " + map.get(CLASS));
}
}
return evaluators;
}
static final ThreadLocal<AtomicLong> QUERY_COUNT = new ThreadLocal<AtomicLong>() {
@Override
protected AtomicLong initialValue() {
return new AtomicLong();
}
};
static final class MSG {
public static final String NO_CONFIG_FOUND = "Configuration not found";
public static final String NO_INIT = "DataImportHandler started. Not Initialized. No commands can be run";
public static final String INVALID_CONFIG = "FATAL: Could not create importer. DataImporter config invalid";
public static final String LOAD_EXP = "Exception while loading DataImporter";
public static final String JMX_DESC = "Manage data import from databases to Solr";
public static final String CMD_RUNNING = "A command is still running...";
public static final String DEBUG_NOT_ENABLED = "Debug not enabled. Add a tag <str name=\"enableDebug\">true</str> in solrconfig.xml";
public static final String CONFIG_RELOADED = "Configuration Re-loaded sucessfully";
public static final String CONFIG_NOT_RELOADED = "Configuration NOT Re-loaded...Data Importer is busy.";
public static final String TOTAL_DOC_PROCESSED = "Total Documents Processed";
public static final String TOTAL_FAILED_DOCS = "Total Documents Failed";
public static final String TOTAL_QUERIES_EXECUTED = "Total Requests made to DataSource";
public static final String TOTAL_ROWS_EXECUTED = "Total Rows Fetched";
public static final String TOTAL_DOCS_DELETED = "Total Documents Deleted";
public static final String TOTAL_DOCS_SKIPPED = "Total Documents Skipped";
}
public SolrCore getCore() {
return core;
}
void putToCoreScopeSession(String key, Object val) {
coreScopeSession.put(key, val);
}
Object getFromCoreScopeSession(String key) {
return coreScopeSession.get(key);
}
public static final String COLUMN = "column";
public static final String TYPE = "type";
public static final String DATA_SRC = "dataSource";
public static final String MULTI_VALUED = "multiValued";
public static final String NAME = "name";
public static final String STATUS_MSGS = "status-messages";
public static final String FULL_IMPORT_CMD = "full-import";
public static final String IMPORT_CMD = "import";
public static final String DELTA_IMPORT_CMD = "delta-import";
public static final String ABORT_CMD = "abort";
public static final String DEBUG_MODE = "debug";
public static final String RELOAD_CONF_CMD = "reload-config";
public static final String SHOW_CONF_CMD = "show-config";
}
| {'content_hash': 'ca6a44ad4b1d82d4f61fa7ab5b3ea408', 'timestamp': '', 'source': 'github', 'line_count': 604, 'max_line_length': 146, 'avg_line_length': 34.87417218543046, 'alnum_prop': 0.6710026585643752, 'repo_name': 'q474818917/solr-5.2.0', 'id': '52ca97790333d75666731415152f004417a7e8b0', 'size': '21865', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'solr/contrib/dataimporthandler/src/java/org/apache/solr/handler/dataimport/DataImporter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '291'}, {'name': 'Batchfile', 'bytes': '53286'}, {'name': 'C++', 'bytes': '26754'}, {'name': 'CSS', 'bytes': '231259'}, {'name': 'GAP', 'bytes': '22114'}, {'name': 'Gnuplot', 'bytes': '4888'}, {'name': 'HTML', 'bytes': '1743012'}, {'name': 'Java', 'bytes': '43573203'}, {'name': 'JavaScript', 'bytes': '1174114'}, {'name': 'Lex', 'bytes': '216872'}, {'name': 'Mathematica', 'bytes': '192'}, {'name': 'Perl', 'bytes': '95225'}, {'name': 'Python', 'bytes': '313663'}, {'name': 'Shell', 'bytes': '167334'}, {'name': 'XSLT', 'bytes': '192968'}]} |
package org.postgresql.test.jdbc2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.postgresql.PGConnection;
import org.postgresql.copy.CopyIn;
import org.postgresql.copy.CopyManager;
import org.postgresql.copy.CopyOut;
import org.postgresql.copy.PGCopyOutputStream;
import org.postgresql.core.ServerVersion;
import org.postgresql.test.TestUtil;
import org.postgresql.util.ByteBufferByteStreamWriter;
import org.postgresql.util.PSQLState;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.nio.ByteBuffer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author [email protected]
*/
public class CopyTest {
private Connection con;
private CopyManager copyAPI;
private String copyParams;
// 0's required to match DB output for numeric(5,2)
private String[] origData =
{"First Row\t1\t1.10\n",
"Second Row\t2\t-22.20\n",
"\\N\t\\N\t\\N\n",
"\t4\t444.40\n"};
private int dataRows = origData.length;
private byte[] getData(String[] origData) {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(buf);
for (String anOrigData : origData) {
ps.print(anOrigData);
}
return buf.toByteArray();
}
@Before
public void setUp() throws Exception {
con = TestUtil.openDB();
TestUtil.createTempTable(con, "copytest", "stringvalue text, intvalue int, numvalue numeric(5,2)");
copyAPI = ((PGConnection) con).getCopyAPI();
if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) {
copyParams = "(FORMAT CSV, HEADER false)";
} else {
copyParams = "CSV";
}
}
@After
public void tearDown() throws Exception {
TestUtil.closeDB(con);
// one of the tests will render the existing connection broken,
// so we need to drop the table on a fresh one.
con = TestUtil.openDB();
try {
TestUtil.dropTable(con, "copytest");
} finally {
con.close();
}
}
private int getCount() throws SQLException {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT count(*) FROM copytest");
rs.next();
int result = rs.getInt(1);
rs.close();
return result;
}
@Test
public void testCopyInByRow() throws SQLException {
String sql = "COPY copytest FROM STDIN";
CopyIn cp = copyAPI.copyIn(sql);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
cp.writeToCopy(buf, 0, buf.length);
}
long count1 = cp.endCopy();
long count2 = cp.getHandledRowCount();
assertEquals(dataRows, count1);
assertEquals(dataRows, count2);
try {
cp.cancelCopy();
} catch (SQLException se) { // should fail with obsolete operation
if (!PSQLState.OBJECT_NOT_IN_STATE.getState().equals(se.getSQLState())) {
fail("should have thrown object not in state exception.");
}
}
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInAsOutputStream() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
OutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.close();
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInAsOutputStreamClosesAfterEndCopy() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
PGCopyOutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
try {
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.endCopy();
} finally {
os.close();
}
assertFalse(os.isActive());
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInAsOutputStreamFailsOnFlushAfterEndCopy() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
PGCopyOutputStream os = new PGCopyOutputStream((PGConnection) con, sql, 1000);
try {
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
os.write(buf);
}
os.endCopy();
} finally {
os.close();
}
try {
os.flush();
fail("should have failed flushing an inactive copy stream.");
} catch (IOException e) {
if (!e.toString().contains("This copy stream is closed.")) {
fail("has failed not due to checkClosed(): " + e);
}
}
}
@Test
public void testCopyInFromInputStream() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
copyAPI.copyIn(sql, new ByteArrayInputStream(getData(origData)), 3);
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInFromStreamFail() throws SQLException {
String sql = "COPY copytest FROM STDIN";
try {
copyAPI.copyIn(sql, new InputStream() {
public int read() {
throw new RuntimeException("COPYTEST");
}
}, 3);
} catch (Exception e) {
if (!e.toString().contains("COPYTEST")) {
fail("should have failed trying to read from our bogus stream.");
}
}
int rowCount = getCount();
assertEquals(0, rowCount);
}
@Test
public void testCopyInFromReader() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
copyAPI.copyIn(sql, new StringReader(new String(getData(origData))), 3);
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
@Test
public void testCopyInFromByteStreamWriter() throws SQLException, IOException {
String sql = "COPY copytest FROM STDIN";
copyAPI.copyIn(sql, new ByteBufferByteStreamWriter(ByteBuffer.wrap(getData(origData))));
int rowCount = getCount();
assertEquals(dataRows, rowCount);
}
/**
* Tests writing to a COPY ... FROM STDIN using both the standard OutputStream API
* write(byte[]) and the driver specific write(ByteStreamWriter) API interleaved.
*/
@Test
public void testCopyMultiApi() throws SQLException, IOException {
TestUtil.execute("CREATE TABLE pg_temp.copy_api_test (data text)", con);
String sql = "COPY pg_temp.copy_api_test (data) FROM STDIN";
PGCopyOutputStream out = new PGCopyOutputStream(copyAPI.copyIn(sql));
try {
out.write("a".getBytes());
out.writeToCopy(new ByteBufferByteStreamWriter(ByteBuffer.wrap("b".getBytes())));
out.write("c".getBytes());
out.writeToCopy(new ByteBufferByteStreamWriter(ByteBuffer.wrap("d".getBytes())));
out.write("\n".getBytes());
} finally {
out.close();
}
String data = TestUtil.queryForString(con, "SELECT data FROM pg_temp.copy_api_test");
assertEquals("The writes to the COPY should be in order", "abcd", data);
}
@Test
public void testSkipping() {
String sql = "COPY copytest FROM STDIN";
String at = "init";
int rowCount = -1;
int skip = 0;
int skipChar = 1;
try {
while (skipChar > 0) {
at = "buffering";
InputStream ins = new ByteArrayInputStream(getData(origData));
at = "skipping";
ins.skip(skip++);
skipChar = ins.read();
at = "copying";
copyAPI.copyIn(sql, ins, 3);
at = "using connection after writing copy";
rowCount = getCount();
}
} catch (Exception e) {
if (!(skipChar == '\t')) {
// error expected when field separator consumed
fail("testSkipping at " + at + " round " + skip + ": " + e.toString());
}
}
assertEquals(dataRows * (skip - 1), rowCount);
}
@Test
public void testCopyOutByRow() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
String sql = "COPY copytest TO STDOUT";
CopyOut cp = copyAPI.copyOut(sql);
int count = 0;
byte[] buf;
while ((buf = cp.readFromCopy()) != null) {
count++;
}
assertEquals(false, cp.isActive());
assertEquals(dataRows, count);
long rowCount = cp.getHandledRowCount();
assertEquals(dataRows, rowCount);
assertEquals(dataRows, getCount());
}
@Test
public void testCopyOut() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
String sql = "COPY copytest TO STDOUT";
ByteArrayOutputStream copydata = new ByteArrayOutputStream();
copyAPI.copyOut(sql, copydata);
assertEquals(dataRows, getCount());
// deep comparison of data written and read
byte[] copybytes = copydata.toByteArray();
assertNotNull(copybytes);
for (int i = 0, l = 0; i < origData.length; i++) {
byte[] origBytes = origData[i].getBytes();
assertTrue("Copy is shorter than original", copybytes.length >= l + origBytes.length);
for (int j = 0; j < origBytes.length; j++, l++) {
assertEquals("content changed at byte#" + j + ": " + origBytes[j] + copybytes[l],
origBytes[j], copybytes[l]);
}
}
}
@Test
public void testNonCopyOut() throws SQLException, IOException {
String sql = "SELECT 1";
try {
copyAPI.copyOut(sql, new ByteArrayOutputStream());
fail("Can't use a non-copy query.");
} catch (SQLException sqle) {
}
// Ensure connection still works.
assertEquals(0, getCount());
}
@Test
public void testNonCopyIn() throws SQLException, IOException {
String sql = "SELECT 1";
try {
copyAPI.copyIn(sql, new ByteArrayInputStream(new byte[0]));
fail("Can't use a non-copy query.");
} catch (SQLException sqle) {
}
// Ensure connection still works.
assertEquals(0, getCount());
}
@Test
public void testStatementCopyIn() throws SQLException {
Statement stmt = con.createStatement();
try {
stmt.execute("COPY copytest FROM STDIN");
fail("Should have failed because copy doesn't work from a Statement.");
} catch (SQLException sqle) {
}
stmt.close();
assertEquals(0, getCount());
}
@Test
public void testStatementCopyOut() throws SQLException {
testCopyInByRow(); // ensure we have some data.
Statement stmt = con.createStatement();
try {
stmt.execute("COPY copytest TO STDOUT");
fail("Should have failed because copy doesn't work from a Statement.");
} catch (SQLException sqle) {
}
stmt.close();
assertEquals(dataRows, getCount());
}
@Test
public void testCopyQuery() throws SQLException, IOException {
testCopyInByRow(); // ensure we have some data.
long count = copyAPI.copyOut("COPY (SELECT generate_series(1,1000)) TO STDOUT",
new ByteArrayOutputStream());
assertEquals(1000, count);
}
@Test
public void testCopyRollback() throws SQLException {
con.setAutoCommit(false);
testCopyInByRow();
con.rollback();
assertEquals(0, getCount());
}
@Test
public void testChangeDateStyle() throws SQLException {
try {
con.setAutoCommit(false);
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
CopyManager manager = con.unwrap(PGConnection.class).getCopyAPI();
Statement stmt = con.createStatement();
stmt.execute("SET DateStyle = 'ISO, DMY'");
// I expect an SQLException
String sql = "COPY copytest FROM STDIN with xxx " + copyParams;
CopyIn cp = manager.copyIn(sql);
for (String anOrigData : origData) {
byte[] buf = anOrigData.getBytes();
cp.writeToCopy(buf, 0, buf.length);
}
long count1 = cp.endCopy();
long count2 = cp.getHandledRowCount();
con.commit();
} catch (SQLException ex) {
// the with xxx is a syntax error which shoud return a state of 42601
// if this fails the 'S' command is not being handled in the copy manager query handler
assertEquals("42601", ex.getSQLState());
con.rollback();
}
}
@Test
public void testLockReleaseOnCancelFailure() throws SQLException, InterruptedException {
if (!TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) {
// pg_backend_pid() requires PostgreSQL 8.4+
return;
}
// This is a fairly complex test because it is testing a
// deadlock that only occurs when the connection to postgres
// is broken during a copy operation. We'll start a copy
// operation, use pg_terminate_backend to rudely break it,
// and then cancel. The test passes if a subsequent operation
// on the Connection object fails to deadlock.
con.setAutoCommit(false);
CopyManager manager = con.unwrap(PGConnection.class).getCopyAPI();
CopyIn copyIn = manager.copyIn("COPY copytest FROM STDIN with " + copyParams);
TestUtil.terminateBackend(con);
try {
byte[] bunchOfNulls = ",,\n".getBytes();
while (true) {
copyIn.writeToCopy(bunchOfNulls, 0, bunchOfNulls.length);
}
} catch (SQLException e) {
acceptIOCause(e);
} finally {
if (copyIn.isActive()) {
try {
copyIn.cancelCopy();
fail("cancelCopy should have thrown an exception");
} catch (SQLException e) {
acceptIOCause(e);
}
}
}
// Now we'll execute rollback on another thread so that if the
// deadlock _does_ occur the testcase doesn't just hange forever.
Rollback rollback = new Rollback(con);
rollback.start();
rollback.join(1000);
if (rollback.isAlive()) {
fail("rollback did not terminate");
}
SQLException rollbackException = rollback.exception();
if (rollbackException == null) {
fail("rollback should have thrown an exception");
}
assertTrue( rollbackException instanceof SQLException);
}
private static class Rollback extends Thread {
private final Connection con;
private SQLException rollbackException;
Rollback(Connection con) {
setName("Asynchronous rollback");
setDaemon(true);
this.con = con;
}
@Override
public void run() {
try {
con.rollback();
} catch (SQLException e) {
rollbackException = e;
}
}
public SQLException exception() {
return rollbackException;
}
}
private void acceptIOCause(SQLException e) throws SQLException {
if (!(e.getCause() instanceof IOException)) {
throw e;
}
}
}
| {'content_hash': '418b5b859fb93a82a9b1fb46f91c1a90', 'timestamp': '', 'source': 'github', 'line_count': 492, 'max_line_length': 103, 'avg_line_length': 30.28252032520325, 'alnum_prop': 0.6550775219813411, 'repo_name': 'davecramer/pgjdbc', 'id': '4c89211f231221a0671d2c6204f76e14cfe76f72', 'size': '15030', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'pgjdbc/src/test/java/org/postgresql/test/jdbc2/CopyTest.java', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Dockerfile', 'bytes': '2555'}, {'name': 'Groovy', 'bytes': '17825'}, {'name': 'Java', 'bytes': '3767991'}, {'name': 'Kotlin', 'bytes': '60360'}, {'name': 'Makefile', 'bytes': '3071'}, {'name': 'Perl', 'bytes': '2844'}, {'name': 'Scala', 'bytes': '2743'}, {'name': 'Shell', 'bytes': '25245'}, {'name': 'Smarty', 'bytes': '5064'}]} |
/**
* Course 25
* React Native API模块之NetInfo(网络信息)使用详解
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
NetInfo,
} from 'react-native';
import Util from '../utils';
import ToastIOS from 'react-native-sk-toast';
export default class extends Component{
constructor(props){
super(props);
this.state = {
isConnected: null,
connectionInfo:null,
};
}
componentDidMount() {
NetInfo.isConnected.addEventListener(
'change',
this._handleConnectivityChange
);
//检测网络是否连接
NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({isConnected}); }
);
//检测网络连接信息
NetInfo.fetch().done(
(connectionInfo) => { this.setState({connectionInfo}); }
);
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener(
'change',
this._handleConnectivityChange
);
}
_handleConnectivityChange(isConnected) {
ToastIOS.bottom((isConnected ? 'online' : 'offline'));
}
render() {
return (
<View style={styles.rootViewContainer}>
<Text style={styles.title}>
当前的网络状态
</Text>
<Text style={styles.value}>
{this.state.isConnected ? '网络在线' : '离线'}
</Text>
<Text style={styles.title}>
当前网络连接类型
</Text>
<Text style={styles.value}>
{this.state.connectionInfo}
</Text>
{/* 只适合Android平台,用来判断当前连接的网络是否需要收费 */}
<Text style={styles.title}>
当前连接网络是否计费
</Text>
<Text style={styles.value}>
{NetInfo.isConnectionExpensive === true ? '需要计费' : '不要'}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
rootViewContainer:{
marginTop : 70,
},
title: {
fontSize: 16,
textAlign: 'left',
margin: 10,
backgroundColor: '#F5FCFF',
},
value: {
fontSize: 13,
textAlign: 'left',
marginLeft: 10,
marginRight: 10,
color: '#FF33FF',
},
});
| {'content_hash': 'd89d35405eb3c8a79c7aa1d63b20d519', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 66, 'avg_line_length': 21.221052631578946, 'alnum_prop': 0.5768849206349206, 'repo_name': 'leechuanjun/TLReactNativeProject', 'id': '724786b1e1a3b2a852cc951750f021a54327347d', 'size': '2190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'view/apimodule/course25.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '559'}, {'name': 'Java', 'bytes': '1054'}, {'name': 'JavaScript', 'bytes': '122590'}, {'name': 'Objective-C', 'bytes': '13419'}, {'name': 'Python', 'bytes': '1664'}]} |
package com.google.api.ads.adwords.jaxws.v201409.cm;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Applies the list of mutate operations.
*
* @param operations The operations to apply.
* @return The modified list of Budgets, returned in the same order as <code>operations</code>.
* @throws ApiException
*
*
* <p>Java class for mutate element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="mutate">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="operations" type="{https://adwords.google.com/api/adwords/cm/v201409}BudgetOperation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"operations"
})
@XmlRootElement(name = "mutate")
public class BudgetServiceInterfacemutate {
protected List<BudgetOperation> operations;
/**
* Gets the value of the operations property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the operations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getOperations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link BudgetOperation }
*
*
*/
public List<BudgetOperation> getOperations() {
if (operations == null) {
operations = new ArrayList<BudgetOperation>();
}
return this.operations;
}
}
| {'content_hash': '12351998d8483a11e9371a467e349b62', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 154, 'avg_line_length': 29.0126582278481, 'alnum_prop': 0.6291448516579407, 'repo_name': 'nafae/developer', 'id': 'e05548a0d4c66abb7e57dc264a2873f94573715e', 'size': '2292', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201409/cm/BudgetServiceInterfacemutate.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '127846798'}, {'name': 'Perl', 'bytes': '28418'}]} |
var fetch = require('./fetch'),
apiCache = require('./apiCache'),
config = require('./config'),
Q = require('q');
module.exports = new Api();
function Api() {
this.local = null;
}
Api.prototype.load = function() {
var deferred = Q.defer();
// return local copy
if(this.local) {
deferred.resolve(this.local);
} else {
if((this.local = apiCache.load())) {
// if we have a cached version, return it
deferred.resolve(this.local);
} else {
console.log('No cached API'.red);
console.log('Fetching API...'.yellow);
// otherwise, fetch new copy
fetch.json(config.API_URL + '?key=' + config.API_KEY)
.then(function(api) {
this.local = api;
apiCache.cache(api);
deferred.resolve(api);
});
}
}
return deferred.promise;
};
| {'content_hash': '3c2e26b891be6cec899a76a21bb28089', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 59, 'avg_line_length': 22.45945945945946, 'alnum_prop': 0.5776173285198556, 'repo_name': 'danprince/typefetch', 'id': '86c6dc843c7c8e66c512f2ee9e6b956160ecd59f', 'size': '831', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'lib/api.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '1283'}]} |
title: Samantha Vilkins
summary: Communications and Engagement Officer (ANU), PhD candidate
categories:
- mac
- researcher
- student
---
### Who are you, and what do you do?
I wear a lot of hats. That's an idiom, not my job. I'm a PhD candidate in science communication and also the Communications and Engagement Officer at the [Australian National Centre for the Public Awareness of Science](http://cpas.anu.edu.au/about-us/people/sam-vilkins "Samantha's profile on ANU.") at The Australian National University, where I also tutor, write, et cetera. I also do freelance [photography/design/writing](http://vilkins.online/ "Samantha's website.") where I can. I just finished up working at [Trove at the National Library of Australia](https://trove.nla.gov.au/ "An Australian information resource from the National Library.") and I've [got the mug to prove it](https://twitter.com/samvilkins/status/968329704594968576 "Samantha's Trove mug tweet.").
### What hardware do you use?
I exclusively use [Pilot G2 0.38 pens][g2.2]. They are a great solution between "using shit pens" and "caring way too much about pens". I use the pens in notebooks from Octaevo. I'd prefer to type notes into my phone but I end up in meetings with people much older than me a lot and the youngest person in the room constantly tapping at their phone isn't a great look. I also think better on paper.
My laptop is a late 2013 [MacBook Pro][macbook-pro] with 16GB of RAM. I'm the sort of monster who cracks open [Photoshop][] to resize a screenshot on the bus, so I'm not sure what I'd do without it.
I've got a fancy [Rain Design mStand][mstand] alongside a [fuzzy Acer monitor at home][k242hqlcbid], and a glorious [Dell UltraSharp][u2715h] alongside a pile of old books as a stand at work, because I'm all about balance.
I own two WASD mechanical keyboards, [the same model][vp3-61-key]. One's [Cherry MX clears all-white with mint legends and a mint Enter key that reads 'GO!'](https://twitter.com/samvilkins/status/978758348538503169 "Samantha's tweet showing her mechanical keyboard with green keys."), and the other is [Cherry MX browns, greyscale with bright yellow keys spelling out my name](https://twitter.com/samvilkins/status/885374232384765952 "Samantha's tweet showing her mechanical keyboard with brown keys."). I adore them.
My camera's a [Canon 60D][eos-60d] and my go-to lenses are my [24mm][ef-s-24mm-f2.8-stm] / [50mm][ef-50mm-f1.4-usm] / [85mm][ef-85mm-f1.8-usm] primes.
I bought a second-hand rose gold "women's" [Moto360 v2][moto-360-2nd-generation] and wear it every day. It can do almost nothing --- it's as if I tore out the notification light of my [Pixel 2][pixel-2] and strung it round my wrist --- but it looks good, starts conversations, alerts me to things while it's rude to look at my phone or it's not on my person, and most importantly, I can set the background to my favourite green and set the text to spell out the time in letters which takes me longer to process than a digital face and thus entertains me to no end.
I care so little about audio quality that a few years ago I bought 4 packs of LG G2 headphones off [eBay][] and keep a pair in various bags and desks. I also just bought a pair of [white BlueAnt wireless headphones][pump-air] because my new phone lacks a headphone jack and I hate how much I love them.
I've got a [Blue Yeti USB microphone][yeti] for when I inevitably start a podcast.
I was recently fitted for new multifocal glasses, because we all have to face our ageing mortal bodies in our own ways.
I use one ModernCoup bag for every occasion. I love it to death even as it's destroying my back.
I've got Aglaonema commutatum, Spathiphyllum petite and Parlour palm plants from Plants in a Box and a Pothos plant from The Name Is Planted at my desk in a long con I've got to make me want to come to work each day to check on them.
I've got a plush office chair I stole (okay, they were giving it away) from my university, wheeled a quarter-way across campus in the rain, and had to re-construct my desk around as my room is too small to fit it otherwise. It was worth it.
### And what software?
I am constantly gaining and shedding bits of software, either for specific research kicks or life admin --- the latest were [gensim][], [sndpeek][] and [1Password][].
As a baseline, my vital organs are hooked into the Google ecosystem --- 16 separate [Calendars][google-calendar], [Maps][google-maps] multiple times a day, autobackup [Photos][google-photos], [Sheets][google-sheets] abound, [Keep][google-keep] for every thought. Quick thoughts from Keep get regularly sorted out to: reminders/events in Calendar, saved/tagged links in [Pocket][], or drafts/ideas in a folder in [iA Writer][ia-writer]. The iA Writer folder is in my [Google Drive][google-drive] so it's on my phone, as well.
I use [Papers][] for research and references, but only because it actively frustrates me the least out of the options.
I use the [macOS][] [Mail][] app to deal with my 4+ regular email addresses and I would love to upgrade to something nicer but absolutely everything else has failed me, so here we still are.
I use [Tweetbot][] because [TweetDeck][] crossed me one too many times.
I use [Spotify][] lazily and [Pocket Casts][pocket-casts] earnestly. I keep a [Shazam][] widget on my phone homepage so I can use it inconspicuously when around cool youth. My other widgets are my Outlook calendar, Google calendar, and Google Keep. The [BOM Weather app][bom-weather-android] is crucial.
I was gifted a copy of Adobe Photoshop CS2 when I was eleven years old and doubt I've closed it since then. I use [Lightroom][]/[Premiere][]/[Illustrator][]/[InDesign][] when it comes to it, all on a [CC][creative-suite] subscription.
Any and all programming I do is extremely amateur hour and usually in [Notepad++][notepad-plusplus] or [TextWrangler][]. I'll dip into [R][] when I have to but I use [Excel][] to within an inch of its life.
I have a rotating [new-font/new-colour-palette][palettab] new tab page, and I'd recommend it.
### What would be your dream setup?
Always more light and less carpet.
[1password]: https://1password.com "Password management software for Mac OS X."
[bom-weather-android]: https://play.google.com/store/apps/details?id=au.gov.bom.metview "A weather app."
[creative-suite]: https://www.adobe.com/creativecloud.html "A collection of design tools."
[ebay]: https://www.ebay.com/ "An auction service."
[ef-50mm-f1.4-usm]: https://www.usa.canon.com/cusa/support/consumer/eos_slr_camera_systems/lenses/ef_50mm_f_1_4_usm "A lens for SLR cameras."
[ef-85mm-f1.8-usm]: http://usa.canon.com/cusa/consumer/products/cameras/ef_lens_lineup/ef_85mm_f_1_8_usm "A telephoto lens."
[ef-s-24mm-f2.8-stm]: https://www.usa.canon.com/internet/portal/us/home/products/details/lenses/ef/wide-angle/ef-s-24mm-f-2-8-stm "A wide-angle camera lens."
[eos-60d]: http://usa.canon.com/cusa/consumer/products/cameras/slr_cameras/eos_60d "A consumer-level DSLR camera."
[excel]: https://products.office.com/en-us/excel "A spreadsheet application."
[g2.2]: https://www.jetpens.com/Pilot-G2-Original-Gel-Pens/ct/610 "A pen."
[gensim]: https://radimrehurek.com/gensim/ "A Python library for working with semantics."
[google-calendar]: https://en.wikipedia.org/wiki/Google_Calendar "A web-based calendar client."
[google-drive]: https://drive.google.com/ "A cloud storage service."
[google-keep]: https://en.wikipedia.org/wiki/Google_Keep "A note-taking service."
[google-maps]: https://www.google.com/maps/ "Web-based map tools."
[google-photos]: https://photos.google.com/ "A photo sharing service."
[google-sheets]: https://www.google.com/sheets/about/ "Online spreadsheet software."
[ia-writer]: https://ia.net/writer/updates/ia-writer-for-mac "A full-screen writing tool for the Mac."
[illustrator]: https://www.adobe.com/products/illustrator.html "A vector graphics editor."
[indesign]: https://www.adobe.com/products/indesign.html "A desktop/web publishing application."
[k242hqlcbid]: https://www.acer.com/ac/en/ZA/content/model/UM.UX6EE.C04 "A 23.6 inch monitor."
[lightroom]: https://www.adobe.com/products/photoshop-lightroom.html "Photo management and editing software."
[macbook-pro]: https://www.apple.com/macbook-pro/ "A laptop."
[macos]: https://en.wikipedia.org/wiki/MacOS "An operating system for Mac hardware."
[mail]: https://en.wikipedia.org/wiki/Mail_(application) "The default Mac OS X mail client."
[moto-360-2nd-generation]: https://en.wikipedia.org/wiki/Moto_360_(2nd_generation) "A smartwatch."
[mstand]: https://www.raindesigninc.com/mstand.html "A laptop stand."
[notepad-plusplus]: https://notepad-plus-plus.org/ "A free text/code editor for Windows."
[palettab]: https://chrome.google.com/webstore/detail/palettab/bidckpnndigbjhmojikkhmejkfkpgoih?hl=en "A Chrome extension that shows you fonts and colour palettes on a new tab."
[papers]: http://papersapp.com "iTunes-like software for organising articles."
[photoshop]: https://www.adobe.com/products/photoshop.html "A bitmap image editor."
[pixel-2]: https://en.wikipedia.org/wiki/Pixel_2 "A 5 inch Android smartphone."
[pocket-casts]: https://play.pocketcasts.com/ "A web-based podcast player."
[pocket]: https://getpocket.com/ "A service for storing links to look at later on."
[premiere]: https://www.adobe.com/products/premiere.html "A video editing suite."
[pump-air]: http://www.myblueant.com/products/headphones/pumpair/ "Wireless earbuds."
[r]: http://www.r-project.org/ "Software for statistical computing and graphics."
[shazam]: https://www.shazam.com/ "A service for identifying music."
[sndpeek]: http://soundlab.cs.princeton.edu/software/sndpeek/ "Real-time audio visualisation software."
[spotify]: https://www.spotify.com/us/ "A music streaming service."
[textwrangler]: http://www.barebones.com/products/textwrangler/ "A free, powerful text editor for the Mac."
[tweetbot]: https://tapbots.com/tweetbot/mac/ "A Twitter client for the Mac."
[tweetdeck]: https://about.twitter.com/products/tweetdeck "A multi-column Twitter client."
[u2715h]: https://www.dell.com/en-us/work/shop/cty/monitor-dell-ultrasharp-27-u2715h/spd/dell-u2715h "A 27 inch monitor."
[vp3-61-key]: http://www.wasdkeyboards.com/index.php/products/mechanical-keyboard/wasd-vp3-61-key-custom-mechanical-keyboard.html "A mechanical keyboard."
[yeti]: http://bluemic.com/yeti/ "A USB microphone."
| {'content_hash': '3f2b1e0c9e57f400cd815c2f56211dc4', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 774, 'avg_line_length': 96.32407407407408, 'alnum_prop': 0.7556474094011343, 'repo_name': 'ivuk/usesthis', 'id': '625c2d265a4adf8f63dae77e95ce1aec9c0318ca', 'size': '10407', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'posts/2018-04-11-samantha.vilkins.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5808'}, {'name': 'HTML', 'bytes': '16292'}, {'name': 'Ruby', 'bytes': '13530'}, {'name': 'Vim script', 'bytes': '205'}]} |
id: "FontElement"
title: "Class: FontElement"
sidebar_label: "FontElement"
sidebar_position: 0
custom_edit_url: null
---
## Hierarchy
- [`Element`](Element.md)
↳ **`FontElement`**
## Properties
### ignoreChildTypes
▪ `Static` `Readonly` **ignoreChildTypes**: `string`[]
#### Inherited from
[Element](Element.md).[ignoreChildTypes](Element.md#ignorechildtypes)
#### Defined in
[src/Document/Element.ts:11](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L11)
___
### attributes
• `Readonly` **attributes**: `Record`<`string`, [`Property`](Property.md)<`unknown`\>\> = `{}`
#### Inherited from
[Element](Element.md).[attributes](Element.md#attributes)
#### Defined in
[src/Document/Element.ts:14](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L14)
___
### styles
• `Readonly` **styles**: `Record`<`string`, [`Property`](Property.md)<`unknown`\>\> = `{}`
#### Inherited from
[Element](Element.md).[styles](Element.md#styles)
#### Defined in
[src/Document/Element.ts:15](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L15)
___
### stylesSpecificity
• `Readonly` **stylesSpecificity**: `Record`<`string`, `string`\> = `{}`
#### Inherited from
[Element](Element.md).[stylesSpecificity](Element.md#stylesspecificity)
#### Defined in
[src/Document/Element.ts:16](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L16)
___
### animationFrozen
• **animationFrozen**: `boolean` = `false`
#### Inherited from
[Element](Element.md).[animationFrozen](Element.md#animationfrozen)
#### Defined in
[src/Document/Element.ts:17](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L17)
___
### animationFrozenValue
• **animationFrozenValue**: `string` = `''`
#### Inherited from
[Element](Element.md).[animationFrozenValue](Element.md#animationfrozenvalue)
#### Defined in
[src/Document/Element.ts:18](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L18)
___
### parent
• **parent**: [`Element`](Element.md) = `null`
#### Inherited from
[Element](Element.md).[parent](Element.md#parent)
#### Defined in
[src/Document/Element.ts:19](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L19)
___
### children
• **children**: [`Element`](Element.md)[] = `[]`
#### Inherited from
[Element](Element.md).[children](Element.md#children)
#### Defined in
[src/Document/Element.ts:20](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L20)
___
### document
• `Protected` `Readonly` **document**: [`Document`](Document.md)
#### Inherited from
[Element](Element.md).[document](Element.md#document)
___
### node
• `Protected` `Optional` `Readonly` **node**: `HTMLElement`
#### Inherited from
[Element](Element.md).[node](Element.md#node)
___
### captureTextNodes
• `Protected` `Readonly` **captureTextNodes**: `boolean` = `false`
#### Inherited from
[Element](Element.md).[captureTextNodes](Element.md#capturetextnodes)
___
### type
• **type**: `string` = `'font'`
#### Overrides
[Element](Element.md).[type](Element.md#type)
#### Defined in
[src/Document/FontElement.ts:8](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L8)
___
### isArabic
• `Readonly` **isArabic**: `boolean` = `false`
#### Defined in
[src/Document/FontElement.ts:9](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L9)
___
### missingGlyph
• `Readonly` **missingGlyph**: [`MissingGlyphElement`](MissingGlyphElement.md)
#### Defined in
[src/Document/FontElement.ts:10](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L10)
___
### glyphs
• `Readonly` **glyphs**: `Record`<`string`, [`GlyphElement`](GlyphElement.md)\> = `{}`
#### Defined in
[src/Document/FontElement.ts:11](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L11)
___
### arabicGlyphs
• `Readonly` **arabicGlyphs**: `Record`<`string`, `Partial`<`Record`<`ArabicForm`, [`GlyphElement`](GlyphElement.md)\>\>\> = `{}`
#### Defined in
[src/Document/FontElement.ts:12](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L12)
___
### horizAdvX
• `Readonly` **horizAdvX**: `number`
#### Defined in
[src/Document/FontElement.ts:13](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L13)
___
### isRTL
• `Readonly` **isRTL**: `boolean` = `false`
#### Defined in
[src/Document/FontElement.ts:14](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L14)
___
### fontFace
• `Readonly` **fontFace**: [`FontFaceElement`](FontFaceElement.md)
#### Defined in
[src/Document/FontElement.ts:15](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L15)
## Methods
### getAttribute
▸ **getAttribute**(`name`, `createIfNotExists?`): [`Property`](Property.md)<`unknown`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `name` | `string` | `undefined` |
| `createIfNotExists` | `boolean` | `false` |
#### Returns
[`Property`](Property.md)<`unknown`\>
#### Inherited from
[Element](Element.md).[getAttribute](Element.md#getattribute)
#### Defined in
[src/Document/Element.ts:87](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L87)
___
### getHrefAttribute
▸ **getHrefAttribute**(): [`Property`](Property.md)<`unknown`\>
#### Returns
[`Property`](Property.md)<`unknown`\>
#### Inherited from
[Element](Element.md).[getHrefAttribute](Element.md#gethrefattribute)
#### Defined in
[src/Document/Element.ts:101](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L101)
___
### getStyle
▸ **getStyle**(`name`, `createIfNotExists?`, `skipAncestors?`): [`Property`](Property.md)<`unknown`\>
#### Parameters
| Name | Type | Default value |
| :------ | :------ | :------ |
| `name` | `string` | `undefined` |
| `createIfNotExists` | `boolean` | `false` |
| `skipAncestors` | `boolean` | `false` |
#### Returns
[`Property`](Property.md)<`unknown`\>
#### Inherited from
[Element](Element.md).[getStyle](Element.md#getstyle)
#### Defined in
[src/Document/Element.ts:114](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L114)
___
### setContext
▸ **setContext**(`_`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | [`RenderingContext2D`](../#renderingcontext2d) |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[setContext](Element.md#setcontext)
#### Defined in
[src/Document/Element.ts:186](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L186)
___
### applyEffects
▸ `Protected` **applyEffects**(`ctx`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `ctx` | [`RenderingContext2D`](../#renderingcontext2d) |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[applyEffects](Element.md#applyeffects)
#### Defined in
[src/Document/Element.ts:190](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L190)
___
### clearContext
▸ **clearContext**(`_`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `_` | [`RenderingContext2D`](../#renderingcontext2d) |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[clearContext](Element.md#clearcontext)
#### Defined in
[src/Document/Element.ts:210](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L210)
___
### renderChildren
▸ **renderChildren**(`ctx`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `ctx` | [`RenderingContext2D`](../#renderingcontext2d) |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[renderChildren](Element.md#renderchildren)
#### Defined in
[src/Document/Element.ts:214](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L214)
___
### addChild
▸ `Protected` **addChild**(`childNode`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `childNode` | `HTMLElement` \| [`Element`](Element.md) |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[addChild](Element.md#addchild)
#### Defined in
[src/Document/Element.ts:220](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L220)
___
### matchesSelector
▸ `Protected` **matchesSelector**(`selector`): `boolean`
#### Parameters
| Name | Type |
| :------ | :------ |
| `selector` | `string` |
#### Returns
`boolean`
#### Inherited from
[Element](Element.md).[matchesSelector](Element.md#matchesselector)
#### Defined in
[src/Document/Element.ts:232](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L232)
___
### addStylesFromStyleDefinition
▸ **addStylesFromStyleDefinition**(): `void`
#### Returns
`void`
#### Inherited from
[Element](Element.md).[addStylesFromStyleDefinition](Element.md#addstylesfromstyledefinition)
#### Defined in
[src/Document/Element.ts:248](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L248)
___
### removeStyles
▸ `Protected` **removeStyles**(`element`, `ignoreStyles`): [`string`, `string`][]
#### Parameters
| Name | Type |
| :------ | :------ |
| `element` | [`Element`](Element.md) |
| `ignoreStyles` | `string`[] |
#### Returns
[`string`, `string`][]
#### Inherited from
[Element](Element.md).[removeStyles](Element.md#removestyles)
#### Defined in
[src/Document/Element.ts:283](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L283)
___
### restoreStyles
▸ `Protected` **restoreStyles**(`element`, `styles`): `void`
#### Parameters
| Name | Type |
| :------ | :------ |
| `element` | [`Element`](Element.md) |
| `styles` | [`string`, `string`][] |
#### Returns
`void`
#### Inherited from
[Element](Element.md).[restoreStyles](Element.md#restorestyles)
#### Defined in
[src/Document/Element.ts:301](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L301)
___
### isFirstChild
▸ **isFirstChild**(): `boolean`
#### Returns
`boolean`
#### Inherited from
[Element](Element.md).[isFirstChild](Element.md#isfirstchild)
#### Defined in
[src/Document/Element.ts:307](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/Element.ts#L307)
___
### render
▸ **render**(): `void`
#### Returns
`void`
#### Overrides
[Element](Element.md).[render](Element.md#render)
#### Defined in
[src/Document/FontElement.ts:63](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L63)
## Constructors
### constructor
• **new FontElement**(`document`, `node`, `captureTextNodes?`)
#### Parameters
| Name | Type |
| :------ | :------ |
| `document` | [`Document`](Document.md) |
| `node` | `HTMLElement` |
| `captureTextNodes?` | `boolean` |
#### Overrides
[Element](Element.md).[constructor](Element.md#constructor)
#### Defined in
[src/Document/FontElement.ts:17](https://github.com/canvg/canvg/blob/5c58ee8/src/Document/FontElement.ts#L17)
| {'content_hash': '1d082efa88f06a25dff7f6ae8146ed4f', 'timestamp': '', 'source': 'github', 'line_count': 577, 'max_line_length': 129, 'avg_line_length': 18.986135181975737, 'alnum_prop': 0.6590597900502054, 'repo_name': 'canvg/canvg', 'id': '1da7b5830d4cb3841e04c240ed53d7c4b3162402', 'size': '11029', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'website/docs/api/classes/FontElement.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1732'}, {'name': 'HTML', 'bytes': '20917'}, {'name': 'JavaScript', 'bytes': '164672'}, {'name': 'Shell', 'bytes': '288'}, {'name': 'TypeScript', 'bytes': '221090'}]} |
layout: post
title: OpenStack Ceilometer Collector代码解读
category: 技术
tags: OpenStack
keywords: OpenStack,Ceilometer,Collector,Source
description: Collector是Ceilometer非常关键的部件之一,它负责搜集采集到的数据,并将其存储到数据库中。它基于PubSubHubbub实现,和agent部件一起实现了数据采集和订阅功能
---
### Collector功能
Collector顾名思义是负责数据收集的,它负责搜集来自OpenStack其他组件(如Nova,Glance,Cinder等)的Notification信息,以及从Compute Agent和Central Agent发送来的数据,然后将这些数据存储在数据库中。
### PubSubHubbub
[PubSubHubbub](https://code.google.com/p/pubsubhubbub/)是Google推出的一个基于Web-hook方式的解决方案,它其实是RSS的改进。它具体要解决的是RSS效率低和压力大的问题,有一个[Go real time with pubsubhubbub and feeds](http://www.slideshare.net/devseed/go-real-time-with-pubsubhubbub-and-feeds)讲的挺清楚
[Tim](http://timyang.net/web/pubsubhubbub/)的这篇博客也讲了它的机制,其中有这个图:

一个PubSubHubbub的大致流程如下:
1. Sub找Pub订阅内容,Pub将Hub的地址发给Sub,告诉Sub:你以后找它要内容去
2. Sub将自己要订阅的地址发给Hub,并在Hub那里注册了一个Callback函数,以后有新内容麻烦给Callback就好啦
3. Hub可以主动,也可以被动的从Pub那里获得内容,然后再分发给在自己这里注册的Sub
图中可以看到,有这么几个关键部分,在Ceilometer中,它们对应如下:
- Publisher 内容提供方,OpenStack的各组件和Agent模块的角色
- Subscriber 内容订阅方,Collector的角色
- Hub 中转,Collector也充当了这个角色
### Collector代码原理
有些相思代码在之前的[OpenStack Ceilometer Compute Agent源码解读](/2013/06/11/hacking-in-openstack-ceilometer-compute-agent.html)讲过
这里只写和collector有关的
#### 入口函数
Collector的核心功能在`ceilometer.collector.service:CollectorService`中,它是OpenStack的Service服务,启动以后从`initialize_service_hook()`开始运行
def initialize_service_hook(self, service):
self.pipeline_manager = pipeline.setup_pipeline(
transformer.TransformerExtensionManager(
'ceilometer.transformer',
),
publisher.PublisherExtensionManager(
'ceilometer.publisher',
),
)
self.notification_manager = \
extension_manager.ActivatedExtensionManager(
namespace=self.COLLECTOR_NAMESPACE,
disabled_names=
cfg.CONF.collector.disabled_notification_listeners,
)
self.notification_manager.map(self._setup_subscription)
self.conn.create_worker(
cfg.CONF.publisher_meter.metering_topic,
rpc_dispatcher.RpcDispatcher([self]),
'ceilometer.collector.' + cfg.CONF.publisher_meter.metering_topic,
)
这里只说重点的,`self.notification_manager`是导入所有可用的内容的处理对象,从`setup.cfg`中可以找到
ceilometer.collector =
instance = ceilometer.compute.notifications:Instance
instance_flavor = ceilometer.compute.notifications:InstanceFlavor
instance_delete = ceilometer.compute.notifications:InstanceDelete
...
#### 订阅内容
接着`self.notification_manager.map(self._setup_subscription)`要对这些对象进行配置,其实就相当于PubSubHubbub中的订阅了
def _setup_subscription(self, ext, *args, **kwds):
handler = ext.obj
for exchange_topic in handler.get_exchange_topics(cfg.CONF):
for topic in exchange_topic.topics:
self.conn.join_consumer_pool(
callback=self.process_notification,
pool_name='ceilometer.notifications',
topic=topic,
exchange_name=exchange_topic.exchange,
)
#### 回调函数
这里`_setup_subscription()`讲每一个订阅对象都`join_consumer_pool`,即在AMQP中接收这些订阅相关topic的内容,然后指定了callback函数为`self.process_notification`
def process_notification(self, notification):
self.notification_manager.map(self._process_notification_for_ext,
notification=notification,
)
def _process_notification_for_ext(self, ext, notification):
handler = ext.obj
if notification['event_type'] in handler.get_event_types():
ctxt = context.get_admin_context()
with self.pipeline_manager.publisher(ctxt,
cfg.CONF.counter_source) as p:
p(list(handler.process_notification(notification)))
callback在执行后会调用这些notification中的`process_notification()`,它的作用是对不同的消息进行不同处理,因为从Nova,Glance等组件发来的消息Collector不一定都读的懂
#### 处理内容
处理好的消息还是会通过Pipeline发送到AMQP中,然后和Agent直接发来的消息类似,Collector接收并交给
def record_metering_data(self, context, data):
for meter in data:
if meter.get('timestamp'):
ts = timeutils.parse_isotime(meter['timestamp'])
meter['timestamp'] = timeutils.normalize_time(ts)
self.storage_conn.record_metering_data(meter)
来处理,其实相当于自己给自己通过AMQP发了一条信息,这也就能看出,其实Collector充当了Hub和Sub双重身份
### 总结
Collector相对来说不是很复杂,了解了PubSubHubbub后再看就相对简单了。
这里没有详细说数据存储部分,因为存储和API调用部分联系比较紧密,留给存储部分再讲吧
| {'content_hash': 'dd474923eca2ba326298d2b302d97ce5', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 244, 'avg_line_length': 36.41732283464567, 'alnum_prop': 0.7029189189189189, 'repo_name': 'itfanr/radxa123', 'id': '94bbcf71408312720f4c4d7f9cb08fffd9c57f0c', 'size': '6035', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': '_posts/2013-06-12-hacking-in-openstack-ceilometer-collector.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6876'}, {'name': 'JavaScript', 'bytes': '4259'}]} |
<!DOCTYPE html>
<html>
<head>
<title>Classe KPixmapSequence</title>
</head>
<body>
<p>Classe <b>KPixmapSequence</b></p><p>Derivada de <a href='.html'></a></p><p>Classes derivadas: <a href='.html'></a></p><p>Módulo <b>kwidgetsaddons</b></p><p>Versão do Qt: <b>5,0,0</b></p><p>Construtor: KPixmapSequence():new( )</p><p>Construtor: KPixmapSequence():new(KPixmapSequence )</p><p>Construtor: KPixmapSequence():new(QPixmap, QSize=QSize() )</p><p>Construtor: KPixmapSequence():new(QString, int )</p><p>Método: KPixmapSequence():isValid( ) -> bool</p><p>Método: KPixmapSequence():isEmpty( ) -> bool</p><p>Método: KPixmapSequence():frameSize( ) -> QSize</p><p>Método: KPixmapSequence():frameCount( ) -> int</p><p>Método: KPixmapSequence():frameAt(int ) -> QPixmap</p>
</body>
</html>
| {'content_hash': 'b641542e98e60995afa9767cc27e0cde', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 676, 'avg_line_length': 78.7, 'alnum_prop': 0.6670902160101652, 'repo_name': 'marcosgambeta/KDE5xHb', 'id': '84bfbf3a7c65e72c2690a107a028fd87ad23e442', 'size': '787', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/KWidgetsAddons/KPixmapSequence.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '15440'}, {'name': 'C++', 'bytes': '110583'}, {'name': 'Makefile', 'bytes': '14435'}, {'name': 'xBase', 'bytes': '628740'}]} |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The Object.prototype.propertyIsEnumerable.length property has the attribute DontEnum
*
* @path ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A8.js
* @description Checking if enumerating the Object.prototype.propertyIsEnumerable.length property fails
*/
//CHECK#0
if (!(Object.prototype.propertyIsEnumerable.hasOwnProperty('length'))) {
$FAIL('#0: the Object.prototype.propertyIsEnumerable has length property');
}
// CHECK#1
if (Object.prototype.propertyIsEnumerable.propertyIsEnumerable('length')) {
$ERROR('#1: the Object.prototype.propertyIsEnumerable.length property has the attributes DontEnum');
}
// CHECK#2
for (p in Object.prototype.propertyIsEnumerable){
if (p==="length")
$ERROR('#2: the Object.prototype.propertyIsEnumerable.length property has the attributes DontEnum');
}
//
| {'content_hash': '3caceb9f3cf1a5dd5b8c0c4818612142', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 108, 'avg_line_length': 33.46153846153846, 'alnum_prop': 0.7505747126436781, 'repo_name': 'honestegg/jint', 'id': '75c6b994e8b2f077db3b2327907c8241116fb651', 'size': '870', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'Jint.Tests.Ecma/TestCases/ch15/15.2/15.2.4/15.2.4.7/S15.2.4.7_A8.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '70'}, {'name': 'C#', 'bytes': '3913340'}, {'name': 'JavaScript', 'bytes': '11429348'}]} |
* @file format_output.h
* outputting format for symbol lists
*
* @remark Copyright 2002 OProfile authors
* @remark Read the file COPYING
*
size_t pc, counts_t & c,
extra_images const & extra, double d = 0.0)
: symbol(sym), sample(s), pclass(pc),
counts(c), extra(extra), diff(d) {}
symbol_entry const & symbol;
sample_entry const & sample; | {'content_hash': '58d87cee417c15b442bea24aededa6ba', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 50, 'avg_line_length': 30.916666666666668, 'alnum_prop': 0.6469002695417789, 'repo_name': 'lach76/scancode-toolkit', 'id': '07d7e2d574d1d849f4d4f9d71a8b90726f83c6da', 'size': '371', 'binary': False, 'copies': '13', 'ref': 'refs/heads/develop', 'path': 'tests/cluecode/data/ics/oprofile-libpp/format_output.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '1251'}, {'name': 'AppleScript', 'bytes': '168'}, {'name': 'Assembly', 'bytes': '78231'}, {'name': 'Awk', 'bytes': '248'}, {'name': 'Batchfile', 'bytes': '5318'}, {'name': 'C', 'bytes': '2030855'}, {'name': 'C#', 'bytes': '5901'}, {'name': 'C++', 'bytes': '537880'}, {'name': 'CMake', 'bytes': '142'}, {'name': 'CSS', 'bytes': '171'}, {'name': 'GAP', 'bytes': '579'}, {'name': 'Groff', 'bytes': '209319'}, {'name': 'HTML', 'bytes': '2985563'}, {'name': 'Inno Setup', 'bytes': '235'}, {'name': 'Java', 'bytes': '150670'}, {'name': 'JavaScript', 'bytes': '10190'}, {'name': 'M4', 'bytes': '45516'}, {'name': 'Makefile', 'bytes': '19150'}, {'name': 'Matlab', 'bytes': '148'}, {'name': 'Objective-C', 'bytes': '27243'}, {'name': 'Objective-C++', 'bytes': '950'}, {'name': 'PHP', 'bytes': '621154'}, {'name': 'Pascal', 'bytes': '3417'}, {'name': 'Perl', 'bytes': '268151'}, {'name': 'PostScript', 'bytes': '562'}, {'name': 'Protocol Buffer', 'bytes': '374'}, {'name': 'Python', 'bytes': '2776839'}, {'name': 'Scala', 'bytes': '4500'}, {'name': 'Shell', 'bytes': '1602822'}, {'name': 'Smalltalk', 'bytes': '603'}, {'name': 'TeX', 'bytes': '3126'}, {'name': 'VimL', 'bytes': '1129'}, {'name': 'Visual Basic', 'bytes': '23'}, {'name': 'XSLT', 'bytes': '474'}, {'name': 'Yacc', 'bytes': '1497'}]} |
package org.springframework.cloud.netflix.hystrix;
/**
* @author Spencer Gibb
*/
public class HystrixConstants {
public static final String HYSTRIX_STREAM_DESTINATION = "springCloudHystrixStream";
private HystrixConstants() {
throw new AssertionError("Must not instantiate constant utility class");
}
}
| {'content_hash': 'e7a3c81207b82cfed2016373328573a4', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 84, 'avg_line_length': 19.75, 'alnum_prop': 0.7658227848101266, 'repo_name': 'brenuart/spring-cloud-netflix', 'id': '073eec02553fc6e4ca1642ee61ef34954bc61f95', 'size': '936', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'spring-cloud-netflix-core/src/main/java/org/springframework/cloud/netflix/hystrix/HystrixConstants.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '52448'}, {'name': 'FreeMarker', 'bytes': '19389'}, {'name': 'Groovy', 'bytes': '964'}, {'name': 'HTML', 'bytes': '10579'}, {'name': 'Java', 'bytes': '1835786'}, {'name': 'JavaScript', 'bytes': '33184'}, {'name': 'Ruby', 'bytes': '481'}, {'name': 'Shell', 'bytes': '952'}]} |
package org.innovateuk.ifs.management.competition.setup.milestone.sectionupdater;
import org.apache.commons.collections4.map.LinkedMap;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.MilestoneResource;
import org.innovateuk.ifs.competition.resource.MilestoneType;
import org.innovateuk.ifs.competition.service.MilestoneRestService;
import org.innovateuk.ifs.management.competition.setup.core.form.CompetitionSetupForm;
import org.innovateuk.ifs.management.competition.setup.core.form.GenericMilestoneRowForm;
import org.innovateuk.ifs.management.competition.setup.core.service.CompetitionSetupMilestoneService;
import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestoneRowForm;
import org.innovateuk.ifs.management.competition.setup.milestone.form.MilestonesForm;
import org.innovateuk.ifs.user.resource.UserResource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hamcrest.CoreMatchers.*;
import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess;
import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.competition.builder.MilestoneResourceBuilder.newMilestoneResource;
import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.Silent.class)
public class MilestonesSectionSaverTest {
@InjectMocks
private MilestonesSectionUpdater service;
@Mock
private CompetitionSetupMilestoneService competitionSetupMilestoneService;
@Mock
private MilestoneRestService milestoneRestService;
@Test
public void testSaveMilestone() {
MilestonesForm competitionSetupForm = new MilestonesForm();
ZonedDateTime milestoneDate = ZonedDateTime.of(2017, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault());
CompetitionResource competition = newCompetitionResource()
.withMilestones(singletonList(1L))
.withId(1L).build();
MilestoneResource milestoneresource = newMilestoneResource()
.withId(1L)
.withName(MilestoneType.OPEN_DATE)
.withDate(milestoneDate)
.withCompetitionId(1L).build();
List<MilestoneResource> resourceList = new ArrayList<>();
resourceList.add(milestoneresource);
UserResource loggedInUser = newUserResource().build();
competitionSetupForm.setMilestoneEntries(populateMilestoneFormEntry(resourceList));
when(competitionSetupMilestoneService.updateMilestonesForCompetition(anyList(), anyMap(), anyLong())).thenReturn(serviceSuccess());
when(milestoneRestService.getAllMilestonesByCompetitionId(anyLong())).thenReturn(restSuccess(resourceList));
service.saveSection(competition, competitionSetupForm, loggedInUser);
List<Long> milestones = competition.getMilestones();
assertEquals(1L, milestones.get(0).longValue());
assertEquals(1L, (long) resourceList.get(0).getCompetitionId());
assertNotNull(resourceList.get(0).getDate());
assertEquals(resourceList.get(0).getType(), MilestoneType.OPEN_DATE);
}
@Test
public void testSaveMilestoneSetupComplete() {
MilestonesForm competitionSetupForm = new MilestonesForm();
ZonedDateTime pastDate = ZonedDateTime.now().minusDays(1);
ZonedDateTime futureDate = ZonedDateTime.now().plusDays(1);
CompetitionResource competition = newCompetitionResource()
.withMilestones(Arrays.asList(1L, 2L))
.withSetupComplete(true)
.withStartDate(ZonedDateTime.now().minusDays(1))
.withFundersPanelDate(ZonedDateTime.now().plusDays(1))
.withId(1L).build();
MilestoneResource milestonePast = newMilestoneResource()
.withId(1L)
.withName(MilestoneType.OPEN_DATE)
.withDate(pastDate)
.withCompetitionId(1L).build();
MilestoneResource milestoneFuture = newMilestoneResource()
.withId(2L)
.withName(MilestoneType.BRIEFING_EVENT)
.withDate(futureDate)
.withCompetitionId(1L).build();
UserResource loggedInUser = newUserResource().build();
List<MilestoneResource> resourceList = asList(milestonePast, milestoneFuture);
competitionSetupForm.setMilestoneEntries(populateMilestoneFormEntry(resourceList));
when(competitionSetupMilestoneService.updateMilestonesForCompetition(anyList(), anyMap(), anyLong())).thenReturn(serviceSuccess());
when(milestoneRestService.getAllMilestonesByCompetitionId(anyLong())).thenReturn(restSuccess(resourceList));
service.saveSection(competition, competitionSetupForm, loggedInUser);
//verify update was only called once (for the future date)
ArgumentCaptor<Map> argumentCaptor = ArgumentCaptor.forClass(Map.class);
verify(competitionSetupMilestoneService).updateMilestonesForCompetition(eq(resourceList), argumentCaptor.capture(), eq(1L));
assertThat(argumentCaptor.getValue().size(), equalTo(1));
assertThat(argumentCaptor.getValue().get(MilestoneType.BRIEFING_EVENT.name()), notNullValue());
assertThat(argumentCaptor.getValue().get(MilestoneType.OPEN_DATE.name()), nullValue());
}
private LinkedMap<String, GenericMilestoneRowForm> populateMilestoneFormEntry(List<MilestoneResource> resources) {
LinkedMap<String, GenericMilestoneRowForm> milestoneList = new LinkedMap<>();
resources.forEach(milestoneResource -> {
MilestoneRowForm milestone = new MilestoneRowForm(milestoneResource.getType(), milestoneResource.getDate());
milestoneList.put(milestoneResource.getType().name(), milestone);
});
return milestoneList;
}
@Test
public void testsSupportsForm() {
assertTrue(service.supportsForm(MilestonesForm.class));
assertFalse(service.supportsForm(CompetitionSetupForm.class));
}
}
| {'content_hash': '95326b4d13136814d20dc500578ee5d3', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 139, 'avg_line_length': 45.33783783783784, 'alnum_prop': 0.744709388971684, 'repo_name': 'InnovateUKGitHub/innovation-funding-service', 'id': '2be27e3dfafc1ef898bb7a3db1a60e8f4b448aea', 'size': '6710', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'ifs-web-service/ifs-competition-mgt-service/src/test/java/org/innovateuk/ifs/management/competition/setup/milestone/sectionupdater/MilestonesSectionSaverTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '1972'}, {'name': 'HTML', 'bytes': '6342985'}, {'name': 'Java', 'bytes': '26591674'}, {'name': 'JavaScript', 'bytes': '269444'}, {'name': 'Python', 'bytes': '58983'}, {'name': 'RobotFramework', 'bytes': '3317394'}, {'name': 'SCSS', 'bytes': '100274'}, {'name': 'Shell', 'bytes': '60248'}]} |
package com.sylvanaar.idea.Lua.projectView;
import com.intellij.ide.projectView.TreeStructureProvider;
import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.sylvanaar.idea.Lua.lang.psi.LuaPsiFile;
import com.sylvanaar.idea.Lua.projectView.nodes.LuaFileTreeNode;
import java.util.ArrayList;
import java.util.Collection;
/**
* Created by IntelliJ IDEA.
* User: Jon S Akhtar
* Date: 12/22/11
* Time: 12:58 PM
*/
public class LuaProjectTreeSubElementProvider implements TreeStructureProvider, DumbAware {
private final Project myProject;
public LuaProjectTreeSubElementProvider(Project project) {
myProject = project;
}
@Override
public Collection<AbstractTreeNode> modify(AbstractTreeNode parent, Collection<AbstractTreeNode> children, ViewSettings settings) {
ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
for (final AbstractTreeNode child : children) {
Object o = child.getValue();
if (o instanceof LuaPsiFile) {
result.add(new LuaFileTreeNode(myProject, (LuaPsiFile) o, settings));
continue;
}
result.add(child);
}
return result;
}
}
| {'content_hash': '87facafddae4b3092f3afc7574ee7c92', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 135, 'avg_line_length': 31.15909090909091, 'alnum_prop': 0.7199124726477024, 'repo_name': 'consulo/consulo-lua', 'id': '1a0f1705d0692a989bb2fd95a783d704aa61e780', 'size': '1992', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/sylvanaar/idea/Lua/projectView/LuaProjectTreeSubElementProvider.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '30192'}, {'name': 'HTML', 'bytes': '272076'}, {'name': 'Java', 'bytes': '1479749'}, {'name': 'Lex', 'bytes': '8843'}, {'name': 'Lua', 'bytes': '243663'}]} |
BOOST_AUTO_TEST_SUITE(getarg_tests)
static void
ResetArgs(const std::string& strArg)
{
std::vector<std::string> vecArg;
boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on);
// Insert dummy executable name:
vecArg.insert(vecArg.begin(), "testagoldcoin");
// Convert to char*:
std::vector<const char*> vecChar;
BOOST_FOREACH(std::string& s, vecArg)
vecChar.push_back(s.c_str());
ParseParameters(vecChar.size(), &vecChar[0]);
}
BOOST_AUTO_TEST_CASE(boolarg)
{
ResetArgs("-foo");
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", false));
BOOST_CHECK(GetBoolArg("-foo", true));
BOOST_CHECK(!GetBoolArg("-fo"));
BOOST_CHECK(!GetBoolArg("-fo", false));
BOOST_CHECK(GetBoolArg("-fo", true));
BOOST_CHECK(!GetBoolArg("-fooo"));
BOOST_CHECK(!GetBoolArg("-fooo", false));
BOOST_CHECK(GetBoolArg("-fooo", true));
ResetArgs("-foo=0");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", false));
BOOST_CHECK(!GetBoolArg("-foo", true));
ResetArgs("-foo=1");
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", false));
BOOST_CHECK(GetBoolArg("-foo", true));
// New 0.6 feature: auto-map -nosomething to !-something:
ResetArgs("-nofoo");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", false));
BOOST_CHECK(!GetBoolArg("-foo", true));
ResetArgs("-nofoo=1");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", false));
BOOST_CHECK(!GetBoolArg("-foo", true));
ResetArgs("-foo -nofoo"); // -foo should win
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", false));
BOOST_CHECK(GetBoolArg("-foo", true));
ResetArgs("-foo=1 -nofoo=1"); // -foo should win
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", false));
BOOST_CHECK(GetBoolArg("-foo", true));
ResetArgs("-foo=0 -nofoo=0"); // -foo should win
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", false));
BOOST_CHECK(!GetBoolArg("-foo", true));
// New 0.6 feature: treat -- same as -:
ResetArgs("--foo=1");
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", false));
BOOST_CHECK(GetBoolArg("-foo", true));
ResetArgs("--nofoo=1");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", false));
BOOST_CHECK(!GetBoolArg("-foo", true));
}
BOOST_AUTO_TEST_CASE(stringarg)
{
ResetArgs("");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven");
ResetArgs("-foo -bar");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "");
ResetArgs("-foo=");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "");
BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "");
ResetArgs("-foo=11");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "11");
BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "11");
ResetArgs("-foo=eleven");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "eleven");
BOOST_CHECK_EQUAL(GetArg("-foo", "eleven"), "eleven");
}
BOOST_AUTO_TEST_CASE(intarg)
{
ResetArgs("");
BOOST_CHECK_EQUAL(GetArg("-foo", 11), 11);
BOOST_CHECK_EQUAL(GetArg("-foo", 0), 0);
ResetArgs("-foo -bar");
BOOST_CHECK_EQUAL(GetArg("-foo", 11), 0);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
ResetArgs("-foo=11 -bar=12");
BOOST_CHECK_EQUAL(GetArg("-foo", 0), 11);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 12);
ResetArgs("-foo=NaN -bar=NotANumber");
BOOST_CHECK_EQUAL(GetArg("-foo", 1), 0);
BOOST_CHECK_EQUAL(GetArg("-bar", 11), 0);
}
BOOST_AUTO_TEST_CASE(doubledash)
{
ResetArgs("--foo");
BOOST_CHECK_EQUAL(GetBoolArg("-foo"), true);
ResetArgs("--foo=verbose --bar=1");
BOOST_CHECK_EQUAL(GetArg("-foo", ""), "verbose");
BOOST_CHECK_EQUAL(GetArg("-bar", 0), 1);
}
BOOST_AUTO_TEST_CASE(boolargno)
{
ResetArgs("-nofoo");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", true));
BOOST_CHECK(!GetBoolArg("-foo", false));
ResetArgs("-nofoo=1");
BOOST_CHECK(!GetBoolArg("-foo"));
BOOST_CHECK(!GetBoolArg("-foo", true));
BOOST_CHECK(!GetBoolArg("-foo", false));
ResetArgs("-nofoo=0");
BOOST_CHECK(GetBoolArg("-foo"));
BOOST_CHECK(GetBoolArg("-foo", true));
BOOST_CHECK(GetBoolArg("-foo", false));
ResetArgs("-foo --nofoo");
BOOST_CHECK(GetBoolArg("-foo"));
ResetArgs("-nofoo -foo"); // foo always wins:
BOOST_CHECK(GetBoolArg("-foo"));
}
BOOST_AUTO_TEST_SUITE_END()
| {'content_hash': 'bdc2ca13966d82cac4aa98bc9caa9246', 'timestamp': '', 'source': 'github', 'line_count': 161, 'max_line_length': 78, 'avg_line_length': 28.82608695652174, 'alnum_prop': 0.6037491919844861, 'repo_name': 'icardgod/A-Gold-Coin', 'id': '5de66cc7377685f172bf35e52003dc04aa54bc4b', 'size': '4764', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/getarg_tests.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '61562'}, {'name': 'C', 'bytes': '7748'}, {'name': 'C++', 'bytes': '1701813'}, {'name': 'Groff', 'bytes': '12626'}, {'name': 'Makefile', 'bytes': '4882'}, {'name': 'NSIS', 'bytes': '6041'}, {'name': 'Objective-C', 'bytes': '858'}, {'name': 'Objective-C++', 'bytes': '3537'}, {'name': 'Python', 'bytes': '41600'}, {'name': 'Shell', 'bytes': '1605'}]} |
def SimpleDecorator( fun ):
def _SimpleDecorator( name ):
name = f'my dearest {name}'
return fun( name )
return _SimpleDecorator
def ArgDecorator( title ):
def _ArgDecorator( fun ):
def __ArgDecorator( name ):
name = f'my dearest {title} {name}'
return fun( name )
return __ArgDecorator
return _ArgDecorator
# Base functions
def printHello( name ):
print( f'Hello {name}' )
@SimpleDecorator
def printHello2( name ):
print( f'Hello {name}' )
@ArgDecorator( 'Sir' )
def printHello3( name ):
print( f'Hello {name}' )
# Normal calls
printHello( 'Anna' )
printHello2( 'Bert' )
printHello3( 'Wolfram' )
# Test 'weird' calls
helloDec = SimpleDecorator( printHello )
helloDec( 'Anna' )
SimpleDecorator( printHello )( 'Herbert' )
ArgDecorator( 'Mr' )( printHello )( 'Simon' )
ArgDecorator( 'Noname Mc.' )( lambda name: print( f'Hello, {name}' ) )( 'Anon' )
| {'content_hash': 'b9abc728a08df97b1f6e2bc49f2ea27d', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 80, 'avg_line_length': 23.825, 'alnum_prop': 0.621196222455404, 'repo_name': 'simonlovgren/tests', 'id': '14b388df88e414c3d0e0f0f9f52dcec52e432471', 'size': '991', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'python/decorators.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '764'}, {'name': 'C', 'bytes': '32375'}, {'name': 'C++', 'bytes': '9072'}, {'name': 'HTML', 'bytes': '1051'}, {'name': 'Haskell', 'bytes': '107'}, {'name': 'JavaScript', 'bytes': '1024'}, {'name': 'Makefile', 'bytes': '495'}, {'name': 'Python', 'bytes': '51224'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.