text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
/*************************************************************************/ /* script_language.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #include "script_language.h" #include "core/core_string_names.h" #include "core/project_settings.h" ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES]; int ScriptServer::_language_count = 0; bool ScriptServer::scripting_enabled = true; bool ScriptServer::reload_scripts_on_save = false; bool ScriptServer::languages_finished = false; ScriptEditRequestFunction ScriptServer::edit_request_func = nullptr; void Script::_notification(int p_what) { if (p_what == NOTIFICATION_POSTINITIALIZE) { if (ScriptDebugger::get_singleton()) { ScriptDebugger::get_singleton()->set_break_language(get_language()); } } } Variant Script::_get_property_default_value(const StringName &p_property) { Variant ret; get_property_default_value(p_property, ret); return ret; } Array Script::_get_script_property_list() { Array ret; List<PropertyInfo> list; get_script_property_list(&list); for (List<PropertyInfo>::Element *E = list.front(); E; E = E->next()) { ret.append(E->get().operator Dictionary()); } return ret; } Array Script::_get_script_method_list() { Array ret; List<MethodInfo> list; get_script_method_list(&list); for (List<MethodInfo>::Element *E = list.front(); E; E = E->next()) { ret.append(E->get().operator Dictionary()); } return ret; } Array Script::_get_script_signal_list() { Array ret; List<MethodInfo> list; get_script_signal_list(&list); for (List<MethodInfo>::Element *E = list.front(); E; E = E->next()) { ret.append(E->get().operator Dictionary()); } return ret; } Dictionary Script::_get_script_constant_map() { Dictionary ret; Map<StringName, Variant> map; get_constants(&map); for (Map<StringName, Variant>::Element *E = map.front(); E; E = E->next()) { ret[E->key()] = E->value(); } return ret; } void Script::_bind_methods() { ClassDB::bind_method(D_METHOD("can_instance"), &Script::can_instance); //ClassDB::bind_method(D_METHOD("instance_create","base_object"),&Script::instance_create); ClassDB::bind_method(D_METHOD("instance_has", "base_object"), &Script::instance_has); ClassDB::bind_method(D_METHOD("has_source_code"), &Script::has_source_code); ClassDB::bind_method(D_METHOD("get_source_code"), &Script::get_source_code); ClassDB::bind_method(D_METHOD("set_source_code", "source"), &Script::set_source_code); ClassDB::bind_method(D_METHOD("reload", "keep_state"), &Script::reload, DEFVAL(false)); ClassDB::bind_method(D_METHOD("get_base_script"), &Script::get_base_script); ClassDB::bind_method(D_METHOD("get_instance_base_type"), &Script::get_instance_base_type); ClassDB::bind_method(D_METHOD("has_script_signal", "signal_name"), &Script::has_script_signal); ClassDB::bind_method(D_METHOD("get_script_property_list"), &Script::_get_script_property_list); ClassDB::bind_method(D_METHOD("get_script_method_list"), &Script::_get_script_method_list); ClassDB::bind_method(D_METHOD("get_script_signal_list"), &Script::_get_script_signal_list); ClassDB::bind_method(D_METHOD("get_script_constant_map"), &Script::_get_script_constant_map); ClassDB::bind_method(D_METHOD("get_property_default_value", "property"), &Script::_get_property_default_value); ClassDB::bind_method(D_METHOD("is_tool"), &Script::is_tool); ADD_PROPERTY(PropertyInfo(Variant::STRING, "source_code", PROPERTY_HINT_NONE, "", 0), "set_source_code", "get_source_code"); } void ScriptServer::set_scripting_enabled(bool p_enabled) { scripting_enabled = p_enabled; } bool ScriptServer::is_scripting_enabled() { return scripting_enabled; } ScriptLanguage *ScriptServer::get_language(int p_idx) { ERR_FAIL_INDEX_V(p_idx, _language_count, nullptr); return _languages[p_idx]; } void ScriptServer::register_language(ScriptLanguage *p_language) { ERR_FAIL_COND(_language_count >= MAX_LANGUAGES); _languages[_language_count++] = p_language; } void ScriptServer::unregister_language(ScriptLanguage *p_language) { for (int i = 0; i < _language_count; i++) { if (_languages[i] == p_language) { _language_count--; if (i < _language_count) { SWAP(_languages[i], _languages[_language_count]); } return; } } } void ScriptServer::init_languages() { { //load global classes global_classes_clear(); if (ProjectSettings::get_singleton()->has_setting("_global_script_classes")) { Array script_classes = ProjectSettings::get_singleton()->get("_global_script_classes"); for (int i = 0; i < script_classes.size(); i++) { Dictionary c = script_classes[i]; if (!c.has("class") || !c.has("language") || !c.has("path") || !c.has("base")) { continue; } add_global_class(c["class"], c["base"], c["language"], c["path"]); } } } for (int i = 0; i < _language_count; i++) { _languages[i]->init(); } } void ScriptServer::finish_languages() { for (int i = 0; i < _language_count; i++) { _languages[i]->finish(); } global_classes_clear(); languages_finished = true; } void ScriptServer::set_reload_scripts_on_save(bool p_enable) { reload_scripts_on_save = p_enable; } bool ScriptServer::is_reload_scripts_on_save_enabled() { return reload_scripts_on_save; } void ScriptServer::thread_enter() { for (int i = 0; i < _language_count; i++) { _languages[i]->thread_enter(); } } void ScriptServer::thread_exit() { for (int i = 0; i < _language_count; i++) { _languages[i]->thread_exit(); } } HashMap<StringName, ScriptServer::GlobalScriptClass> ScriptServer::global_classes; void ScriptServer::global_classes_clear() { global_classes.clear(); } void ScriptServer::add_global_class(const StringName &p_class, const StringName &p_base, const StringName &p_language, const String &p_path) { ERR_FAIL_COND_MSG(p_class == p_base || (global_classes.has(p_base) && get_global_class_native_base(p_base) == p_class), "Cyclic inheritance in script class."); GlobalScriptClass g; g.language = p_language; g.path = p_path; g.base = p_base; global_classes[p_class] = g; } void ScriptServer::remove_global_class(const StringName &p_class) { global_classes.erase(p_class); } bool ScriptServer::is_global_class(const StringName &p_class) { return global_classes.has(p_class); } StringName ScriptServer::get_global_class_language(const StringName &p_class) { ERR_FAIL_COND_V(!global_classes.has(p_class), StringName()); return global_classes[p_class].language; } String ScriptServer::get_global_class_path(const String &p_class) { ERR_FAIL_COND_V(!global_classes.has(p_class), String()); return global_classes[p_class].path; } StringName ScriptServer::get_global_class_base(const String &p_class) { ERR_FAIL_COND_V(!global_classes.has(p_class), String()); return global_classes[p_class].base; } StringName ScriptServer::get_global_class_native_base(const String &p_class) { ERR_FAIL_COND_V(!global_classes.has(p_class), String()); String base = global_classes[p_class].base; while (global_classes.has(base)) { base = global_classes[base].base; } return base; } void ScriptServer::get_global_class_list(List<StringName> *r_global_classes) { const StringName *K = nullptr; List<StringName> classes; while ((K = global_classes.next(K))) { classes.push_back(*K); } classes.sort_custom<StringName::AlphCompare>(); for (List<StringName>::Element *E = classes.front(); E; E = E->next()) { r_global_classes->push_back(E->get()); } } void ScriptServer::save_global_classes() { List<StringName> gc; get_global_class_list(&gc); Array gcarr; for (List<StringName>::Element *E = gc.front(); E; E = E->next()) { Dictionary d; d["class"] = E->get(); d["language"] = global_classes[E->get()].language; d["path"] = global_classes[E->get()].path; d["base"] = global_classes[E->get()].base; gcarr.push_back(d); } Array old; if (ProjectSettings::get_singleton()->has_setting("_global_script_classes")) { old = ProjectSettings::get_singleton()->get("_global_script_classes"); } if ((!old.empty() || gcarr.empty()) && gcarr.hash() == old.hash()) { return; } if (gcarr.empty()) { if (ProjectSettings::get_singleton()->has_setting("_global_script_classes")) { ProjectSettings::get_singleton()->clear("_global_script_classes"); } } else { ProjectSettings::get_singleton()->set("_global_script_classes", gcarr); } ProjectSettings::get_singleton()->save(); } //////////////////// void ScriptInstance::get_property_state(List<Pair<StringName, Variant>> &state) { List<PropertyInfo> pinfo; get_property_list(&pinfo); for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) { if (E->get().usage & PROPERTY_USAGE_STORAGE) { Pair<StringName, Variant> p; p.first = E->get().name; if (get(p.first, p.second)) { state.push_back(p); } } } } Variant ScriptInstance::call(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) { break; } argc++; } Variant::CallError error; return call(p_method, argptr, argc, error); } void ScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) { Variant::CallError ce; call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls } void ScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) { Variant::CallError ce; call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls } void ScriptInstance::property_set_fallback(const StringName &, const Variant &, bool *r_valid) { if (r_valid) { *r_valid = false; } } Variant ScriptInstance::property_get_fallback(const StringName &, bool *r_valid) { if (r_valid) { *r_valid = false; } return Variant(); } void ScriptInstance::call_multilevel(const StringName &p_method, VARIANT_ARG_DECLARE) { VARIANT_ARGPTRS; int argc = 0; for (int i = 0; i < VARIANT_ARG_MAX; i++) { if (argptr[i]->get_type() == Variant::NIL) { break; } argc++; } call_multilevel(p_method, argptr, argc); } ScriptInstance::~ScriptInstance() { } ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton = nullptr; ScriptCodeCompletionCache::ScriptCodeCompletionCache() { singleton = this; } void ScriptLanguage::frame() { } ScriptDebugger *ScriptDebugger::singleton = nullptr; void ScriptDebugger::set_lines_left(int p_left) { lines_left = p_left; } int ScriptDebugger::get_lines_left() const { return lines_left; } void ScriptDebugger::set_depth(int p_depth) { depth = p_depth; } int ScriptDebugger::get_depth() const { return depth; } void ScriptDebugger::insert_breakpoint(int p_line, const StringName &p_source) { if (!breakpoints.has(p_line)) { breakpoints[p_line] = Set<StringName>(); } breakpoints[p_line].insert(p_source); } void ScriptDebugger::remove_breakpoint(int p_line, const StringName &p_source) { if (!breakpoints.has(p_line)) { return; } breakpoints[p_line].erase(p_source); if (breakpoints[p_line].size() == 0) { breakpoints.erase(p_line); } } bool ScriptDebugger::is_breakpoint(int p_line, const StringName &p_source) const { if (!breakpoints.has(p_line)) { return false; } return breakpoints[p_line].has(p_source); } bool ScriptDebugger::is_breakpoint_line(int p_line) const { return breakpoints.has(p_line); } String ScriptDebugger::breakpoint_find_source(const String &p_source) const { return p_source; } void ScriptDebugger::clear_breakpoints() { breakpoints.clear(); } void ScriptDebugger::idle_poll() { } void ScriptDebugger::line_poll() { } void ScriptDebugger::set_break_language(ScriptLanguage *p_lang) { break_lang = p_lang; } ScriptLanguage *ScriptDebugger::get_break_language() const { return break_lang; } ScriptDebugger::ScriptDebugger() { singleton = this; lines_left = -1; depth = -1; break_lang = nullptr; } bool PlaceHolderScriptInstance::set(const StringName &p_name, const Variant &p_value) { if (script->is_placeholder_fallback_enabled()) { return false; } if (values.has(p_name)) { Variant defval; if (script->get_property_default_value(p_name, defval)) { if (defval == p_value) { values.erase(p_name); return true; } } values[p_name] = p_value; return true; } else { Variant defval; if (script->get_property_default_value(p_name, defval)) { if (defval != p_value) { values[p_name] = p_value; } return true; } } return false; } bool PlaceHolderScriptInstance::get(const StringName &p_name, Variant &r_ret) const { if (values.has(p_name)) { r_ret = values[p_name]; return true; } if (constants.has(p_name)) { r_ret = constants[p_name]; return true; } if (!script->is_placeholder_fallback_enabled()) { Variant defval; if (script->get_property_default_value(p_name, defval)) { r_ret = defval; return true; } } return false; } void PlaceHolderScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const { if (script->is_placeholder_fallback_enabled()) { for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { p_properties->push_back(E->get()); } } else { for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) { PropertyInfo pinfo = E->get(); if (!values.has(pinfo.name)) { pinfo.usage |= PROPERTY_USAGE_SCRIPT_DEFAULT_VALUE; } p_properties->push_back(E->get()); } } } Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const { if (values.has(p_name)) { if (r_is_valid) { *r_is_valid = true; } return values[p_name].get_type(); } if (constants.has(p_name)) { if (r_is_valid) { *r_is_valid = true; } return constants[p_name].get_type(); } if (r_is_valid) { *r_is_valid = false; } return Variant::NIL; } void PlaceHolderScriptInstance::get_method_list(List<MethodInfo> *p_list) const { if (script->is_placeholder_fallback_enabled()) { return; } if (script.is_valid()) { script->get_script_method_list(p_list); } } bool PlaceHolderScriptInstance::has_method(const StringName &p_method) const { if (script->is_placeholder_fallback_enabled()) { return false; } if (script.is_valid()) { return script->has_method(p_method); } return false; } void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values) { Set<StringName> new_values; for (const List<PropertyInfo>::Element *E = p_properties.front(); E; E = E->next()) { StringName n = E->get().name; new_values.insert(n); if (!values.has(n) || values[n].get_type() != E->get().type) { if (p_values.has(n)) { values[n] = p_values[n]; } } } properties = p_properties; List<StringName> to_remove; for (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) { if (!new_values.has(E->key())) { to_remove.push_back(E->key()); } Variant defval; if (script->get_property_default_value(E->key(), defval)) { //remove because it's the same as the default value if (defval == E->get()) { to_remove.push_back(E->key()); } } } while (to_remove.size()) { values.erase(to_remove.front()->get()); to_remove.pop_front(); } if (owner && owner->get_script_instance() == this) { owner->_change_notify(); } //change notify constants.clear(); script->get_constants(&constants); } void PlaceHolderScriptInstance::property_set_fallback(const StringName &p_name, const Variant &p_value, bool *r_valid) { if (script->is_placeholder_fallback_enabled()) { Map<StringName, Variant>::Element *E = values.find(p_name); if (E) { E->value() = p_value; } else { values.insert(p_name, p_value); } bool found = false; for (const List<PropertyInfo>::Element *F = properties.front(); F; F = F->next()) { if (F->get().name == p_name) { found = true; break; } } if (!found) { properties.push_back(PropertyInfo(p_value.get_type(), p_name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_SCRIPT_VARIABLE)); } } if (r_valid) { *r_valid = false; // Cannot change the value in either case } } Variant PlaceHolderScriptInstance::property_get_fallback(const StringName &p_name, bool *r_valid) { if (script->is_placeholder_fallback_enabled()) { const Map<StringName, Variant>::Element *E = values.find(p_name); if (E) { if (r_valid) { *r_valid = true; } return E->value(); } E = constants.find(p_name); if (E) { if (r_valid) { *r_valid = true; } return E->value(); } } if (r_valid) { *r_valid = false; } return Variant(); } PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner) : owner(p_owner), language(p_language), script(p_script) { } PlaceHolderScriptInstance::~PlaceHolderScriptInstance() { if (script.is_valid()) { script->_placeholder_erased(this); } }
{'content_hash': '4ba8cee6a1567cf69c261b38b5719e9a', 'timestamp': '', 'source': 'github', 'line_count': 649, 'max_line_length': 160, 'avg_line_length': 29.31895223420647, 'alnum_prop': 0.6492011772125289, 'repo_name': 'ex/godot', 'id': '24f530364c9d769c1ff2174b549f11df671ee0ae', 'size': '19028', 'binary': False, 'copies': '1', 'ref': 'refs/heads/3.5', 'path': 'core/script_language.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AIDL', 'bytes': '1633'}, {'name': 'Batchfile', 'bytes': '26'}, {'name': 'C', 'bytes': '1045182'}, {'name': 'C#', 'bytes': '1061492'}, {'name': 'C++', 'bytes': '39315087'}, {'name': 'CMake', 'bytes': '606'}, {'name': 'GAP', 'bytes': '62'}, {'name': 'GDScript', 'bytes': '323212'}, {'name': 'GLSL', 'bytes': '836846'}, {'name': 'Java', 'bytes': '595274'}, {'name': 'JavaScript', 'bytes': '194742'}, {'name': 'Kotlin', 'bytes': '84098'}, {'name': 'Makefile', 'bytes': '1421'}, {'name': 'Objective-C', 'bytes': '20550'}, {'name': 'Objective-C++', 'bytes': '365306'}, {'name': 'PowerShell', 'bytes': '2713'}, {'name': 'Python', 'bytes': '475722'}, {'name': 'Shell', 'bytes': '30899'}]}
FROM balenalib/vab820-quad-fedora:30-run ENV GO_VERSION 1.16 # gcc for cgo RUN dnf install -y \ gcc-c++ \ gcc \ git \ && dnf clean all RUN mkdir -p /usr/local/go \ && curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-armv7hf.tar.gz" \ && echo "5d2c637632fc23139c992e7f5adce1e46bccebd5a43fc90f797050ae71f46ab9 go$GO_VERSION.linux-armv7hf.tar.gz" | sha256sum -c - \ && tar -xzf "go$GO_VERSION.linux-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \ && rm -f go$GO_VERSION.linux-armv7hf.tar.gz ENV GOROOT /usr/local/go ENV GOPATH /go ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH" WORKDIR $GOPATH 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@golang" \ && 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 v7 \nOS: Fedora 30 \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.16 \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/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
{'content_hash': '468c4b3506aad21a429a5cb11c4ec313', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 667, 'avg_line_length': 54.63157894736842, 'alnum_prop': 0.7182080924855492, 'repo_name': 'nghiant2710/base-images', 'id': '9e845e8de76dd611fc1db65025e990ed20e2bbb2', 'size': '2097', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/golang/vab820-quad/fedora/30/1.16/run/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]}
CSS3-ROCKS ========== Create powerful apps with just HTML5 and CSS3. ------------------------------------------------------------ CSS3-ROCKS is a CSS3 template with all tags for css3, and have a support for mobile WebKit browsers like iPhone, Nexus One, and Palm Pre. -CSS3 page transitions, including 3d flip - Easily allow apps to run in fullscreen mode with custom icons and startup screens Credits ------- Created by [Wylkon Cardoso](http://www.wylkon.com.br). (c) 2011 by CSS3-ROCKS project members. See LICENSE.txt for license.
{'content_hash': '0fb40aefada38f87ccdef89d02f7ee4e', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 137, 'avg_line_length': 30.0, 'alnum_prop': 0.6611111111111111, 'repo_name': 'Wylkon/CSS3-ROCKS', 'id': '872f88fb940f3c71e04ae5e7875738614c002198', 'size': '540', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': []}
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Control.Exception (ErrorCall (..), handle) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B8 import Data.FileEmbed (injectWith) import Data.List (isInfixOf) import Universum main :: IO () main = do (hash, progs) <- parseArgs mapM_ (setGitRev hash) progs setGitRev :: ByteString -> FilePath -> IO () setGitRev hash prog = do putStr $ "Setting gitrev of " <> prog <> " ... " bs <- B8.readFile prog injectWith' "gitrev" hash bs >>= \case Right bs' -> do B8.writeFile prog bs' B8.putStrLn "OK" exitSuccess Left "" -> do B8.putStrLn $ "Failed setting gitrev to \"" <> hash <> "\"" exitFailure Left msg | "Size is: \"\"" `isInfixOf` msg -> do -- Ignore programs without a gitrev injected B8.putStrLn "File does not have dummySpace." exitSuccess Left msg -> do putStrLn msg exitFailure -- | Work around annoying use of error function in file-embed. injectWith' :: ByteString -> ByteString -> ByteString -> IO (Either String ByteString) injectWith' postfix toInj orig = handle (pure . toLeft) (toRight <$> evaluateNF inj) where inj = injectWith postfix toInj orig toRight (Just a) = Right a toRight Nothing = Left "" toLeft (ErrorCall msg) = Left msg parseArgs :: IO (ByteString, [FilePath]) parseArgs = getArgs >>= \case (rev:prog:progs) -> pure (B8.pack rev, (prog:progs)) _ -> die "usage: set-git-rev REV PROG [PROGS...]" >> exitFailure
{'content_hash': '392818e61da2939fe312e15f5aa93442', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 86, 'avg_line_length': 33.15686274509804, 'alnum_prop': 0.6232998225901834, 'repo_name': 'input-output-hk/cardano-sl', 'id': '472f8a1b89411324de26a8a97bef34edfe6de341', 'size': '1691', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'scripts/set-git-rev/set-git-rev.hs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '539'}, {'name': 'CSS', 'bytes': '54967'}, {'name': 'HTML', 'bytes': '217850'}, {'name': 'Haskell', 'bytes': '6587947'}, {'name': 'JavaScript', 'bytes': '47584'}, {'name': 'Makefile', 'bytes': '6928'}, {'name': 'Nix', 'bytes': '1600437'}, {'name': 'PureScript', 'bytes': '311942'}, {'name': 'Python', 'bytes': '36838'}, {'name': 'Shell', 'bytes': '76693'}, {'name': 'TSQL', 'bytes': '3275'}]}
package com.nurkiewicz.lazyseq; import org.testng.annotations.Test; import static com.nurkiewicz.lazyseq.LazySeq.empty; import static com.nurkiewicz.lazyseq.LazySeq.of; import static com.nurkiewicz.lazyseq.samples.Seqs.primes; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; /** * @author Tomasz Nurkiewicz * @since 5/12/13, 3:35 PM */ public class LazySeqStartsWithTest extends AbstractBaseTestCase { @Test public void emptySeqStartsWithEmptySeq() throws Exception { assertThat(empty().startsWith(empty())).isTrue(); } @Test public void emptySeqDoesNotStartWithNonEmptySeq() throws Exception { final LazySeq<Integer> empty = empty(); assertThat(empty.startsWith(of(1))).isFalse(); assertThat(empty.startsWith(of(1, 2))).isFalse(); } @Test public void everySeqStartsWithEmptySeq() throws Exception { assertThat(of(1).startsWith(empty())).isTrue(); assertThat(of(1, 2).startsWith(empty())).isTrue(); } @Test public void seqStartsWithSelf() throws Exception { final LazySeq<Character> seq = of('a', 'b', 'c'); assertThat(seq.startsWith(seq)).isTrue(); } @Test public void seqStartsWithPrefix() throws Exception { final LazySeq<Character> seq = of('a', 'b', 'c', 'd'); assertThat(seq.startsWith(asList('a'))).isTrue(); assertThat(seq.startsWith(asList('a', 'b', 'c'))).isTrue(); } @Test public void seqNotStartsWithLongerPrefix() throws Exception { final LazySeq<Character> seq = of('a', 'b', 'c'); assertThat(seq.startsWith(asList('a', 'b', 'c', 'd'))).isFalse(); } @Test public void infiniteSeqStartsWithEmpty() throws Exception { final LazySeq<Integer> primes = primes(); assertThat(primes.startsWith(empty())).isTrue(); } @Test public void infiniteSeqStartsWithFixedSeq() throws Exception { final LazySeq<Integer> primes = primes(); assertThat(primes.startsWith(asList(2, 3, 5, 7))).isTrue(); } @Test public void infiniteSeqNotStartsWithWrongPrefix() throws Exception { final LazySeq<Integer> primes = primes(); assertThat(primes.startsWith(asList(2, 3, 4))).isFalse(); } }
{'content_hash': 'c1289b787034c5c981132854f3320c9a', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 69, 'avg_line_length': 26.734177215189874, 'alnum_prop': 0.7211174242424242, 'repo_name': 'nurkiewicz/LazySeq', 'id': '30c89ec91ec1f60c4ef7d59322236b6e04547528', 'size': '2112', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/nurkiewicz/lazyseq/LazySeqStartsWithTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '145566'}]}
<div class="container project-view"> <div class="row"> <div class="col-md-12 project-images"> <img src="images/portfolio/livingroom16.png" alt="livingroom16" class="img-responsive" /> </div> </div> </div>
{'content_hash': 'f1a150920c8d431deb5ccb67e766ce3c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 101, 'avg_line_length': 31.25, 'alnum_prop': 0.58, 'repo_name': 'mattkfpc/nfdrapery', 'id': 'fac0392217b5364f05719ec7ce11483f0fdcf098', 'size': '250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'project-livingroom16.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '437954'}, {'name': 'HTML', 'bytes': '289789'}, {'name': 'JavaScript', 'bytes': '618699'}, {'name': 'PHP', 'bytes': '808'}]}
package org.openntf.domino.nsfdata.structs.cd; import org.openntf.domino.nsfdata.structs.SIG; import org.openntf.domino.nsfdata.structs.WSIG; /** * Text in a rich-text field can have the "Pass-Thru HTML" attribute. Pass-through HTML text is not translated to the Domino rich text * format. Pass-through HTML text is marked by CDHTMLBEGIN and CDHTMLEND records. (editods.h) * * @since Lotus Notes/Domino 4.6 * */ public class CDHTMLEND extends CDRecord { public final WSIG Header = inner(new WSIG()); public final Unsigned8[] Spares = array(new Unsigned8[4]); @Override public SIG getHeader() { return Header; } }
{'content_hash': '97df195737ab5ab0a4fe49465f14cd89', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 134, 'avg_line_length': 27.47826086956522, 'alnum_prop': 0.740506329113924, 'repo_name': 'rPraml/org.openntf.domino', 'id': 'e36721c387a3f1f1cd3ad6f36850f5b6cb575f04', 'size': '632', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'domino/design-impl/src/main/java/org/openntf/domino/nsfdata/structs/cd/CDHTMLEND.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2051'}, {'name': 'CSS', 'bytes': '952'}, {'name': 'HTML', 'bytes': '17439'}, {'name': 'Java', 'bytes': '7812097'}, {'name': 'JavaScript', 'bytes': '1950'}, {'name': 'Ragel in Ruby Host', 'bytes': '2783'}, {'name': 'Shell', 'bytes': '1080'}, {'name': 'XPages', 'bytes': '105402'}, {'name': 'XSLT', 'bytes': '15719'}]}
'use strict'; var BaseModel = require('model-toolkit').BaseModel; module.exports = class OrderType extends BaseModel{ constructor(source){ super('order-type', '1.0.0'); this.code = ''; this.name = ''; this.remark = ''; this.copy(source); } };
{'content_hash': '062a17cc269ec9d76f3af4f678ac52fc', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 52, 'avg_line_length': 22.53846153846154, 'alnum_prop': 0.5665529010238908, 'repo_name': 'danliris/dl-models', 'id': '7e7b8adacf33b6f8c55f66769e740de4be8e7810', 'size': '293', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/master/order-type.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '369982'}]}
package org.camunda.bpm.security; /** * * @author nico.rehwaldt */ public class SecurityException extends RuntimeException { private static final long serialVersionUID = 1L; public SecurityException(String message) { super(message); } public SecurityException(Throwable cause) { super(cause); } public SecurityException(String message, Throwable cause) { super(message, cause); } }
{'content_hash': 'c5143d94964100f856b59eeed7b92070', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 61, 'avg_line_length': 19.0, 'alnum_prop': 0.715311004784689, 'repo_name': '1and1/camunda-bpm-platform', 'id': 'dcded4cd6151d5e01690a33f9928b6b137c6d815', 'size': '418', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'webapps/cycle/cycle/src/main/java/org/camunda/bpm/security/SecurityException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3524'}, {'name': 'CSS', 'bytes': '41455'}, {'name': 'HTML', 'bytes': '207609'}, {'name': 'Java', 'bytes': '8707800'}, {'name': 'JavaScript', 'bytes': '636111'}, {'name': 'Shell', 'bytes': '3423'}, {'name': 'XSLT', 'bytes': '13061'}]}
title: Calculating Conditional Probability localeTitle: Calculando Probabilidade Condicional --- ## Calculando Probabilidade Condicional Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/calculating-conditional-probability/index.md) . [Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) . #### Mais Informações:
{'content_hash': '6b4edf861196ecd7a1b3a07b3e533c5f', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 176, 'avg_line_length': 49.8, 'alnum_prop': 0.8112449799196787, 'repo_name': 'pahosler/freecodecamp', 'id': 'dd893026570b5103fbcc7740c072c6ed2fe1056d', 'size': '510', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'guide/portuguese/mathematics/calculating-conditional-probability/index.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '35491'}, {'name': 'HTML', 'bytes': '17600'}, {'name': 'JavaScript', 'bytes': '777274'}]}
package com.vk.api.sdk.exceptions; public class ApiGroupNotInClubException extends ApiException { public ApiGroupNotInClubException(String message) { super(701, "User should be in club", message); } }
{'content_hash': '5cd6eec2b9ed8625b9d1efb62f2d2c3b', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 31.142857142857142, 'alnum_prop': 0.7431192660550459, 'repo_name': 'kokorin/vk-java-sdk', 'id': '38d82f0ca89e64fb9b01fb8ec2c7c39303b5ae36', 'size': '218', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'sdk/src/main/java/com/vk/api/sdk/exceptions/ApiGroupNotInClubException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2634022'}]}
{-# LANGUAGE LambdaCase, QuasiQuotes, OverloadedStrings #-} module PrettySpec where import qualified Data.Text as Text import Test.Hspec import Test.QuickCheck import Grin.Pretty import Grin.Grin import Grin.TH import Grin.Parse import Test.Test import Test.Assertions runTests :: IO () runTests = hspec spec spec :: Spec spec = do describe "external defintions" $ do it "primop + ffi" $ do let sample = [prog| primop effectful _prim_string_print :: T_String -> T_Unit _prim_read_string :: T_String "newArrayArray#" :: {"Int#"} -> {"State#" %s} -> {"GHC.Prim.Unit#" {"MutableArrayArray#" %s}} primop pure _prim_string_concat :: T_String -> T_String -> T_String ffi pure newArrayArray :: {Int} -> {State %s} -> {GHC.Prim.Unit {MutableArrayArray %s}} grinMain = pure () |] let before = parseGrin "" (Text.pack . show $ (PP $ prettyProgram WithExternals sample)) after = Program [ External { eName = "_prim_string_print" , eRetType = TySimple T_Unit , eArgsType = [ TySimple T_String ] , eEffectful = True , eKind = PrimOp } , External { eName = "_prim_read_string" , eRetType = TySimple T_String , eArgsType = [] , eEffectful = True , eKind = PrimOp } , External { eName = "newArrayArray#" , eRetType = TyCon "GHC.Prim.Unit#" [ TyCon "MutableArrayArray#" [ TyVar "s" ] ] , eArgsType = [ TyCon "Int#" [] , TyCon "State#" [ TyVar "s" ] ] , eEffectful = True , eKind = PrimOp } , External { eName = "_prim_string_concat" , eRetType = TySimple T_String , eArgsType = [ TySimple T_String , TySimple T_String ] , eEffectful = False , eKind = PrimOp } , External { eName = "newArrayArray" , eRetType = TyCon "GHC.Prim.Unit" [ TyCon "MutableArrayArray" [ TyVar "s" ] ] , eArgsType = [ TyCon "Int" [] , TyCon "State" [ TyVar "s" ] ] , eEffectful = False , eKind = FFI } ] [ Def "grinMain" [] ( SReturn Unit ) ] (fmap PP before) `shouldBe` (Right $ PP after)
{'content_hash': '26b4495de0ca9b41b360afef6c5c0ee8', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 103, 'avg_line_length': 31.123595505617978, 'alnum_prop': 0.45018050541516247, 'repo_name': 'andorp/grin', 'id': '16a3869c77e66adbe0d6a318d51127b8534a58e7', 'size': '2770', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'grin/test/PrettySpec.hs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '361'}, {'name': 'Haskell', 'bytes': '356035'}, {'name': 'Idris', 'bytes': '1026'}, {'name': 'Roff', 'bytes': '991'}, {'name': 'Shell', 'bytes': '66'}]}
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > String.prototype.split(separator, limit): i) can be transferred to other kinds of objects for use as a method. separator and limit can be any kinds of object since: ii) if separator is not RegExp ToString(separator) performs and iii) ToInteger(limit) performs es5id: 15.5.4.14_A1_T5 description: > Argument is null, and instance is function call that returned string ---*/ //since ToString(null) evaluates to "null" split(null) evaluates to split("null",0) var __split = function(){return "gnulluna"}().split(null); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if (typeof __split !== "object") { $ERROR('#1: __split = function(){return "gnulluna"}().split(null); typeof __split === "object". Actual: '+typeof __split ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (__split.constructor !== Array) { $ERROR('#2: __split = function(){return "gnulluna"}().split(null); __split.constructor === Array. Actual: '+__split.constructor ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#3 if (__split.length !== 2) { $ERROR('#3: __split = function(){return "gnulluna"}().split(null); __split.length === 2. Actual: '+__split.length ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#4 if (__split[0] !== "g") { $ERROR('#4: __split = function(){return "gnulluna"}().split(null); __split[0] === "g". Actual: '+__split[0] ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#5 if (__split[1] !== "una") { $ERROR('#5: __split = function(){return "gnulluna"}().split(null); __split[1] === "una". Actual: '+__split[1] ); } // //////////////////////////////////////////////////////////////////////////////
{'content_hash': 'c4877a64649107146fdf15bb45054a1a', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 132, 'avg_line_length': 40.03448275862069, 'alnum_prop': 0.4125753660637382, 'repo_name': 'baslr/ArangoDB', 'id': '6d8b15f3ebbaefc9c8c6aea23236ed1752ae8653', 'size': '2322', 'binary': False, 'copies': '4', 'ref': 'refs/heads/3.1-silent', 'path': '3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/String/prototype/split/S15.5.4.14_A1_T5.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '391227'}, {'name': 'Awk', 'bytes': '4272'}, {'name': 'Batchfile', 'bytes': '62892'}, {'name': 'C', 'bytes': '7932707'}, {'name': 'C#', 'bytes': '96430'}, {'name': 'C++', 'bytes': '284363933'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CMake', 'bytes': '681903'}, {'name': 'CSS', 'bytes': '1036656'}, {'name': 'CWeb', 'bytes': '174166'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '259402'}, {'name': 'Emacs Lisp', 'bytes': '14637'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Groovy', 'bytes': '131'}, {'name': 'HTML', 'bytes': '2318016'}, {'name': 'Java', 'bytes': '2325801'}, {'name': 'JavaScript', 'bytes': '67878359'}, {'name': 'LLVM', 'bytes': '24129'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'Lua', 'bytes': '16189'}, {'name': 'M4', 'bytes': '600550'}, {'name': 'Makefile', 'bytes': '509612'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'NSIS', 'bytes': '28404'}, {'name': 'Objective-C', 'bytes': '19321'}, {'name': 'Objective-C++', 'bytes': '2503'}, {'name': 'PHP', 'bytes': '98503'}, {'name': 'Pascal', 'bytes': '145688'}, {'name': 'Perl', 'bytes': '720157'}, {'name': 'Perl 6', 'bytes': '9918'}, {'name': 'Python', 'bytes': '5859911'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'R', 'bytes': '5123'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Roff', 'bytes': '1010686'}, {'name': 'Ruby', 'bytes': '922159'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Scheme', 'bytes': '10604'}, {'name': 'Shell', 'bytes': '511077'}, {'name': 'Swift', 'bytes': '116'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'Vim script', 'bytes': '4075'}, {'name': 'Visual Basic', 'bytes': '11568'}, {'name': 'XSLT', 'bytes': '551977'}, {'name': 'Yacc', 'bytes': '53005'}]}
{% load i18n sizeformat %} {% load url from future %} <h3>{% trans "Job Overview" %}</h3> <div class="status row detail"> <dl class="dl-horizontal"> <dt>{% trans "Status" %}</dt> <dd>{{ job_execution.info.status }}</dd> <dt>{% trans "ID" %}</dt> <dd>{{ job_execution.id }}</dd> <dt>{% trans "Job Template" %}</dt> <dd><a href="{% url 'horizon:project:data_processing.jobs:details' job_execution.job_id %}">{{ object_names.job_name }}</a></dd> {% if job_execution.input_id %} <dt>{% trans "Input Data Source" %}</dt> <dd><a href="{% url 'horizon:project:data_processing.data_sources:details' job_execution.input_id %}">{{ object_names.input_name }}</a> ({{ object_names.input_url }})</dd> {% endif %} {% if job_execution.output_id %} <dt>{% trans "Output Data Source" %}</dt> <dd><a href="{% url 'horizon:project:data_processing.data_sources:details' job_execution.output_id %}">{{ object_names.output_name }}</a> ({{ object_names.output_url }})</dd> {% endif %} <dt>{% trans "Cluster" %}</dt> <dd><a href="{% url 'horizon:project:data_processing.clusters:details' job_execution.cluster_id %}">{{ object_names.cluster_name }}</a></dd> <dt>{% trans "Last Updated" %}</dt> <dd>{{ job_execution.updated_at }}</dd> <dt>{% trans "Started" context "Start time" %}</dt> <dd>{{ job_execution.start_time }}</dd> <dt>{% trans "Ended" context "End time" %}</dt> <dd>{{ job_execution.end_time }}</dd> <dt>{% trans "Return Code" %}</dt> <dd>{{ job_execution.return_code }}</dd> <dt>{% trans "Oozie Job ID" %}</dt> <dd>{{ job_execution.oozie_job_id }}</dd> <dt>{% trans "Created" context "Created time" %}</dt> <dd>{{ job_execution.created_at }}</dd> <dt>{% trans "Job Configuration" %}</dt> <dd>{% for group, vals in job_execution.job_configs.iteritems %} <ul><li><span style="font-weight:bold">{% blocktrans %}{{ group }}:{% endblocktrans %}</span> {% if group == "args" %} <ul>{% for val in vals %} <li>{{ val }}</li> {% endfor %}</ul> {% else %} <ul>{% for key, val in vals.iteritems %} <li>{{ key }} = {{ val }}</li> {% endfor %}</ul> {% endif %} </li></ul> {% endfor %} </dd> </dl> </div>
{'content_hash': 'd2ecf51fa10b032461d8fd3973a40314', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 180, 'avg_line_length': 49.869565217391305, 'alnum_prop': 0.5540540540540541, 'repo_name': 'philoniare/horizon', 'id': '256ced603e9fb504da36ff4447d7852fad8884b0', 'size': '2294', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'openstack_dashboard/contrib/sahara/content/data_processing/job_executions/templates/data_processing.job_executions/_details.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '106071'}, {'name': 'HTML', 'bytes': '518098'}, {'name': 'JavaScript', 'bytes': '973924'}, {'name': 'Makefile', 'bytes': '588'}, {'name': 'Python', 'bytes': '4930308'}, {'name': 'Shell', 'bytes': '18658'}]}
/*************************************************************************/ /* ray_shape.h */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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. */ /*************************************************************************/ #ifndef RAY_SHAPE_H #define RAY_SHAPE_H #include "scene/resources/shape.h" class RayShape : public Shape { GDCLASS(RayShape, Shape); float length; protected: static void _bind_methods(); virtual void _update_shape(); virtual Vector<Vector3> _gen_debug_mesh_lines(); public: void set_length(float p_length); float get_length() const; RayShape(); }; #endif // RAY_SHAPE_H
{'content_hash': '4e1ddcf5e8cc685fc5d608a2ca6a528d', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 75, 'avg_line_length': 51.74, 'alnum_prop': 0.48318515655199074, 'repo_name': 'MrMaidx/godot', 'id': '5a17e9414eaf8f0efadeb6d10d7ce2cf157aaf83', 'size': '2587', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'scene/resources/ray_shape.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '50004'}, {'name': 'C++', 'bytes': '16763326'}, {'name': 'HTML', 'bytes': '10302'}, {'name': 'Java', 'bytes': '497034'}, {'name': 'Makefile', 'bytes': '451'}, {'name': 'Objective-C', 'bytes': '2644'}, {'name': 'Objective-C++', 'bytes': '146351'}, {'name': 'Python', 'bytes': '264258'}, {'name': 'Shell', 'bytes': '11105'}]}
.. _debugging: .. index:: Bugs, Debugging ========= Debugging ========= .. contents:: A few tips for debugging your casper scripts: :local: Use the :index:`verbose` mode ----------------------------- By default & by design, a ``Casper`` instance won't print anything to the console. This can be very limitating & frustrating when creating or debugging scripts, so a good practice is to always start coding a script using these :index:`settings`:: var casper = require('casper').create({ verbose: true, logLevel: "debug" }); The ``verbose`` setting will tell Casper to write every logged message at the ``logLevel`` logging level onto the standard output, so you'll be able to trace every step made. .. warning:: Output will then be pretty verbose, and will potentially display sensitive informations onto the console. **Use with care on production.** Hook in the deep using :index:`events` -------------------------------------- :doc:`Events <events-filters>` are a very powerful features of CasperJS, and you should probably give it a look if you haven't already. Some interesting events you may eventually use to debug your scripts: - The ``http.status.XXX`` event will be emitted everytime a resource is sent with the `HTTP code <http://en.wikipedia.org/wiki/List_of_HTTP_status_codes>`_ corresponding to ``XXX``; - The ``remote.alert`` everytime an ``alert()`` call is performed client-side; - ``remote.message`` everytime a message is sent to the client-side console; - ``step.added`` everytime a step is added to the stack; - etc… Listening to an event is dead easy:: casper.on('http.status.404', function(resource) { this.log('Hey, this one is 404: ' + resource.url, 'warning'); }); Ensure to check the :ref:`full list <events_list>` of all the other available events. .. _debugging_dump: Dump serialized values to the console ------------------------------------- Sometimes it's helpful to inspect a variable, especially Object contents. The :ref:`utils_dump() <utils_dump>` function can achieve just that:: require('utils').dump({ foo: { bar: 42 }, }); .. note:: :ref:`utils_dump() <utils_dump>` won't be able to serialize function nor complex cyclic structures though. Localize yourself in modules ---------------------------- .. warning:: .. deprecated:: 1.1 As of 1.1, CasperJS uses PhantomJS' builtin `require` and won't expose the `__file__` variable anymore. If you're creating Casper modules, a cool thing to know is that there's a special built-in variable available in every module, ``__file__``, which contains the absolute path to current javascript file (the module file). Name your closures ------------------ Probably one of the most easy but effective best practice, always name your closures: **Hard to track:** :: casper.start('http://foo.bar/', function() { this.evaluate(function() { // ... }); }); **Easier:** :: casper.start('http://foo.bar/', function afterStart() { this.evaluate(function evaluateStuffAfterStart() { // ... }); }); That way, everytime one is failing, its name will be printed out in the :index:`stack trace`, **so you can more easily locate it within your code**. .. note:: This one also applies for all your other Javascript works, of course ;)
{'content_hash': 'c8bd86ad6ddc715e0767efc76d25ccd6', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 246, 'avg_line_length': 30.666666666666668, 'alnum_prop': 0.6512925969447708, 'repo_name': 'spektraldevelopment/spektraltools', 'id': '6cbbb4f8c9c5a8b2be452ba8e3d1f47b570cf9d4', 'size': '3406', 'binary': False, 'copies': '61', 'ref': 'refs/heads/master', 'path': 'node_modules/grunt-casper/node_modules/casperjs/docs/debugging.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '184705'}]}
<?php /** * A PHPUnit test case wrapping the Mustache Spec. * * @group mustache-spec * @group functional */ class Mustache_Test_Functional_MustacheSpecTest extends Mustache_Test_SpecTestCase { /** * For some reason data providers can't mark tests skipped, so this test exists * simply to provide a 'skipped' test if the `spec` submodule isn't initialized. */ public function testSpecInitialized() { if (!file_exists(dirname(__FILE__) . '/../../../../vendor/spec/specs/')) { $this->markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); } } /** * @group comments * @dataProvider loadCommentSpec */ public function testCommentSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadCommentSpec() { return $this->loadSpec('comments'); } /** * @group delimiters * @dataProvider loadDelimitersSpec */ public function testDelimitersSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadDelimitersSpec() { return $this->loadSpec('delimiters'); } /** * @group interpolation * @dataProvider loadInterpolationSpec */ public function testInterpolationSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadInterpolationSpec() { return $this->loadSpec('interpolation'); } /** * @group inverted * @group inverted-sections * @dataProvider loadInvertedSpec */ public function testInvertedSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadInvertedSpec() { return $this->loadSpec('inverted'); } /** * @group partials * @dataProvider loadPartialsSpec */ public function testPartialsSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadPartialsSpec() { return $this->loadSpec('partials'); } /** * @group sections * @dataProvider loadSectionsSpec */ public function testSectionsSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); $this->assertEquals($expected, $template->render($data), $desc); } public function loadSectionsSpec() { return $this->loadSpec('sections'); } }
{'content_hash': '7420f03b18abed3f9e1704d1131649c3', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 113, 'avg_line_length': 27.359649122807017, 'alnum_prop': 0.6152613016992626, 'repo_name': 'prnvrna/ThaalJS', 'id': 'bdf851aef5b300a465eadf1118164b9a693d2e24', 'size': '3328', 'binary': False, 'copies': '23', 'ref': 'refs/heads/master', 'path': 'thaaljs.php.dev/library/third-party/mustache.php/test/Mustache/Test/Functional/MustacheSpecTest.php', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '499'}, {'name': 'JavaScript', 'bytes': '2969'}, {'name': 'PHP', 'bytes': '24704'}, {'name': 'Python', 'bytes': '165'}, {'name': 'Rust', 'bytes': '451'}, {'name': 'Shell', 'bytes': '5216'}]}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using System; using Xunit; using Microsoft.CodeAnalysis.Test.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.Source { public sealed class ExpressionBodiedPropertyTests : CSharpTestBase { [Fact(Skip = "973907")] public void Syntax01() { // Language feature enabled by default var comp = CreateCompilation(@" class C { public int P => 1; }"); comp.VerifyDiagnostics(); } [Fact] public void Syntax02() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P { get; } => 1; }"); comp.VerifyDiagnostics( // (4,5): error CS8056: Properties cannot combine accessor lists with expression bodies. // public int P { get; } => 1; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int P { get; } => 1;").WithLocation(4, 5) ); } [Fact] public void Syntax03() { var comp = CreateCompilation(@" interface C { int P => 1; }", parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetStandardLatest); comp.VerifyDiagnostics( // (4,14): error CS8652: The feature 'default interface implementation' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // int P => 1; Diagnostic(ErrorCode.ERR_FeatureInPreview, "1").WithArguments("default interface implementation").WithLocation(4, 14) ); } [Fact] public void Syntax04() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,28): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 28)); } [Fact] public void Syntax05() { var comp = CreateCompilationWithMscorlib45(@" class C { public abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,29): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 29), // (4,29): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract class 'C' // public abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "1").WithArguments("C.P.get", "C").WithLocation(4, 29)); } [Fact] public void Syntax06() { var comp = CreateCompilationWithMscorlib45(@" abstract class C { abstract int P => 1; }"); comp.VerifyDiagnostics( // (4,17): error CS0621: 'C.P': virtual or abstract members cannot be private // abstract int P => 1; Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("C.P").WithLocation(4, 17), // (4,22): error CS0500: 'C.P.get' cannot declare a body because it is marked abstract // abstract int P => 1; Diagnostic(ErrorCode.ERR_AbstractHasBody, "1").WithArguments("C.P.get").WithLocation(4, 22)); } [Fact] public void Syntax07() { // The '=' here parses as part of the expression body, not the property var comp = CreateCompilationWithMscorlib45(@" class C { public int P => 1 = 2; }"); comp.VerifyDiagnostics( // (4,21): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // public int P => 1 = 2; Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(4, 21)); } [Fact] public void Syntax08() { CreateCompilationWithMscorlib45(@" interface I { int P { get; }; }").VerifyDiagnostics( // (4,19): error CS1597: Semicolon after method or accessor block is not valid // int P { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 19)); } [Fact] public void Syntax09() { CreateCompilationWithMscorlib45(@" class C { int P => 2 }").VerifyDiagnostics( // (4,15): error CS1002: ; expected // int P => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 15)); } [Fact] public void Syntax10() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i] Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax11() { CreateCompilationWithMscorlib45(@" interface I { int this[int i]; }").VerifyDiagnostics( // (4,20): error CS1514: { expected // int this[int i]; Diagnostic(ErrorCode.ERR_LbraceExpected, ";").WithLocation(4, 20), // (4,20): error CS1014: A get or set accessor expected // int this[int i]; Diagnostic(ErrorCode.ERR_GetOrSetExpected, ";").WithLocation(4, 20), // (5,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 2), // (4,9): error CS0548: 'I.this[int]': property or indexer must have at least one accessor // int this[int i]; Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("I.this[int]").WithLocation(4, 9)); } [Fact] public void Syntax12() { CreateCompilationWithMscorlib45(@" interface I { int this[int i] { get; }; }").VerifyDiagnostics( // (4,29): error CS1597: Semicolon after method or accessor block is not valid // int this[int i] { get; }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 29)); } [Fact] public void Syntax13() { // End the property declaration at the semicolon after the accessor list CreateCompilationWithMscorlib45(@" class C { int P { get; set; }; => 2; }").VerifyDiagnostics( // (4,24): error CS1597: Semicolon after method or accessor block is not valid // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(4, 24), // (4,26): error CS1519: Invalid token '=>' in class, struct, or interface member declaration // int P { get; set; }; => 2; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(4, 26)); } [Fact] public void Syntax14() { CreateCompilationWithMscorlib45(@" class C { int this[int i] => 2 }").VerifyDiagnostics( // (4,25): error CS1002: ; expected // int this[int i] => 2 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(4, 25)); } [Fact] public void LambdaTest01() { var comp = CreateCompilationWithMscorlib45(@" using System; class C { public Func<int, Func<int, int>> P => x => y => x + y; }"); comp.VerifyDiagnostics(); } [Fact] public void SimpleTest() { var text = @" class C { public int P => 2 * 2; public int this[int i, int j] => i * j * P; }"; var comp = CreateCompilationWithMscorlib45(text); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); var indexer = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(indexer.SetMethod); Assert.NotNull(indexer.GetMethod); Assert.False(indexer.GetMethod.IsImplicitlyDeclared); Assert.True(indexer.IsExpressionBodied); Assert.True(indexer.IsIndexer); Assert.Equal(2, indexer.ParameterCount); var i = indexer.Parameters[0]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("i", i.Name); var j = indexer.Parameters[1]; Assert.Equal(SpecialType.System_Int32, i.Type.SpecialType); Assert.Equal("j", j.Name); } [Fact] public void Override01() { var comp = CreateCompilationWithMscorlib45(@" class B { public virtual int P { get; set; } } class C : B { public override int P => 1; }").VerifyDiagnostics(); } [Fact] public void Override02() { CreateCompilationWithMscorlib45(@" class B { public int P => 10; public int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics( // (10,25): error CS0506: 'C.this[int]': cannot override inherited member 'B.this[int]' because it is not marked virtual, abstract, or override // public override int this[int i] => i * 2; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "this").WithArguments("C.this[int]", "B.this[int]").WithLocation(10, 25), // (9,25): error CS0506: 'C.P': cannot override inherited member 'B.P' because it is not marked virtual, abstract, or override // public override int P => 20; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "P").WithArguments("C.P", "B.P").WithLocation(9, 25)); } [Fact] public void Override03() { CreateCompilationWithMscorlib45(@" class B { public virtual int P => 10; public virtual int this[int i] => i; } class C : B { public override int P => 20; public override int this[int i] => i * 2; }").VerifyDiagnostics(); } [Fact] public void VoidExpression() { var comp = CreateCompilationWithMscorlib45(@" class C { public void P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,17): error CS0547: 'C.P': property or indexer cannot have void type // public void P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "P").WithArguments("C.P").WithLocation(4, 17)); } [Fact] public void VoidExpression2() { var comp = CreateCompilationWithMscorlib45(@" class C { public int P => System.Console.WriteLine(""goo""); }").VerifyDiagnostics( // (4,21): error CS0029: Cannot implicitly convert type 'void' to 'int' // public int P => System.Console.WriteLine("goo"); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"System.Console.WriteLine(""goo"")").WithArguments("void", "int").WithLocation(4, 21)); } [Fact] public void InterfaceImplementation01() { var comp = CreateCompilationWithMscorlib45(@" interface I { int P { get; } string Q { get; } } internal interface J { string Q { get; } } internal interface K { decimal D { get; } } class C : I, J, K { public int P => 10; string I.Q { get { return ""goo""; } } string J.Q { get { return ""bar""; } } public decimal D { get { return P; } } }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var i = global.GetTypeMember("I"); var j = global.GetTypeMember("J"); var k = global.GetTypeMember("K"); var c = global.GetTypeMember("C"); var iP = i.GetMember<SourcePropertySymbol>("P"); var prop = c.GetMember<SourcePropertySymbol>("P"); Assert.True(prop.IsReadOnly); var implements = prop.ContainingType.FindImplementationForInterfaceMember(iP); Assert.Equal(prop, implements); prop = (SourcePropertySymbol)c.GetProperty("I.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = (SourcePropertySymbol)c.GetProperty("J.Q"); Assert.True(prop.IsReadOnly); Assert.True(prop.IsExplicitInterfaceImplementation); prop = c.GetMember<SourcePropertySymbol>("D"); Assert.True(prop.IsReadOnly); } [ClrOnlyFact] public void Emit01() { var comp = CreateCompilationWithMscorlib45(@" abstract class A { protected abstract string Z { get; } } abstract class B : A { protected sealed override string Z => ""goo""; protected abstract string Y { get; } } class C : B { public const int X = 2; public static int P => C.X * C.X; public int Q => X; private int R => P * Q; protected sealed override string Y => Z + R; public int this[int i] => R + i; public static void Main() { System.Console.WriteLine(C.X); System.Console.WriteLine(C.P); var c = new C(); System.Console.WriteLine(c.Q); System.Console.WriteLine(c.R); System.Console.WriteLine(c.Z); System.Console.WriteLine(c.Y); System.Console.WriteLine(c[10]); } }", options: TestOptions.ReleaseExe.WithMetadataImportOptions(MetadataImportOptions.Internal)); var verifier = CompileAndVerify(comp, expectedOutput: @"2 4 2 8 goo goo8 18"); } [ClrOnlyFact] public void AccessorInheritsVisibility() { var comp = CreateCompilationWithMscorlib45(@" class C { private int P => 1; private int this[int i] => i; }", options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); Action<ModuleSymbol> srcValidator = m => { var c = m.GlobalNamespace.GetMember<NamedTypeSymbol>("C"); var p = c.GetMember<PropertySymbol>("P"); var indexer = c.Indexers[0]; Assert.Equal(Accessibility.Private, p.DeclaredAccessibility); Assert.Equal(Accessibility.Private, indexer.DeclaredAccessibility); }; var verifier = CompileAndVerify(comp, sourceSymbolValidator: srcValidator); } [Fact] public void StaticIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { static int this[int i] => i; }"); comp.VerifyDiagnostics( // (4,16): error CS0106: The modifier 'static' is not valid for this item // static int this[int i] => i; Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("static").WithLocation(4, 16)); } [Fact] public void RefReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.Ref, p.GetMethod.RefKind); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedProperty() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int P => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("P"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } [Fact] [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public void RefReadonlyReturningExpressionBodiedIndexer1() { var comp = CreateCompilationWithMscorlib45(@" class C { int field = 0; public ref readonly int this[in int arg] => ref field; }"); comp.VerifyDiagnostics(); var global = comp.GlobalNamespace; var c = global.GetTypeMember("C"); var p = c.GetMember<SourcePropertySymbol>("this[]"); Assert.Null(p.SetMethod); Assert.NotNull(p.GetMethod); Assert.False(p.GetMethod.IsImplicitlyDeclared); Assert.True(p.IsExpressionBodied); Assert.Equal(RefKind.RefReadOnly, p.GetMethod.RefKind); Assert.Equal(RefKind.In, p.GetMethod.Parameters[0].RefKind); Assert.False(p.ReturnsByRef); Assert.False(p.GetMethod.ReturnsByRef); Assert.True(p.ReturnsByRefReadonly); Assert.True(p.GetMethod.ReturnsByRefReadonly); } } }
{'content_hash': '3de902d482adb775b12ae0a8a9328f50', 'timestamp': '', 'source': 'github', 'line_count': 593, 'max_line_length': 191, 'avg_line_length': 32.31365935919056, 'alnum_prop': 0.6012942281598997, 'repo_name': 'swaroop-sridhar/roslyn', 'id': 'a0977043deb94f05ad22eb2560bf05ac4fa31ded', 'size': '19164', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Compilers/CSharp/Test/Symbol/Symbols/Source/ExpressionBodiedPropertyTests.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '8656'}, {'name': 'C#', 'bytes': '117879685'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2102'}, {'name': 'F#', 'bytes': '508'}, {'name': 'PowerShell', 'bytes': '137471'}, {'name': 'Rich Text Format', 'bytes': '14887'}, {'name': 'Shell', 'bytes': '61637'}, {'name': 'Smalltalk', 'bytes': '622'}, {'name': 'Visual Basic', 'bytes': '69188845'}]}
package com.hazelcast.serviceprovider; import com.hazelcast.core.DistributedObject; import com.hazelcast.internal.services.RemoteService; import java.util.UUID; public class TestRemoteService implements RemoteService { public static final String SERVICE_NAME = "TestRemoteService"; @Override public DistributedObject createDistributedObject(String objectName, UUID source, boolean local) { return new TestDistributedObject(objectName); } @Override public void destroyDistributedObject(String objectName, boolean local) { } }
{'content_hash': 'b704194b148a34218b9f897aa6ed5434', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 101, 'avg_line_length': 25.863636363636363, 'alnum_prop': 0.7768014059753954, 'repo_name': 'mesutcelik/hazelcast', 'id': '74fab357df9fc8bee9bff46cc9a4c20dcdc9c715', 'size': '1194', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'hazelcast/src/test/java/com/hazelcast/serviceprovider/TestRemoteService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1261'}, {'name': 'C', 'bytes': '353'}, {'name': 'Java', 'bytes': '39634706'}, {'name': 'Shell', 'bytes': '29479'}]}
package io.grpc.helloworldexample; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.TextUtils; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.android.examples.GreeterGrpc; import io.grpc.android.examples.nano.Helloworld.HelloReply; import io.grpc.android.examples.nano.Helloworld.HelloRequest; import java.util.concurrent.TimeUnit; public class HelloworldActivity extends ActionBarActivity { private Button mSendButton; private EditText mHostEdit; private EditText mPortEdit; private EditText mMessageEdit; private TextView mResultText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_helloworld); mSendButton = (Button) findViewById(R.id.send_button); mHostEdit = (EditText) findViewById(R.id.host_edit_text); mPortEdit = (EditText) findViewById(R.id.port_edit_text); mMessageEdit = (EditText) findViewById(R.id.message_edit_text); mResultText = (TextView) findViewById(R.id.grpc_response_text); } public void sendMessage(View view) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(mHostEdit.getWindowToken(), 0); mSendButton.setEnabled(false); new GrpcTask().execute(); } private class GrpcTask extends AsyncTask<Void, Void, String> { private String mHost; private String mMessage; private int mPort; private ManagedChannel mChannel; @Override protected void onPreExecute() { mHost = mHostEdit.getText().toString(); mMessage = mMessageEdit.getText().toString(); String portStr = mPortEdit.getText().toString(); mPort = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); mResultText.setText(""); } private String sayHello(ManagedChannel channel) { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest message = new HelloRequest(); message.name = mMessage; HelloReply reply = stub.sayHello(message); return reply.message; } @Override protected String doInBackground(Void... nothing) { try { mChannel = ManagedChannelBuilder.forAddress(mHost, mPort) .usePlaintext(true) .build(); return sayHello(mChannel); } catch (Exception e) { return "Failed... : " + e.getMessage(); } } @Override protected void onPostExecute(String result) { try { mChannel.shutdown().awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } mResultText.setText(result); mSendButton.setEnabled(true); } } }
{'content_hash': 'bf4d04d49250cabd8a096a2aaadb12ff', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 88, 'avg_line_length': 35.87096774193548, 'alnum_prop': 0.6561750599520384, 'repo_name': 'eamonnmcmanus/grpc-java', 'id': '2163f82432dd530698e0532b0168730620f69404', 'size': '3336', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'examples/android/app/src/main/java/io/grpc/helloworldexample/HelloworldActivity.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C++', 'bytes': '26377'}, {'name': 'Java', 'bytes': '1564566'}, {'name': 'Protocol Buffer', 'bytes': '27641'}, {'name': 'Shell', 'bytes': '5794'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '48271163e07b3b416392749f593c4de8', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '8476411efc68129062c29af7c6f6d1d1b072f586', 'size': '201', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Lycopodiophyta/Lycopodiopsida/Selaginellales/Selaginellaceae/Selaginella/Selaginella novoleonensis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package com.intellij.refactoring.introduceVariable; import com.intellij.codeInsight.CodeInsightUtil; import com.intellij.codeInsight.completion.JavaCompletionUtil; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.codeInsight.unwrap.ScopeHighlighter; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.featureStatistics.ProductivityFeatureNames; import com.intellij.ide.util.PropertiesComponent; import com.intellij.lang.LanguageRefactoringSupport; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.lang.refactoring.RefactoringSupportProvider; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pass; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.WindowManager; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.impl.PsiDiamondTypeUtil; import com.intellij.psi.impl.source.jsp.jspJava.JspCodeBlock; import com.intellij.psi.impl.source.jsp.jspJava.JspHolderMethod; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil; import com.intellij.psi.scope.processor.VariablesProcessor; import com.intellij.psi.scope.util.PsiScopesUtil; import com.intellij.psi.util.*; import com.intellij.refactoring.*; import com.intellij.refactoring.introduce.inplace.AbstractInplaceIntroducer; import com.intellij.refactoring.introduce.inplace.OccurrencesChooser; import com.intellij.refactoring.introduceField.ElementToWorkOn; import com.intellij.refactoring.listeners.RefactoringEventData; import com.intellij.refactoring.listeners.RefactoringEventListener; import com.intellij.refactoring.ui.TypeSelectorManagerImpl; import com.intellij.refactoring.util.CommonRefactoringUtil; import com.intellij.refactoring.util.FieldConflictsResolver; import com.intellij.refactoring.util.RefactoringUIUtil; import com.intellij.refactoring.util.RefactoringUtil; import com.intellij.refactoring.util.occurrences.ExpressionOccurrenceManager; import com.intellij.refactoring.util.occurrences.NotInSuperCallOccurrenceFilter; import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author dsl * Date: Nov 15, 2002 */ public abstract class IntroduceVariableBase extends IntroduceHandlerBase { private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.introduceVariable.IntroduceVariableBase"); @NonNls private static final String PREFER_STATEMENTS_OPTION = "introduce.variable.prefer.statements"; @NonNls private static final String REFACTORING_ID = "refactoring.extractVariable"; protected static final String REFACTORING_NAME = RefactoringBundle.message("introduce.variable.title"); public static final Key<Boolean> NEED_PARENTHESIS = Key.create("NEED_PARENTHESIS"); private JavaVariableInplaceIntroducer myInplaceIntroducer; public static SuggestedNameInfo getSuggestedName(@Nullable PsiType type, @NotNull final PsiExpression expression) { return getSuggestedName(type, expression, expression); } public static SuggestedNameInfo getSuggestedName(@Nullable PsiType type, @NotNull final PsiExpression expression, final PsiElement anchor) { final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(expression.getProject()); final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.LOCAL_VARIABLE, null, expression, type); final String[] strings = JavaCompletionUtil .completeVariableNameForRefactoring(codeStyleManager, type, VariableKind.LOCAL_VARIABLE, nameInfo); final SuggestedNameInfo.Delegate delegate = new SuggestedNameInfo.Delegate(strings, nameInfo); return codeStyleManager.suggestUniqueVariableName(delegate, anchor, true); } public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file, DataContext dataContext) { final SelectionModel selectionModel = editor.getSelectionModel(); if (!selectionModel.hasSelection()) { final int offset = editor.getCaretModel().getOffset(); final PsiElement[] statementsInRange = findStatementsAtOffset(editor, file, offset); //try line selection if (statementsInRange.length == 1 && selectLineAtCaret(offset, statementsInRange)) { selectionModel.selectLineAtCaret(); final PsiExpression expressionInRange = findExpressionInRange(project, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); if (expressionInRange == null || getErrorMessage(expressionInRange) != null) { selectionModel.removeSelection(); } } if (!selectionModel.hasSelection()) { final List<PsiExpression> expressions = collectExpressions(file, editor, offset); if (expressions.isEmpty()) { selectionModel.selectLineAtCaret(); } else if (!isChooserNeeded(expressions)) { final TextRange textRange = expressions.get(0).getTextRange(); selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset()); } else { IntroduceTargetChooser.showChooser(editor, expressions, new Pass<PsiExpression>(){ public void pass(final PsiExpression selectedValue) { invoke(project, editor, file, selectedValue.getTextRange().getStartOffset(), selectedValue.getTextRange().getEndOffset()); } }, new PsiExpressionTrimRenderer.RenderFunction(), "Expressions", preferredSelection(statementsInRange, expressions), ScopeHighlighter.NATURAL_RANGER); return; } } } if (invoke(project, editor, file, selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) && LookupManager.getActiveLookup(editor) == null) { selectionModel.removeSelection(); } } public static boolean isChooserNeeded(List<PsiExpression> exprs) { if (exprs.size() == 1) { final PsiExpression expression = exprs.get(0); return expression instanceof PsiNewExpression && ((PsiNewExpression)expression).getAnonymousClass() != null; } return true; } public static boolean selectLineAtCaret(int offset, PsiElement[] statementsInRange) { TextRange range = statementsInRange[0].getTextRange(); if (statementsInRange[0] instanceof PsiExpressionStatement) { range = ((PsiExpressionStatement)statementsInRange[0]).getExpression().getTextRange(); } return range.getStartOffset() > offset || range.getEndOffset() <= offset || isPreferStatements(); } public static int preferredSelection(PsiElement[] statementsInRange, List<PsiExpression> expressions) { int selection; if (statementsInRange.length == 1 && statementsInRange[0] instanceof PsiExpressionStatement && PsiUtilCore.hasErrorElementChild(statementsInRange[0])) { selection = expressions.indexOf(((PsiExpressionStatement)statementsInRange[0]).getExpression()); } else { PsiExpression expression = expressions.get(0); if (expression instanceof PsiReferenceExpression && ((PsiReferenceExpression)expression).resolve() instanceof PsiLocalVariable) { selection = 1; } else { selection = -1; } } return selection; } public static boolean isPreferStatements() { return Boolean.valueOf(PropertiesComponent.getInstance().getBoolean(PREFER_STATEMENTS_OPTION)) || Registry.is(PREFER_STATEMENTS_OPTION, false); } public static List<PsiExpression> collectExpressions(final PsiFile file, final Editor editor, final int offset) { return collectExpressions(file, editor, offset, false); } public static List<PsiExpression> collectExpressions(final PsiFile file, final Editor editor, final int offset, boolean acceptVoid) { return collectExpressions(file, editor.getDocument(), offset, acceptVoid); } public static List<PsiExpression> collectExpressions(final PsiFile file, final Document document, final int offset, boolean acceptVoid) { CharSequence text = document.getCharsSequence(); int correctedOffset = offset; int textLength = document.getTextLength(); if (offset >= textLength) { correctedOffset = textLength - 1; } else if (!Character.isJavaIdentifierPart(text.charAt(offset))) { correctedOffset--; } if (correctedOffset < 0) { correctedOffset = offset; } else if (!Character.isJavaIdentifierPart(text.charAt(correctedOffset))) { if (text.charAt(correctedOffset) == ';') {//initially caret on the end of line correctedOffset--; } if (correctedOffset < 0 || text.charAt(correctedOffset) != ')') { correctedOffset = offset; } } final PsiElement elementAtCaret = file.findElementAt(correctedOffset); final List<PsiExpression> expressions = new ArrayList<PsiExpression>(); /*for (PsiElement element : statementsInRange) { if (element instanceof PsiExpressionStatement) { final PsiExpression expression = ((PsiExpressionStatement)element).getExpression(); if (expression.getType() != PsiType.VOID) { expressions.add(expression); } } }*/ PsiExpression expression = PsiTreeUtil.getParentOfType(elementAtCaret, PsiExpression.class); while (expression != null) { if (!expressions.contains(expression) && !(expression instanceof PsiParenthesizedExpression) && !(expression instanceof PsiSuperExpression) && (acceptVoid || !PsiType.VOID.equals(expression.getType()))) { if (expression instanceof PsiMethodReferenceExpression) { expressions.add(expression); } else if (!(expression instanceof PsiAssignmentExpression)) { if (!(expression instanceof PsiReferenceExpression)) { expressions.add(expression); } else { if (!(expression.getParent() instanceof PsiMethodCallExpression)) { final PsiElement resolve = ((PsiReferenceExpression)expression).resolve(); if (!(resolve instanceof PsiClass) && !(resolve instanceof PsiPackage)) { expressions.add(expression); } } } } } expression = PsiTreeUtil.getParentOfType(expression, PsiExpression.class); } return expressions; } public static PsiElement[] findStatementsAtOffset(final Editor editor, final PsiFile file, final int offset) { final Document document = editor.getDocument(); final int lineNumber = document.getLineNumber(offset); final int lineStart = document.getLineStartOffset(lineNumber); final int lineEnd = document.getLineEndOffset(lineNumber); return CodeInsightUtil.findStatementsInRange(file, lineStart, lineEnd); } private boolean invoke(final Project project, final Editor editor, PsiFile file, int startOffset, int endOffset) { FeatureUsageTracker.getInstance().triggerFeatureUsed(ProductivityFeatureNames.REFACTORING_INTRODUCE_VARIABLE); PsiDocumentManager.getInstance(project).commitAllDocuments(); return invokeImpl(project, findExpressionInRange(project, file, startOffset, endOffset), editor); } private static PsiExpression findExpressionInRange(Project project, PsiFile file, int startOffset, int endOffset) { PsiExpression tempExpr = CodeInsightUtil.findExpressionInRange(file, startOffset, endOffset); if (tempExpr == null) { PsiElement[] statements = CodeInsightUtil.findStatementsInRange(file, startOffset, endOffset); if (statements.length == 1) { if (statements[0] instanceof PsiExpressionStatement) { tempExpr = ((PsiExpressionStatement) statements[0]).getExpression(); } else if (statements[0] instanceof PsiReturnStatement) { tempExpr = ((PsiReturnStatement)statements[0]).getReturnValue(); } } } if (tempExpr == null) { tempExpr = getSelectedExpression(project, file, startOffset, endOffset); } return tempExpr; } /** * @return can return NotNull value although extraction will fail: reason could be retrieved from {@link #getErrorMessage(PsiExpression)} */ public static PsiExpression getSelectedExpression(final Project project, PsiFile file, int startOffset, int endOffset) { final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(project); PsiElement elementAtStart = file.findElementAt(startOffset); if (elementAtStart == null || elementAtStart instanceof PsiWhiteSpace || elementAtStart instanceof PsiComment) { final PsiElement element = PsiTreeUtil.skipSiblingsForward(elementAtStart, PsiWhiteSpace.class, PsiComment.class); if (element != null) { startOffset = element.getTextOffset(); elementAtStart = file.findElementAt(startOffset); } if (elementAtStart == null) { if (injectedLanguageManager.isInjectedFragment(file)) { return getSelectionFromInjectedHost(project, file, injectedLanguageManager, startOffset, endOffset); } else { return null; } } startOffset = elementAtStart.getTextOffset(); } PsiElement elementAtEnd = file.findElementAt(endOffset - 1); if (elementAtEnd == null || elementAtEnd instanceof PsiWhiteSpace || elementAtEnd instanceof PsiComment) { elementAtEnd = PsiTreeUtil.skipSiblingsBackward(elementAtEnd, PsiWhiteSpace.class, PsiComment.class); if (elementAtEnd == null) return null; endOffset = elementAtEnd.getTextRange().getEndOffset(); } if (endOffset <= startOffset) return null; PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd); final PsiExpression containingExpression = PsiTreeUtil.getParentOfType(elementAt, PsiExpression.class, false); if (containingExpression != null && containingExpression == elementAtEnd && startOffset == containingExpression.getTextOffset()) { return containingExpression; } if (containingExpression == null || containingExpression instanceof PsiLambdaExpression) { if (injectedLanguageManager.isInjectedFragment(file)) { return getSelectionFromInjectedHost(project, file, injectedLanguageManager, startOffset, endOffset); } elementAt = null; } final PsiLiteralExpression literalExpression = PsiTreeUtil.getParentOfType(elementAt, PsiLiteralExpression.class); final PsiLiteralExpression startLiteralExpression = PsiTreeUtil.getParentOfType(elementAtStart, PsiLiteralExpression.class); final PsiLiteralExpression endLiteralExpression = PsiTreeUtil.getParentOfType(file.findElementAt(endOffset), PsiLiteralExpression.class); final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory(); String text = null; PsiExpression tempExpr; try { text = file.getText().subSequence(startOffset, endOffset).toString(); String prefix = null; String stripped = text; if (startLiteralExpression != null) { final int startExpressionOffset = startLiteralExpression.getTextOffset(); if (startOffset == startExpressionOffset) { if (StringUtil.startsWithChar(text, '\"') || StringUtil.startsWithChar(text, '\'')) { stripped = text.substring(1); } } else if (startOffset == startExpressionOffset + 1) { text = "\"" + text; } else if (startOffset > startExpressionOffset + 1){ prefix = "\" + "; text = "\"" + text; } } String suffix = null; if (endLiteralExpression != null) { final int endExpressionOffset = endLiteralExpression.getTextOffset() + endLiteralExpression.getTextLength(); if (endOffset == endExpressionOffset ) { if (StringUtil.endsWithChar(stripped, '\"') || StringUtil.endsWithChar(stripped, '\'')) { stripped = stripped.substring(0, stripped.length() - 1); } } else if (endOffset == endExpressionOffset - 1) { text += "\""; } else if (endOffset < endExpressionOffset - 1) { suffix = " + \""; text += "\""; } } boolean primitive = false; if (stripped.equals("true") || stripped.equals("false")) { primitive = true; } else { try { Integer.parseInt(stripped); primitive = true; } catch (NumberFormatException e1) { //then not primitive } } if (primitive) { text = stripped; } if (literalExpression != null && text.equals(literalExpression.getText())) return literalExpression; final PsiElement parent = literalExpression != null ? literalExpression : elementAt; tempExpr = elementFactory.createExpressionFromText(text, parent); final boolean [] hasErrors = new boolean[1]; final JavaRecursiveElementWalkingVisitor errorsVisitor = new JavaRecursiveElementWalkingVisitor() { @Override public void visitElement(final PsiElement element) { if (hasErrors[0]) { return; } super.visitElement(element); } @Override public void visitErrorElement(final PsiErrorElement element) { hasErrors[0] = true; } }; tempExpr.accept(errorsVisitor); if (hasErrors[0]) return null; tempExpr.putUserData(ElementToWorkOn.PREFIX, prefix); tempExpr.putUserData(ElementToWorkOn.SUFFIX, suffix); final RangeMarker rangeMarker = FileDocumentManager.getInstance().getDocument(file.getVirtualFile()).createRangeMarker(startOffset, endOffset); tempExpr.putUserData(ElementToWorkOn.TEXT_RANGE, rangeMarker); if (parent != null) { tempExpr.putUserData(ElementToWorkOn.PARENT, parent); } else { PsiErrorElement errorElement = elementAtStart instanceof PsiErrorElement ? (PsiErrorElement)elementAtStart : PsiTreeUtil.getNextSiblingOfType(elementAtStart, PsiErrorElement.class); if (errorElement == null) { errorElement = PsiTreeUtil.getParentOfType(elementAtStart, PsiErrorElement.class); } if (errorElement == null) return null; if (!(errorElement.getParent() instanceof PsiClass)) return null; tempExpr.putUserData(ElementToWorkOn.PARENT, errorElement); tempExpr.putUserData(ElementToWorkOn.OUT_OF_CODE_BLOCK, Boolean.TRUE); } final String fakeInitializer = "intellijidearulezzz"; final int[] refIdx = new int[1]; final PsiElement toBeExpression = createReplacement(fakeInitializer, project, prefix, suffix, parent, rangeMarker, refIdx); toBeExpression.accept(errorsVisitor); if (hasErrors[0]) return null; if (literalExpression != null && toBeExpression instanceof PsiExpression) { PsiType type = ((PsiExpression)toBeExpression).getType(); if (type != null && !type.equals(literalExpression.getType())) { return null; } } final PsiReferenceExpression refExpr = PsiTreeUtil.getParentOfType(toBeExpression.findElementAt(refIdx[0]), PsiReferenceExpression.class); if (refExpr == null) return null; if (toBeExpression == refExpr && refIdx[0] > 0) { return null; } if (ReplaceExpressionUtil.isNeedParenthesis(refExpr.getNode(), tempExpr.getNode())) { tempExpr.putCopyableUserData(NEED_PARENTHESIS, Boolean.TRUE); return tempExpr; } } catch (IncorrectOperationException e) { if (elementAt instanceof PsiExpressionList) { final PsiElement parent = elementAt.getParent(); return parent instanceof PsiCallExpression ? createArrayCreationExpression(text, startOffset, endOffset, (PsiCallExpression)parent) : null; } return null; } return tempExpr; } private static PsiExpression getSelectionFromInjectedHost(Project project, PsiFile file, InjectedLanguageManager injectedLanguageManager, int startOffset, int endOffset) { final PsiLanguageInjectionHost injectionHost = injectedLanguageManager.getInjectionHost(file); return getSelectedExpression(project, injectionHost.getContainingFile(), injectedLanguageManager.injectedToHost(file, startOffset), injectedLanguageManager.injectedToHost(file, endOffset)); } @Nullable public static String getErrorMessage(PsiExpression expr) { final Boolean needParenthesis = expr.getCopyableUserData(NEED_PARENTHESIS); if (needParenthesis != null && needParenthesis.booleanValue()) { return "Extracting selected expression would change the semantic of the whole expression."; } return null; } private static PsiExpression createArrayCreationExpression(String text, int startOffset, int endOffset, PsiCallExpression parent) { if (text == null || parent == null) return null; final String[] varargsExpressions = text.split("s*,s*"); if (varargsExpressions.length > 1) { final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(parent.getProject()); final JavaResolveResult resolveResult = parent.resolveMethodGenerics(); final PsiMethod psiMethod = (PsiMethod)resolveResult.getElement(); if (psiMethod == null || !psiMethod.isVarArgs()) return null; final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); final PsiParameter varargParameter = parameters[parameters.length - 1]; final PsiType type = varargParameter.getType(); LOG.assertTrue(type instanceof PsiEllipsisType); final PsiArrayType psiType = (PsiArrayType)((PsiEllipsisType)type).toArrayType(); final PsiExpression[] args = parent.getArgumentList().getExpressions(); final PsiSubstitutor psiSubstitutor = resolveResult.getSubstitutor(); if (args.length < parameters.length || startOffset < args[parameters.length - 1].getTextRange().getStartOffset()) return null; final PsiFile containingFile = parent.getContainingFile(); PsiElement startElement = containingFile.findElementAt(startOffset); while (startElement != null && startElement.getParent() != parent.getArgumentList()) { startElement = startElement.getParent(); } if (startElement == null || startOffset > startElement.getTextOffset()) return null; PsiElement endElement = containingFile.findElementAt(endOffset - 1); while (endElement != null && endElement.getParent() != parent.getArgumentList()) { endElement = endElement.getParent(); } if (endElement == null || endOffset < endElement.getTextRange().getEndOffset()) return null; final PsiType componentType = TypeConversionUtil.erasure(psiSubstitutor.substitute(psiType.getComponentType())); try { final PsiExpression expressionFromText = elementFactory.createExpressionFromText("new " + componentType.getCanonicalText() + "[]{" + text + "}", parent); final RangeMarker rangeMarker = FileDocumentManager.getInstance().getDocument(containingFile.getVirtualFile()).createRangeMarker(startOffset, endOffset); expressionFromText.putUserData(ElementToWorkOn.TEXT_RANGE, rangeMarker); expressionFromText.putUserData(ElementToWorkOn.PARENT, parent); return expressionFromText; } catch (IncorrectOperationException e) { return null; } } return null; } protected boolean invokeImpl(final Project project, final PsiExpression expr, final Editor editor) { if (expr != null) { final String errorMessage = getErrorMessage(expr); if (errorMessage != null) { showErrorMessage(project, editor, RefactoringBundle.getCannotRefactorMessage(errorMessage)); return false; } } if (expr != null && expr.getParent() instanceof PsiExpressionStatement) { FeatureUsageTracker.getInstance().triggerFeatureUsed("refactoring.introduceVariable.incompleteStatement"); } if (LOG.isDebugEnabled()) { LOG.debug("expression:" + expr); } if (expr == null || !expr.isPhysical()) { if (ReassignVariableUtil.reassign(editor)) return false; if (expr == null) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("selected.block.should.represent.an.expression")); showErrorMessage(project, editor, message); return false; } } final PsiType originalType = RefactoringUtil.getTypeByExpressionWithExpectedType(expr); if (originalType == null || LambdaUtil.notInferredType(originalType)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("unknown.expression.type")); showErrorMessage(project, editor, message); return false; } if (PsiType.VOID.equals(originalType)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("selected.expression.has.void.type")); showErrorMessage(project, editor, message); return false; } final PsiElement physicalElement = expr.getUserData(ElementToWorkOn.PARENT); final PsiElement anchorStatement = RefactoringUtil.getParentStatement(physicalElement != null ? physicalElement : expr, false); if (anchorStatement == null) { return parentStatementNotFound(project, editor); } if (checkAnchorBeforeThisOrSuper(project, editor, anchorStatement, REFACTORING_NAME, HelpID.INTRODUCE_VARIABLE)) return false; final PsiElement tempContainer = anchorStatement.getParent(); if (!(tempContainer instanceof PsiCodeBlock) && !RefactoringUtil.isLoopOrIf(tempContainer) && (tempContainer.getParent() instanceof PsiLambdaExpression)) { String message = RefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", REFACTORING_NAME); showErrorMessage(project, editor, message); return false; } if(!NotInSuperCallOccurrenceFilter.INSTANCE.isOK(expr)) { String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("cannot.introduce.variable.in.super.constructor.call")); showErrorMessage(project, editor, message); return false; } final PsiFile file = anchorStatement.getContainingFile(); LOG.assertTrue(file != null, "expr.getContainingFile() == null"); final PsiElement nameSuggestionContext = editor == null ? null : file.findElementAt(editor.getCaretModel().getOffset()); final RefactoringSupportProvider supportProvider = LanguageRefactoringSupport.INSTANCE.forLanguage(expr.getLanguage()); final boolean isInplaceAvailableOnDataContext = supportProvider != null && editor.getSettings().isVariableInplaceRenameEnabled() && supportProvider.isInplaceIntroduceAvailable(expr, nameSuggestionContext) && (!ApplicationManager.getApplication().isUnitTestMode() || isInplaceAvailableInTestMode()) && !isInJspHolderMethod(expr); if (isInplaceAvailableOnDataContext) { final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>(); checkInLoopCondition(expr, conflicts); if (!conflicts.isEmpty()) { showErrorMessage(project, editor, StringUtil.join(conflicts.values(), "<br>")); return false; } } final ExpressionOccurrenceManager occurrenceManager = createOccurrenceManager(expr, tempContainer); final PsiExpression[] occurrences = occurrenceManager.getOccurrences(); final PsiElement anchorStatementIfAll = occurrenceManager.getAnchorStatementForAll(); final List<PsiExpression> nonWrite = new ArrayList<PsiExpression>(); boolean cantReplaceAll = false; boolean cantReplaceAllButWrite = false; for (PsiExpression occurrence : occurrences) { if (!RefactoringUtil.isAssignmentLHS(occurrence)) { nonWrite.add(occurrence); } else if (isFinalVariableOnLHS(occurrence)) { cantReplaceAll = true; } else if (!nonWrite.isEmpty()){ cantReplaceAllButWrite = true; cantReplaceAll = true; } } if (!CommonRefactoringUtil.checkReadOnlyStatus(project, file)) return false; final LinkedHashMap<OccurrencesChooser.ReplaceChoice, List<PsiExpression>> occurrencesMap = ContainerUtil.newLinkedHashMap(); occurrencesMap.put(OccurrencesChooser.ReplaceChoice.NO, Collections.singletonList(expr)); final boolean hasWriteAccess = occurrences.length > nonWrite.size() && occurrences.length > 1; if (hasWriteAccess && !cantReplaceAllButWrite) { occurrencesMap.put(OccurrencesChooser.ReplaceChoice.NO_WRITE, nonWrite); } if (occurrences.length > 1 && !cantReplaceAll) { occurrencesMap.put(OccurrencesChooser.ReplaceChoice.ALL, Arrays.asList(occurrences)); } final boolean inFinalContext = occurrenceManager.isInFinalContext(); final InputValidator validator = new InputValidator(this, project, anchorStatementIfAll, anchorStatement, occurrenceManager); final TypeSelectorManagerImpl typeSelectorManager = new TypeSelectorManagerImpl(project, originalType, expr, occurrences); final boolean[] wasSucceed = new boolean[]{true}; final Pass<OccurrencesChooser.ReplaceChoice> callback = new Pass<OccurrencesChooser.ReplaceChoice>() { @Override public void pass(final OccurrencesChooser.ReplaceChoice choice) { if (choice != null) { final boolean replaceAll = choice == OccurrencesChooser.ReplaceChoice.ALL || choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; typeSelectorManager.setAllOccurrences(replaceAll); final PsiElement chosenAnchor = chooseAnchor(replaceAll, choice == OccurrencesChooser.ReplaceChoice.NO_WRITE, nonWrite, anchorStatementIfAll, anchorStatement); final IntroduceVariableSettings settings = getSettings(project, editor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, chosenAnchor, choice); final boolean cantChangeFinalModifier = (hasWriteAccess || inFinalContext) && choice == OccurrencesChooser.ReplaceChoice.ALL; final boolean noWrite = choice == OccurrencesChooser.ReplaceChoice.NO_WRITE; final List<PsiExpression> allOccurrences = new ArrayList<PsiExpression>(); for (PsiExpression occurrence : occurrences) { if (expr.equals(occurrence) && expr.getParent() instanceof PsiExpressionStatement) continue; if (choice == OccurrencesChooser.ReplaceChoice.ALL || (noWrite && !PsiUtil.isAccessedForWriting(occurrence)) || expr.equals(occurrence)) { allOccurrences.add(occurrence); } } myInplaceIntroducer = new JavaVariableInplaceIntroducer(project, settings, chosenAnchor, editor, expr, cantChangeFinalModifier, allOccurrences.toArray(new PsiExpression[allOccurrences.size()]), typeSelectorManager, REFACTORING_NAME); if (myInplaceIntroducer.startInplaceIntroduceTemplate()) { return; } } CommandProcessor.getInstance().executeCommand( project, new Runnable() { public void run() { final Editor topLevelEditor ; if (!InjectedLanguageManager.getInstance(project).isInjectedFragment(anchorStatement.getContainingFile())) { topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(editor); } else { topLevelEditor = editor; } PsiVariable variable = null; try { final IntroduceVariableSettings settings = getSettings(project, topLevelEditor, expr, occurrences, typeSelectorManager, inFinalContext, hasWriteAccess, validator, anchorStatement, choice); if (!settings.isOK()) { wasSucceed[0] = false; return; } final RefactoringEventData beforeData = new RefactoringEventData(); beforeData.addElement(expr); project.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, beforeData); final PsiElement chosenAnchor = chooseAnchor(settings.isReplaceAllOccurrences(), hasWriteAccess, nonWrite, anchorStatementIfAll, anchorStatement); variable = ApplicationManager.getApplication().runWriteAction( introduce(project, expr, topLevelEditor, chosenAnchor, occurrences, settings)); } finally { final RefactoringEventData afterData = new RefactoringEventData(); afterData.addElement(variable); project.getMessageBus() .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, afterData); } } }, REFACTORING_NAME, null); } }; if (!isInplaceAvailableOnDataContext) { callback.pass(null); } else { OccurrencesChooser.ReplaceChoice choice = getOccurrencesChoice(); if (choice != null) { callback.pass(choice); } else { OccurrencesChooser.<PsiExpression>simpleChooser(editor).showChooser(callback, occurrencesMap); } } return wasSucceed[0]; } protected OccurrencesChooser.ReplaceChoice getOccurrencesChoice() { return null; } protected static PsiElement chooseAnchor(boolean allOccurences, boolean hasWriteAccess, List<PsiExpression> nonWrite, PsiElement anchorStatementIfAll, PsiElement anchorStatement) { if (allOccurences) { if (hasWriteAccess) { return RefactoringUtil.getAnchorElementForMultipleExpressions(nonWrite.toArray(new PsiExpression[nonWrite.size()]), null); } else { return anchorStatementIfAll; } } else { return anchorStatement; } } protected boolean isInplaceAvailableInTestMode() { return false; } private static ExpressionOccurrenceManager createOccurrenceManager(PsiExpression expr, PsiElement tempContainer) { boolean skipForStatement = true; final PsiForStatement forStatement = PsiTreeUtil.getParentOfType(expr, PsiForStatement.class); if (forStatement != null) { final VariablesProcessor variablesProcessor = new VariablesProcessor(false) { @Override protected boolean check(PsiVariable var, ResolveState state) { return PsiTreeUtil.isAncestor(forStatement.getInitialization(), var, true); } }; PsiScopesUtil.treeWalkUp(variablesProcessor, expr, null); skipForStatement = variablesProcessor.size() == 0; } PsiElement containerParent = tempContainer; PsiElement lastScope = tempContainer; while (true) { if (containerParent instanceof PsiFile) break; if (containerParent instanceof PsiMethod) break; if (containerParent instanceof PsiLambdaExpression) break; if (!skipForStatement && containerParent instanceof PsiForStatement) break; containerParent = containerParent.getParent(); if (containerParent instanceof PsiCodeBlock) { lastScope = containerParent; } } return new ExpressionOccurrenceManager(expr, lastScope, NotInSuperCallOccurrenceFilter.INSTANCE); } private static boolean isInJspHolderMethod(PsiExpression expr) { final PsiElement parent1 = expr.getParent(); if (parent1 == null) { return false; } final PsiElement parent2 = parent1.getParent(); if (!(parent2 instanceof JspCodeBlock)) return false; final PsiElement parent3 = parent2.getParent(); return parent3 instanceof JspHolderMethod; } public static Computable<PsiVariable> introduce(final Project project, final PsiExpression expr, final Editor editor, final PsiElement anchorStatement, final PsiExpression[] occurrences, final IntroduceVariableSettings settings) { final PsiElement container = anchorStatement.getParent(); PsiElement child = anchorStatement; final boolean isInsideLoop = RefactoringUtil.isLoopOrIf(container); if (!isInsideLoop) { child = locateAnchor(child); if (isFinalVariableOnLHS(expr)) { child = child.getNextSibling(); } } final PsiElement anchor = child == null ? anchorStatement : child; boolean tempDeleteSelf = false; final boolean replaceSelf = settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(expr); final PsiElement exprParent = expr.getParent(); if (!isInsideLoop) { if (exprParent instanceof PsiExpressionStatement && anchor.equals(anchorStatement)) { PsiElement parent = exprParent.getParent(); if (parent instanceof PsiCodeBlock || //fabrique parent instanceof PsiCodeFragment) { tempDeleteSelf = true; } } tempDeleteSelf &= replaceSelf; } final boolean deleteSelf = tempDeleteSelf; final boolean replaceLoop = isInsideLoop ? exprParent instanceof PsiExpressionStatement : container instanceof PsiLambdaExpression && exprParent == container; final int col = editor != null ? editor.getCaretModel().getLogicalPosition().column : 0; final int line = editor != null ? editor.getCaretModel().getLogicalPosition().line : 0; if (deleteSelf) { if (editor != null) { LogicalPosition pos = new LogicalPosition(line, col); editor.getCaretModel().moveToLogicalPosition(pos); } } final PsiCodeBlock newDeclarationScope = PsiTreeUtil.getParentOfType(container, PsiCodeBlock.class, false); final FieldConflictsResolver fieldConflictsResolver = new FieldConflictsResolver(settings.getEnteredName(), newDeclarationScope); return new Computable<PsiVariable>() { @Override public PsiVariable compute() { try { PsiStatement statement = null; if (!isInsideLoop && deleteSelf) { statement = (PsiStatement)exprParent; } final PsiExpression expr1 = fieldConflictsResolver.fixInitializer(expr); PsiExpression initializer = RefactoringUtil.unparenthesizeExpression(expr1); final SmartTypePointer selectedType = SmartTypePointerManager.getInstance(project).createSmartTypePointer( settings.getSelectedType()); if (expr1 instanceof PsiNewExpression) { final PsiNewExpression newExpression = (PsiNewExpression)expr1; if (newExpression.getArrayInitializer() != null) { initializer = newExpression.getArrayInitializer(); } initializer = replaceExplicitWithDiamondWhenApplicable(initializer, selectedType.getType()); } PsiDeclarationStatement declaration = JavaPsiFacade.getInstance(project).getElementFactory() .createVariableDeclarationStatement(settings.getEnteredName(), selectedType.getType(), initializer, container); if (!isInsideLoop) { declaration = addDeclaration(declaration, initializer); LOG.assertTrue(expr1.isValid()); if (deleteSelf) { final PsiElement lastChild = statement.getLastChild(); if (lastChild instanceof PsiComment) { // keep trailing comment declaration.addBefore(lastChild, null); } statement.delete(); if (editor != null) { LogicalPosition pos = new LogicalPosition(line, col); editor.getCaretModel().moveToLogicalPosition(pos); editor.getCaretModel().moveToOffset(declaration.getTextRange().getEndOffset()); editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); editor.getSelectionModel().removeSelection(); } } } PsiExpression ref = JavaPsiFacade.getInstance(project).getElementFactory().createExpressionFromText(settings.getEnteredName(), null); if (settings.isReplaceAllOccurrences()) { ArrayList<PsiElement> array = new ArrayList<PsiElement>(); for (PsiExpression occurrence : occurrences) { if (deleteSelf && occurrence.equals(expr)) continue; if (occurrence.equals(expr)) { occurrence = expr1; } if (occurrence != null) { occurrence = RefactoringUtil.outermostParenthesizedExpression(occurrence); } if (settings.isReplaceLValues() || !RefactoringUtil.isAssignmentLHS(occurrence)) { array.add(replace(occurrence, ref, project)); } } if (!deleteSelf && replaceSelf && expr1 instanceof PsiPolyadicExpression && expr1.isValid() && !expr1.isPhysical() ) { array.add(replace(expr1, ref, project)); } if (editor != null) { final PsiElement[] replacedOccurences = PsiUtilCore.toPsiElementArray(array); highlightReplacedOccurences(project, editor, replacedOccurences); } } else { if (!deleteSelf && replaceSelf) { replace(expr1, ref, project); } } declaration = (PsiDeclarationStatement) RefactoringUtil.putStatementInLoopBody(declaration, container, anchorStatement, replaceSelf && replaceLoop); declaration = (PsiDeclarationStatement)JavaCodeStyleManager.getInstance(project).shortenClassReferences(declaration); PsiVariable var = (PsiVariable) declaration.getDeclaredElements()[0]; PsiUtil.setModifierProperty(var, PsiModifier.FINAL, settings.isDeclareFinal()); fieldConflictsResolver.fix(); return var; } catch (IncorrectOperationException e) { LOG.error(e); } return null; } private PsiDeclarationStatement addDeclaration(PsiDeclarationStatement declaration, PsiExpression initializer) { if (anchor instanceof PsiDeclarationStatement) { final PsiElement[] declaredElements = ((PsiDeclarationStatement)anchor).getDeclaredElements(); if (declaredElements.length > 1) { final int [] usedFirstVar = new int[] {-1}; initializer.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expression) { final int i = ArrayUtilRt.find(declaredElements, expression.resolve()); if (i > -1) { usedFirstVar[0] = Math.max(i, usedFirstVar[0]); } super.visitReferenceExpression(expression); } }); if (usedFirstVar[0] > -1) { final PsiVariable psiVariable = (PsiVariable)declaredElements[usedFirstVar[0]]; psiVariable.normalizeDeclaration(); final PsiDeclarationStatement parDeclarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class); return (PsiDeclarationStatement)container.addAfter(declaration, parDeclarationStatement); } } } return (PsiDeclarationStatement) container.addBefore(declaration, anchor); } }; } private static boolean isFinalVariableOnLHS(PsiExpression expr) { if (expr instanceof PsiReferenceExpression && RefactoringUtil.isAssignmentLHS(expr)) { final PsiElement resolve = ((PsiReferenceExpression)expr).resolve(); if (resolve instanceof PsiVariable && ((PsiVariable)resolve).hasModifierProperty(PsiModifier.FINAL)) { //should be inserted after assignment return true; } } return false; } public static PsiExpression replaceExplicitWithDiamondWhenApplicable(final PsiExpression initializer, final PsiType expectedType) { if (initializer instanceof PsiNewExpression) { final PsiNewExpression newExpression = (PsiNewExpression)initializer; final PsiExpression tryToDetectDiamondNewExpr = ((PsiVariable)JavaPsiFacade.getElementFactory(initializer.getProject()) .createVariableDeclarationStatement("x", expectedType, initializer, initializer).getDeclaredElements()[0]) .getInitializer(); if (tryToDetectDiamondNewExpr instanceof PsiNewExpression && PsiDiamondTypeUtil.canCollapseToDiamond((PsiNewExpression)tryToDetectDiamondNewExpr, (PsiNewExpression)tryToDetectDiamondNewExpr, expectedType)) { final PsiElement paramList = PsiDiamondTypeUtil .replaceExplicitWithDiamond(newExpression.getClassOrAnonymousClassReference().getParameterList()); return PsiTreeUtil.getParentOfType(paramList, PsiNewExpression.class); } } return initializer; } public static PsiElement replace(final PsiExpression expr1, final PsiExpression ref, final Project project) throws IncorrectOperationException { final PsiExpression expr2; if (expr1 instanceof PsiArrayInitializerExpression && expr1.getParent() instanceof PsiNewExpression) { expr2 = (PsiNewExpression) expr1.getParent(); } else { expr2 = RefactoringUtil.outermostParenthesizedExpression(expr1); } if (expr2.isPhysical() || expr1.getUserData(ElementToWorkOn.REPLACE_NON_PHYSICAL) != null) { return expr2.replace(ref); } else { final String prefix = expr1.getUserData(ElementToWorkOn.PREFIX); final String suffix = expr1.getUserData(ElementToWorkOn.SUFFIX); final PsiElement parent = expr1.getUserData(ElementToWorkOn.PARENT); final RangeMarker rangeMarker = expr1.getUserData(ElementToWorkOn.TEXT_RANGE); LOG.assertTrue(parent != null, expr1); return parent.replace(createReplacement(ref.getText(), project, prefix, suffix, parent, rangeMarker, new int[1])); } } private static PsiElement createReplacement(final String refText, final Project project, final String prefix, final String suffix, final PsiElement parent, final RangeMarker rangeMarker, int[] refIdx) { String text = refText; if (parent != null) { final String allText = parent.getContainingFile().getText(); final TextRange parentRange = parent.getTextRange(); LOG.assertTrue(parentRange.getStartOffset() <= rangeMarker.getStartOffset(), parent + "; prefix:" + prefix + "; suffix:" + suffix); String beg = allText.substring(parentRange.getStartOffset(), rangeMarker.getStartOffset()); if (StringUtil.stripQuotesAroundValue(beg).trim().length() == 0 && prefix == null) beg = ""; LOG.assertTrue(rangeMarker.getEndOffset() <= parentRange.getEndOffset(), parent + "; prefix:" + prefix + "; suffix:" + suffix); String end = allText.substring(rangeMarker.getEndOffset(), parentRange.getEndOffset()); if (StringUtil.stripQuotesAroundValue(end).trim().length() == 0 && suffix == null) end = ""; final String start = beg + (prefix != null ? prefix : ""); refIdx[0] = start.length(); text = start + refText + (suffix != null ? suffix : "") + end; } final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory(); return parent instanceof PsiStatement ? factory.createStatementFromText(text, parent) : parent instanceof PsiCodeBlock ? factory.createCodeBlockFromText(text, parent) : factory.createExpressionFromText(text, parent); } private boolean parentStatementNotFound(final Project project, Editor editor) { String message = RefactoringBundle.message("refactoring.is.not.supported.in.the.current.context", REFACTORING_NAME); showErrorMessage(project, editor, message); return false; } protected boolean invokeImpl(Project project, PsiLocalVariable localVariable, Editor editor) { throw new UnsupportedOperationException(); } private static PsiElement locateAnchor(PsiElement child) { while (child != null) { PsiElement prev = child.getPrevSibling(); if (prev instanceof PsiStatement) break; if (prev instanceof PsiJavaToken && ((PsiJavaToken)prev).getTokenType() == JavaTokenType.LBRACE) break; child = prev; } while (child instanceof PsiWhiteSpace || child instanceof PsiComment) { child = child.getNextSibling(); } return child; } protected static void highlightReplacedOccurences(Project project, Editor editor, PsiElement[] replacedOccurences){ if (editor == null) return; if (ApplicationManager.getApplication().isUnitTestMode()) return; HighlightManager highlightManager = HighlightManager.getInstance(project); EditorColorsManager colorsManager = EditorColorsManager.getInstance(); TextAttributes attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); highlightManager.addOccurrenceHighlights(editor, replacedOccurences, attributes, true, null); WindowManager.getInstance().getStatusBar(project).setInfo(RefactoringBundle.message("press.escape.to.remove.the.highlighting")); } protected abstract void showErrorMessage(Project project, Editor editor, String message); protected boolean reportConflicts(MultiMap<PsiElement,String> conflicts, Project project, IntroduceVariableSettings settings){ return false; } public IntroduceVariableSettings getSettings(Project project, Editor editor, PsiExpression expr, PsiExpression[] occurrences, final TypeSelectorManagerImpl typeSelectorManager, boolean declareFinalIfAll, boolean anyAssignmentLHS, final InputValidator validator, PsiElement anchor, final OccurrencesChooser.ReplaceChoice replaceChoice) { final boolean replaceAll = replaceChoice == OccurrencesChooser.ReplaceChoice.ALL || replaceChoice == OccurrencesChooser.ReplaceChoice.NO_WRITE; final SuggestedNameInfo suggestedName = getSuggestedName(typeSelectorManager.getDefaultType(), expr, anchor); final String variableName = suggestedName.names.length > 0 ? suggestedName.names[0] : ""; final boolean declareFinal = replaceAll && declareFinalIfAll || !anyAssignmentLHS && createFinals(project); final boolean replaceWrite = anyAssignmentLHS && replaceChoice == OccurrencesChooser.ReplaceChoice.ALL; return new IntroduceVariableSettings() { @Override public String getEnteredName() { return variableName; } @Override public boolean isReplaceAllOccurrences() { return replaceAll; } @Override public boolean isDeclareFinal() { return declareFinal; } @Override public boolean isReplaceLValues() { return replaceWrite; } @Override public PsiType getSelectedType() { final PsiType selectedType = typeSelectorManager.getTypeSelector().getSelectedType(); return selectedType != null ? selectedType : typeSelectorManager.getDefaultType(); } @Override public boolean isOK() { return true; } }; } public static boolean createFinals(Project project) { final Boolean createFinals = JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS; return createFinals == null ? CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS : createFinals.booleanValue(); } public static boolean checkAnchorBeforeThisOrSuper(final Project project, final Editor editor, final PsiElement tempAnchorElement, final String refactoringName, final String helpID) { if (tempAnchorElement instanceof PsiExpressionStatement) { PsiExpression enclosingExpr = ((PsiExpressionStatement)tempAnchorElement).getExpression(); if (enclosingExpr instanceof PsiMethodCallExpression) { PsiMethod method = ((PsiMethodCallExpression)enclosingExpr).resolveMethod(); if (method != null && method.isConstructor()) { //This is either 'this' or 'super', both must be the first in the respective contructor String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invalid.expression.context")); CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpID); return true; } } } return false; } public interface Validator { boolean isOK(IntroduceVariableSettings dialog); } public static void checkInLoopCondition(PsiExpression occurence, MultiMap<PsiElement, String> conflicts) { final PsiElement loopForLoopCondition = RefactoringUtil.getLoopForLoopCondition(occurence); if (loopForLoopCondition == null) return; final List<PsiVariable> referencedVariables = RefactoringUtil.collectReferencedVariables(occurence); final List<PsiVariable> modifiedInBody = new ArrayList<PsiVariable>(); for (PsiVariable psiVariable : referencedVariables) { if (RefactoringUtil.isModifiedInScope(psiVariable, loopForLoopCondition)) { modifiedInBody.add(psiVariable); } } if (!modifiedInBody.isEmpty()) { for (PsiVariable variable : modifiedInBody) { final String message = RefactoringBundle.message("is.modified.in.loop.body", RefactoringUIUtil.getDescription(variable, false)); conflicts.putValue(variable, CommonRefactoringUtil.capitalize(message)); } conflicts.putValue(occurence, RefactoringBundle.message("introducing.variable.may.break.code.logic")); } } @Override public AbstractInplaceIntroducer getInplaceIntroducer() { return myInplaceIntroducer; } }
{'content_hash': 'bcd903ac3bad8c5018a29737a76ca8f7', 'timestamp': '', 'source': 'github', 'line_count': 1191, 'max_line_length': 193, 'avg_line_length': 47.98908480268682, 'alnum_prop': 0.6837022132796781, 'repo_name': 'Soya93/Extract-Refactoring', 'id': '09aa58c9e48eea6a0d8688c0c99be89093405458', 'size': '57755', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '63896'}, {'name': 'C', 'bytes': '214817'}, {'name': 'C#', 'bytes': '1538'}, {'name': 'C++', 'bytes': '191650'}, {'name': 'CSS', 'bytes': '189895'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Cucumber', 'bytes': '14382'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groff', 'bytes': '35232'}, {'name': 'Groovy', 'bytes': '2436826'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1803098'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '154798881'}, {'name': 'JavaScript', 'bytes': '562223'}, {'name': 'Jupyter Notebook', 'bytes': '92629'}, {'name': 'Kotlin', 'bytes': '1430452'}, {'name': 'Lex', 'bytes': '179878'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '53411'}, {'name': 'Objective-C', 'bytes': '29064'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6570'}, {'name': 'Python', 'bytes': '23314398'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '68088'}, {'name': 'Smalltalk', 'bytes': '64'}, {'name': 'TeX', 'bytes': '62325'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'XSLT', 'bytes': '113040'}]}
/*! * gumshoejs v5.0.0 * A simple, framework-agnostic scrollspy script. * (c) 2019 Chris Ferdinandi * MIT License * http://github.com/cferdinandi/gumshoe */ (function (root, factory) { if ( typeof define === 'function' && define.amd ) { define([], (function () { return factory(root); })); } else if ( typeof exports === 'object' ) { module.exports = factory(root); } else { root.Gumshoe = factory(root); } })(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) { 'use strict'; // // Defaults // var defaults = { // Active classes navClass: 'active', contentClass: 'active', // Nested navigation nested: false, nestedClass: 'active', // Offset & reflow offset: 0, reflow: false, // Event support events: true }; // // Methods // /** * Merge two or more objects together. * @param {Object} objects The objects to merge together * @returns {Object} Merged values of defaults and options */ var extend = function () { var merged = {}; Array.prototype.forEach.call(arguments, (function (obj) { for (var key in obj) { if (!obj.hasOwnProperty(key)) return; merged[key] = obj[key]; } })); return merged; }; /** * Emit a custom event * @param {String} type The event type * @param {Node} elem The element to attach the event to * @param {Object} detail Any details to pass along with the event */ var emitEvent = function (type, elem, detail) { // Make sure events are enabled if (!detail.settings.events) return; // Create a new event var event = new CustomEvent(type, { bubbles: true, cancelable: true, detail: detail }); // Dispatch the event elem.dispatchEvent(event); }; /** * Get an element's distance from the top of the Document. * @param {Node} elem The element * @return {Number} Distance from the top in pixels */ var getOffsetTop = function (elem) { var location = 0; if (elem.offsetParent) { while (elem) { location += elem.offsetTop; elem = elem.offsetParent; } } return location >= 0 ? location : 0; }; /** * Sort content from first to last in the DOM * @param {Array} contents The content areas */ var sortContents = function (contents) { contents.sort((function (item1, item2) { var offset1 = getOffsetTop(item1.content); var offset2 = getOffsetTop(item2.content); if (offset1 < offset2) return -1; return 1; })); }; /** * Get the offset to use for calculating position * @param {Object} settings The settings for this instantiation * @return {Float} The number of pixels to offset the calculations */ var getOffset = function (settings) { // if the offset is a function run it if (typeof settings.offset === 'function') { return parseFloat(settings.offset()); } // Otherwise, return it as-is return parseFloat(settings.offset); }; /** * Determine if an element is in the viewport * @param {Node} elem The element * @param {Object} settings The settings for this instantiation * @return {Boolean} Returns true if element is in the viewport */ var isInViewport = function (elem, settings) { var bounds = elem.getBoundingClientRect(); var offset = getOffset(settings); return parseInt(bounds.top, 10) <= offset && parseInt(bounds.bottom, 10) > offset; }; /** * Get the active content * @param {Array} contents The content areas * @param {Object} settings The settings for this instantiation * @return {Object} The content area and matching navigation link */ var getActive = function (contents, settings) { for (var i = contents.length - 1; i >= 0; i--) { if (isInViewport(contents[i].content, settings)) return contents[i]; } }; /** * Deactivate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var deactivateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Remove the active class li.classList.remove(settings.nestedClass); // Apply recursively to any parent navigation elements deactivateNested(li, settings); }; /** * Deactivate a nav and content area * @param {Object} items The nav item and content to deactivate * @param {Object} settings The settings for this instantiation */ var deactivate = function (items, settings) { // Make sure their are items to deactivate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Remove the active class from the nav and content li.classList.remove(settings.navClass); items.content.classList.remove(settings.contentClass); // Deactivate any parent navs in a nested navigation deactivateNested(li, settings); // Emit a custom event emitEvent('gumshoeDeactivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Activate parent navs in a nested navigation * @param {Node} nav The starting navigation element * @param {Object} settings The settings for this instantiation */ var activateNested = function (nav, settings) { // If nesting isn't activated, bail if (!settings.nested) return; // Get the parent navigation var li = nav.parentNode.closest('li'); if (!li) return; // Add the active class li.classList.add(settings.nestedClass); // Apply recursively to any parent navigation elements activateNested(li, settings); }; /** * Activate a nav and content area * @param {Object} items The nav item and content to activate * @param {Object} settings The settings for this instantiation */ var activate = function (items, settings) { // Make sure their are items to activate if (!items) return; // Get the parent list item var li = items.nav.closest('li'); if (!li) return; // Add the active class to the nav and content li.classList.add(settings.navClass); items.content.classList.add(settings.contentClass); // Activate any parent navs in a nested navigation activateNested(li, settings); // Emit a custom event emitEvent('gumshoeActivate', li, { link: items.nav, content: items.content, settings: settings }); }; /** * Create the Constructor object * @param {String} selector The selector to use for navigation items * @param {Object} options User options and settings */ var Constructor = function (selector, options) { // // Variables // var publicAPIs = {}; var navItems, contents, current, timeout, settings; // // Methods // /** * Set variables from DOM elements */ publicAPIs.setup = function () { // Get all nav items navItems = document.querySelectorAll(selector); // Create contents array contents = []; // Loop through each item, get it's matching content, and push to the array Array.prototype.forEach.call(navItems, (function (item) { // Get the content for the nav item var content = document.getElementById(decodeURIComponent(item.hash.substr(1))); if (!content) return; // Push to the contents array contents.push({ nav: item, content: content }); })); // Sort contents by the order they appear in the DOM sortContents(contents); }; /** * Detect which content is currently active */ publicAPIs.detect = function () { // Get the active content var active = getActive(contents, settings); // if there's no active content, deactivate and bail if (!active) { if (current) { deactivate(current, settings); current = null; } return; } // If the active content is the one currently active, do nothing if (current && active.content === current.content) return; // Deactivate the current content and activate the new content deactivate(current, settings); activate(active, settings); // Update the currently active content current = active; }; /** * Detect the active content on scroll * Debounced for performance */ var scrollHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame(publicAPIs.detect); }; /** * Update content sorting on resize * Debounced for performance */ var resizeHandler = function (event) { // If there's a timer, cancel it if (timeout) { window.cancelAnimationFrame(timeout); } // Setup debounce callback timeout = window.requestAnimationFrame((function () { sortContents(); publicAPIs.detect(); })); }; /** * Destroy the current instantiation */ publicAPIs.destroy = function () { // Undo DOM changes if (current) { deactivate(current); } // Remove event listeners window.removeEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.removeEventListener('resize', resizeHandler, false); } // Reset variables contents = null; navItems = null; current = null; timeout = null; settings = null; }; /** * Initialize the current instantiation */ var init = function () { // Merge user options into defaults settings = extend(defaults, options || {}); // Setup variables based on the current DOM publicAPIs.setup(); // Find the currently active content publicAPIs.detect(); // Setup event listeners window.addEventListener('scroll', scrollHandler, false); if (settings.reflow) { window.addEventListener('resize', resizeHandler, false); } }; // // Initialize and return the public APIs // init(); return publicAPIs; }; // // Return the Constructor // return Constructor; }));
{'content_hash': '2a836968bedfb4dfcc663b65cd3bf57e', 'timestamp': '', 'source': 'github', 'line_count': 443, 'max_line_length': 111, 'avg_line_length': 22.672686230248306, 'alnum_prop': 0.6558144165671047, 'repo_name': 'sufuf3/cdnjs', 'id': '475c2b7d0f68633fbb02c5c785cd6f3f8222983e', 'size': '10044', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ajax/libs/gumshoe/5.0.0/gumshoe.js', 'mode': '33188', 'license': 'mit', 'language': []}
<?php namespace Symfony\Component\Translation\Loader; /** * PhpFileLoader loads translations from PHP files returning an array of translations. * * @author Fabien Potencier <[email protected]> */ class PhpFileLoader extends FileLoader { private static $cache = []; /** * {@inheritdoc} */ protected function loadResource($resource) { if ([] === self::$cache && \function_exists('opcache_invalidate') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOLEAN) && (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) || filter_var(\ini_get('opcache.enable_cli'), \FILTER_VALIDATE_BOOLEAN))) { self::$cache = null; } if (null === self::$cache) { return require $resource; } if (isset(self::$cache[$resource])) { return self::$cache[$resource]; } return self::$cache[$resource] = require $resource; } }
{'content_hash': 'c01ff2f9735984428e45841d3519a2fc', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 268, 'avg_line_length': 26.771428571428572, 'alnum_prop': 0.5955176093916755, 'repo_name': 'electric-eloquence/fepper-drupal', 'id': '2310740bd821bb4bd8e8be7982980b68e79c9414', 'size': '1166', 'binary': False, 'copies': '5', 'ref': 'refs/heads/dev', 'path': 'backend/drupal/vendor/symfony/translation/Loader/PhpFileLoader.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2300765'}, {'name': 'HTML', 'bytes': '68444'}, {'name': 'JavaScript', 'bytes': '2453602'}, {'name': 'Mustache', 'bytes': '40698'}, {'name': 'PHP', 'bytes': '41684915'}, {'name': 'PowerShell', 'bytes': '755'}, {'name': 'Shell', 'bytes': '72896'}, {'name': 'Stylus', 'bytes': '32803'}, {'name': 'Twig', 'bytes': '1820730'}, {'name': 'VBScript', 'bytes': '466'}]}
<?php /** * class Mlp_Db_Table_List * * Get table names for various contexts from either WordPress or the * INFORMATION SCHEMA tables. * * @version 2014.08.22 * @author Inpsyde GmbH, toscho * @license GPL */ class Mlp_Db_Table_List implements Mlp_Db_Table_List_Interface { /** * @type wpdb */ private $wpdb; /** * @type string */ private $no_tables_found = 'no_tables_found'; /** * Constructor. * * @param wpdb $wpdb */ public function __construct( wpdb $wpdb ) { $this->wpdb = $wpdb; if ( ! function_exists( 'wp_get_db_schema' ) ) { require_once ABSPATH . 'wp-admin/includes/schema.php'; } } /** * Get all table names for the current installation * * @api * @return array */ public function get_all_table_names() { $names = $this->get_names_from_db(); if ( array( $this->no_tables_found ) === $names ) { return array(); } return $names; } /** * Get standard network tables * * @api * @return array */ public function get_network_core_tables() { $all_tables = $this->get_all_table_names(); $network_tables = $this->get_network_core_table_names(); return array_intersect( $all_tables, $network_tables ); } /** * Get standard site tables * * @api * @param int $site_id * @return array */ public function get_site_core_tables( $site_id ) { $schema = wp_get_db_schema( 'blog', $site_id ); $prefix = $this->wpdb->get_blog_prefix( $site_id ); return $this->extract_names_from_schema( $schema, $prefix ); } /** * Get custom site tables * * Might return custom network tables from other plugins if the site id is * the network id. * * @api * @param int $site_id * @return array */ public function get_site_custom_tables( $site_id ) { $all_tables = $this->get_all_table_names(); $prefix = $this->wpdb->get_blog_prefix( $site_id ); $exclude = $this->get_not_custom_site_tables( $site_id, $prefix ); $out = array(); foreach ( $all_tables as $name ) { if ( $this->is_valid_custom_site_table( $name, $exclude, $prefix ) ) { $out[] = $name; } } return $out; } /** * Get this plugin's table names * * @api * @return array */ public function get_mlp_tables() { return array( $this->wpdb->base_prefix . 'mlp_languages', $this->wpdb->base_prefix . 'mlp_site_relations', $this->wpdb->base_prefix . 'multilingual_linked', ); } /** * Check whether a table name can be a custom table for a site * * @param string $name Table name to check * @param array $exclude List of invalid names * @param string $prefix Database prefix for the current site * @return bool */ private function is_valid_custom_site_table( $name, $exclude, $prefix ) { if ( in_array( $name, $exclude, true ) ) { return false; } return (bool) preg_match( '~^' . $prefix . '[^0-9]~', $name ); } /** * Get all table names that are not custom tables for a site * * @param int $site_id * @param string $site_prefix * @return array */ private function get_not_custom_site_tables( $site_id, $site_prefix ) { $core = $this->get_site_core_tables( $site_id ); if ( $site_prefix !== $this->wpdb->base_prefix ) { return $core; } // We are on the main site. This is difficult, because there is no clear // distinction between custom network tables and custom site tables. $network = $this->get_network_core_table_names(); $mlp = $this->get_mlp_tables(); return array_merge( $core, $network, $mlp ); } /** * Get standard network tables * * @return array */ private function get_network_core_table_names() { $schema = wp_get_db_schema( 'global' ); return $this->extract_names_from_schema( $schema, $this->wpdb->base_prefix ); } /** * There is no API for the names of the core tables, so we read the SQL for * the CREATE statements and extract the names per regex. * * @param string $schema * @param string $prefix * @return array */ private function extract_names_from_schema( $schema, $prefix = '' ) { $matches = array(); $pattern = '~CREATE TABLE (' . $prefix . '.*) \(~'; preg_match_all( $pattern, $schema, $matches ); if ( empty( $matches[1] ) ) { return array(); } return $matches[1]; } /** * Fetch all table names for this installation. * * @return array */ private function get_names_from_db() { $query = $this->get_sql_for_all_tables( $this->wpdb->base_prefix ); $names = $this->wpdb->get_col( $query ); // Make sure there is something in the array, so we don't try that again. if ( empty( $names ) ) { return array( $this->no_tables_found ); } return $names; } /** * Get SQL to fetch the table names. * * @param string $prefix * @return string */ private function get_sql_for_all_tables( $prefix ) { $like = $this->wpdb->esc_like( $prefix ); return "SHOW TABLES LIKE '$like%'"; } }
{'content_hash': '3784aca16b666bbc7a28a35a7dd0cf52', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 79, 'avg_line_length': 21.517391304347825, 'alnum_prop': 0.6096181046676096, 'repo_name': 'openstream/web', 'id': 'a816ec9770d38eafe6c5ac8a20c0126d557b5bc9', 'size': '4949', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'wp-content/plugins/multilingual-press/inc/db/Mlp_Db_Table_List.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3778260'}, {'name': 'HTML', 'bytes': '2616'}, {'name': 'JavaScript', 'bytes': '6800858'}, {'name': 'PHP', 'bytes': '21897162'}, {'name': 'TSQL', 'bytes': '658119'}]}
package org.jbpm.services.cdi.producer; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.kie.api.task.TaskService; import org.kie.internal.runtime.manager.TaskServiceFactory; /** * CDI based task service factory that will always deliver the same instance of the * <code>TaskService</code> that was injected into it. * */ @ApplicationScoped public class CDITaskServiceFactory implements TaskServiceFactory { @Inject private Instance<TaskService> taskService; @Override public TaskService newTaskService() { return taskService.get(); } @Override public void close() { } }
{'content_hash': 'cca1d8f835789b8b8f0b58ad05059244', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 84, 'avg_line_length': 22.3125, 'alnum_prop': 0.7380952380952381, 'repo_name': 'Aaron2000/jbpm', 'id': '0ad6c822f0188c39565418bdd767c36fb196b580', 'size': '1307', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'jbpm-services/jbpm-services-cdi/src/main/java/org/jbpm/services/cdi/producer/CDITaskServiceFactory.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '14604'}, {'name': 'HTML', 'bytes': '251'}, {'name': 'Java', 'bytes': '10294602'}, {'name': 'Protocol Buffer', 'bytes': '6420'}, {'name': 'Shell', 'bytes': '98'}]}
<div class="modal-header"> <h3>{{'_WARNING.TITLE' | translate}}</h3> </div> <div class="modal-body"> <progressbar ng-if="displayProgression" max="$root.idleMax" value="$root.idleCounter" animate="false" class="progress-striped active"></progressbar> <div>{{getContent()}}</div> <button class="btn btn-warning" ng-click="action()">{{'_CONTINUE' | translate}}</button> </div>
{'content_hash': 'ec6d1317ccf62b7af2195b28d18e0312', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 150, 'avg_line_length': 47.5, 'alnum_prop': 0.6815789473684211, 'repo_name': 'SciSpike/yaktor-ui-angular1', 'id': 'ce327eda7f75cf6219fec00c08ebf759967b9e33', 'size': '380', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'template/generated/partials/modals/warning-dialog.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '173848'}, {'name': 'HTML', 'bytes': '29547'}, {'name': 'JavaScript', 'bytes': '166152'}]}
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="UIDispatcher.Android.cs" company="MADE Apps"> // Copyright (c) MADE Apps. // </copyright> // <summary> // Defines the Android helper class for dispatching actions on the UI thread. // </summary> // -------------------------------------------------------------------------------------------------------------------- #if __ANDROID__ namespace MADE.App.Views.Threading { using System; using System.Threading.Tasks; using Android.App; using XPlat.UI.Core; /// <summary> /// Defines the Android helper class for dispatching actions on the UI thread. /// </summary> public class UIDispatcher : IUIDispatcher { /// <summary> /// Gets the platform specified UI object to use as a reference. /// </summary> public object Reference { get; private set; } /// <summary> /// Gets the instance of the Android CoreDispatcher. /// </summary> internal CoreDispatcher Instance { get; private set; } /// <summary> /// Sets the platform specific UI object to use as a reference for dispatching actions on the UI thread. /// </summary> /// <param name="reference"> /// The platform specific UI reference object. /// </param> public void SetReference(object reference) { this.Instance = null; if (!(reference is Activity activity)) { throw new UIDispatcherException("Cannot initialize the UIDispatcher without an Activity."); } this.Reference = activity; this.Instance = new CoreDispatcher(activity); } /// <summary> /// Schedules the provided action on the UI thread from a worker thread. /// </summary> /// <param name="action"> /// The action to run on the dispatcher. /// </param> public void Run(Action action) { this.CheckInitialized(); if (action == null) { return; } this.Run(CoreDispatcherPriority.Normal, action); } /// <summary> /// Schedules the provided action on the UI thread from a worker thread. /// </summary> /// <param name="priority"> /// The priority. /// </param> /// <param name="action"> /// The action to run on the dispatcher. /// </param> public async void Run(CoreDispatcherPriority priority, Action action) { this.CheckInitialized(); if (action == null) { return; } await this.Instance.RunAsync(() => action()); } /// <summary> /// Schedules the provided action on the UI thread from a worker thread. /// </summary> /// <param name="action"> /// The action to run on the dispatcher. /// </param> /// <returns> /// An asynchronous operation. /// </returns> public Task RunAsync(Action action) { this.CheckInitialized(); return action == null ? Task.CompletedTask : this.RunAsync(CoreDispatcherPriority.Normal, action); } /// <summary> /// Schedules the provided action on the UI thread from a worker thread. /// </summary> /// <param name="priority"> /// The priority. /// </param> /// <param name="action"> /// The action to run on the dispatcher. /// </param> /// <returns> /// An asynchronous operation. /// </returns> public Task RunAsync(CoreDispatcherPriority priority, Action action) { this.CheckInitialized(); return action == null ? Task.CompletedTask : this.Instance.RunAsync(() => action()); } private void CheckInitialized() { if (this.Instance == null) { throw new UIDispatcherException("Cannot run an action as the UIDispatcher has no UI reference set."); } } } } #endif
{'content_hash': '66237f551521362f0f41b0409abb9527', 'timestamp': '', 'source': 'github', 'line_count': 137, 'max_line_length': 120, 'avg_line_length': 31.233576642335766, 'alnum_prop': 0.5108670250058425, 'repo_name': 'MADE-Apps/MADE-App-Components', 'id': '7979ccc3c680b9ad83eced935f77ccaee80a786d', 'size': '4281', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dependabot/nuget/Xamarin.AndroidX.AppCompat-1.2.0.5', 'path': 'src/MADE.App.Views/Threading/UIDispatcher.Android.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '323554'}]}
<?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> <groupId>org.uberfire.demo</groupId> <artifactId>notes</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <name>Simple Notes Application</name> <properties> <version.assembly.plugin>2.4</version.assembly.plugin> <version.buildhelper.plugin>1.7</version.buildhelper.plugin> <version.bundle.plugin>2.3.7</version.bundle.plugin> <version.clean.plugin>2.5</version.clean.plugin> <version.compiler.plugin>3.0</version.compiler.plugin> <version.dependency.plugin>2.8</version.dependency.plugin> <version.failsafe.plugin>2.12.3</version.failsafe.plugin> <version.jar.plugin>2.4</version.jar.plugin> <version.resources.plugin>2.6</version.resources.plugin> <version.source.plugin>2.2.1</version.source.plugin> <version.surefire.plugin>2.12.3</version.surefire.plugin> <version.war.plugin>2.3</version.war.plugin> <!-- Cross plugins settings --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- maven-compiler-plugin --> <maven.compiler.target>1.6</maven.compiler.target> <maven.compiler.source>1.6</maven.compiler.source> <!-- Options to override the compiler arguments directly on the compiler arument line to separate between what the IDE understands as the source level and what the Maven compiler actually use. --> <maven.compiler.argument.target>${maven.compiler.target}</maven.compiler.argument.target> <maven.compiler.argument.source>${maven.compiler.source}</maven.compiler.argument.source> </properties> <modules> <module>notes-bom</module> <module>notes-parent-with-dependencies</module> <module>notes-model</module> <module>notes-mail</module> <module>notes-persistence</module> <module>notes-api</module> <module>notes-showcase</module> </modules> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>${version.dependency.plugin}</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>1.7</version> <executions> <execution> <goals> <goal>parse-version</goal> </goals> </execution> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>target/generated-sources/annotations</source> </sources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-project-info-reports-plugin</artifactId> <version>2.7</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <fork>false</fork> <meminitial>128m</meminitial> <maxmem>512m</maxmem> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.18</version> <configuration> <includes> <include>**/*Test.java</include> </includes> <excludes> <exclude>**/*IntegrationTest.java</exclude> </excludes> <argLine>-Xmx1024m -XX:MaxPermSize=128m</argLine> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.12</version> <executions> <execution> <goals> <goal>integration-test</goal> </goals> </execution> </executions> <configuration> <includes> <include>**/*IntegrationTest.java</include> </includes> <argLine>-Xmx1024m -XX:MaxPermSize=128m</argLine> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>2.1.2</version> <executions> <execution> <id>jar</id> <goals> <goal>jar</goal> </goals> <configuration> <archive> <manifestEntries> <Bundle-ManifestVersion>2</Bundle-ManifestVersion> <Bundle-SymbolicName>${project.artifactId}.source</Bundle-SymbolicName> <Bundle-Version>${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${osgi.snapshot.qualifier}</Bundle-Version> <Bundle-Name>${project.name}</Bundle-Name> <Bundle-Vendor>${project.organization.name}</Bundle-Vendor> <Eclipse-SourceBundle>${project.artifactId};version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${osgi.snapshot.qualifier}";roots:="."</Eclipse-SourceBundle> </manifestEntries> </archive> </configuration> </execution> <execution> <id>test-jar</id> <goals> <goal>test-jar</goal> </goals> <configuration> <archive> <manifestEntries> <Bundle-ManifestVersion>2</Bundle-ManifestVersion> <Bundle-SymbolicName>${project.artifactId}.tests.source</Bundle-SymbolicName> <Bundle-Version>${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${osgi.snapshot.qualifier}</Bundle-Version> <Bundle-Name>${project.name}</Bundle-Name> <Bundle-Vendor>${project.organization.name}</Bundle-Vendor> <Eclipse-SourceBundle>${project.artifactId}.tests;version="${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${osgi.snapshot.qualifier}";roots:="."</Eclipse-SourceBundle> </manifestEntries> </archive> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>versions-maven-plugin</artifactId> <version>2.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <configuration> <!-- Manually push changes (including git tags) after nexus staged repo is successfully closed --> <pushChanges>false</pushChanges> <autoVersionSubmodules>true</autoVersionSubmodules> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> </plugin> <!-- Site plugin >= 3.3 required for compat with Maven 3.1.x --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.3</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>cobertura-maven-plugin</artifactId> <configuration> <instrumentation> <excludes> <exclude>org/drools/**/*Test.class</exclude> </excludes> </instrumentation> </configuration> <executions> <execution> <goals> <goal>clean</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <links> <link>http://docs.oracle.com/javase/6/docs/api</link> </links> <minmemory>128m</minmemory> <maxmemory>512m</maxmemory> <author>false</author> <breakiterator>true</breakiterator> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>${version.war.plugin}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.3.1</version> <executions> <!-- No OSGi manifestEntries for <goal>jar</goal>: if it supported, then felix has already added them --> <execution> <id>test-jar</id> <goals> <goal>test-jar</goal> </goals> <configuration> <excludes> <exclude>**/logback-test.xml</exclude> </excludes> <archive> <manifestEntries> <Bundle-SymbolicName>${project.artifactId}.tests</Bundle-SymbolicName> <Bundle-Version>${parsedVersion.majorVersion}.${parsedVersion.minorVersion}.${parsedVersion.incrementalVersion}.${osgi.snapshot.qualifier}</Bundle-Version> <Bundle-Name>${project.name}</Bundle-Name> <Bundle-Vendor>${project.organization.name}</Bundle-Vendor> </manifestEntries> </archive> </configuration> </execution> </executions> <configuration> <archive> <manifest> <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> </archive> </configuration> </plugin> <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> <plugin> <groupId>org.eclipse.m2e</groupId> <artifactId>lifecycle-mapping</artifactId> <version>1.0.0</version> <configuration> <lifecycleMappingMetadata> <pluginExecutions> <pluginExecution> <pluginExecutionFilter> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <versionRange>[1.7,)</versionRange> <goals> <goal>parse-version</goal> </goals> </pluginExecutionFilter> <action> <ignore></ignore> </action> </pluginExecution> <pluginExecution> <pluginExecutionFilter> <groupId>org.codehaus.mojo</groupId> <artifactId>gwt-maven-plugin</artifactId> <versionRange>[2.3.0,)</versionRange> <goals> <goal>resources</goal> </goals> </pluginExecutionFilter> <action> <execute/> </action> </pluginExecution> <pluginExecution> <pluginExecutionFilter> <groupId>org.jboss.errai</groupId> <artifactId>jacoco-gwt-maven-plugin</artifactId> <versionRange>[0.0,)</versionRange> <goals> <goal>prepare-agent</goal> </goals> </pluginExecutionFilter> <action> <ignore/> </action> </pluginExecution> </pluginExecutions> </lifecycleMappingMetadata> </configuration> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <!-- Entry needed to provide parsed version properties --> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addDefaultImplementationEntries>true</addDefaultImplementationEntries> </manifest> </archive> </configuration> </plugin> <plugin> <artifactId>maven-source-plugin</artifactId> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> </plugin> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>${version.clean.plugin}</version> <configuration> <filesets> <fileset> <directory>${basedir}</directory> <includes> <include>src/main/webapp/WEB-INF/deploy/</include> <include>src/main/webapp/WEB-INF/classes/</include> <include>src/main/webapp/WEB-INF/lib/</include> <include>**/gwt-unitCache/**</include> <include>.errai/</include> <include>.niogit/**</include> </includes> </fileset> </filesets> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>jboss</id> <url>https://repository.jboss.org/nexus/content/groups/public/</url> </repository> </repositories> </project>
{'content_hash': '53636983f20812213dd5ad4544d3c6f4', 'timestamp': '', 'source': 'github', 'line_count': 408, 'max_line_length': 236, 'avg_line_length': 36.818627450980394, 'alnum_prop': 0.5473971508454267, 'repo_name': 'porcelli/javaee2microservices', 'id': 'e78ffe9bf307b96bf6435faa986303853a831dfa', 'size': '15022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '8011'}, {'name': 'Java', 'bytes': '15278'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace DioLive.Cache.WebUI.Models { public class Budget { public Budget() { Categories = new HashSet<Category>(); Purchases = new HashSet<Purchase>(); Shares = new HashSet<Share>(); Plans = new HashSet<Plan>(); } public Guid Id { get; set; } public string Name { get; set; } public string AuthorId { get; set; } public byte Version { get; set; } public virtual ApplicationUser Author { get; set; } public virtual ICollection<Category> Categories { get; set; } public virtual ICollection<Purchase> Purchases { get; set; } public virtual ICollection<Share> Shares { get; set; } public virtual ICollection<Plan> Plans { get; set; } public static Task<Budget> GetWithShares(Data.ApplicationDbContext context, Guid id) { return context.Budget.Include(b => b.Shares) .SingleOrDefaultAsync(b => b.Id == id); } public bool HasRights(string userId, ShareAccess requiredAccess) { return this.AuthorId == userId || this.Shares.Any(s => s.UserId == userId && s.Access.HasFlag(requiredAccess)); } } }
{'content_hash': 'ef778ada849264a29dd6d7cb8f381708', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 93, 'avg_line_length': 27.96, 'alnum_prop': 0.6008583690987125, 'repo_name': 'diolive/cache', 'id': '23d95c9b4b2238ae5df0eb0dcbc237b0070c9c5e', 'size': '1400', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'DioLive.Cache/src/DioLive.Cache.WebUI/Models/Budget.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '218980'}, {'name': 'CSS', 'bytes': '3527'}, {'name': 'JavaScript', 'bytes': '9106'}, {'name': 'PowerShell', 'bytes': '49409'}]}
<project name="RoboSpice UI SpiceList"> <skin> <groupId>org.apache.maven.skins</groupId> <artifactId>maven-fluido-skin</artifactId> <version>1.3.0</version> </skin> <custom> <fluidoSkin> <googlePlusOne /> </fluidoSkin> </custom> <version position="right"/> <poweredBy> <logo name="octo" href="http://octo.com" img="https://raw.github.com/octo-online/robospice/master/gfx/octo-ascii-logo-blue.png"/> </poweredBy> <body> <!-- Include all info and reports --> <menu ref="reports" /> </body> </project>
{'content_hash': 'ac727564cc68b1216a79d06f2f25d2a9', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 98, 'avg_line_length': 22.48, 'alnum_prop': 0.6316725978647687, 'repo_name': 'hgl888/robospice', 'id': '3b480284990118cdad1de68d0ed71e06ef3560ba', 'size': '562', 'binary': False, 'copies': '17', 'ref': 'refs/heads/release', 'path': 'extensions/robospice-ui-spicelist-parent/robospice-ui-spicelist/src/site/site.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '871787'}, {'name': 'Shell', 'bytes': '370'}]}
package gmapsfx; import gmapsfx.javascript.JavaFxWebEngine; import gmapsfx.javascript.JavascriptArray; import gmapsfx.javascript.JavascriptObject; import gmapsfx.javascript.JavascriptRuntime; import javafx.application.Application; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.concurrent.Worker; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.web.WebView; import javafx.stage.Stage; import netscape.javascript.JSObject; /** * @author Geoff Capper */ public class ArrayTester extends Application { protected WebView webview; protected JavaFxWebEngine webengine; public static void main(String[] args) { System.setProperty("java.net.useSystemProxies", "true"); launch(args); } @Override public void start(final Stage stage) throws Exception { webview = new WebView(); webengine = new JavaFxWebEngine(webview.getEngine()); JavascriptRuntime.setDefaultWebEngine(webengine); BorderPane bp = new BorderPane(); bp.setCenter(webview); webengine.getLoadWorker().stateProperty().addListener( new ChangeListener<Worker.State>() { public void changed(ObservableValue ov, Worker.State oldState, Worker.State newState) { if (newState == Worker.State.SUCCEEDED) { runTests(); //Platform.exit(); } } }); webengine.load(getClass().getResource("/html/arrays.html").toExternalForm()); Scene scene = new Scene(bp, 600, 600); stage.setScene(scene); stage.show(); } private void runTests() { JSObject jsWin = (JSObject) webengine.executeScript("window"); jsWin.call("displayTest", new Object[]{null}); JavascriptArray ary = new JavascriptArray(); int len = 0; for (int i = 0; i < 6; i++) { len = ary.push("String " + i); System.out.println("testArrays push " + i + " gives len: " + len); } System.out.println("testArrays toString: " + ary.toString()); ary.reverse(); System.out.println("testArrays reverse toString: " + ary.toString()); ary.reverse(); Object obj = ary.pop(); System.out.println("testArrays popped: " + obj); System.out.println("testArrays popped toString: " + ary.toString()); TestJSO jso = new TestJSO(); jso.setTestName("Test 1"); ary.unshift(jso); System.out.println("testArrays unshift JsO toString: " + ary.toString()); Object jso1 = ary.shift(); System.out.println("testArrays shift JsO: " + jso1); System.out.println("testArrays shift JsO reference equality: " + (jso == jso1)); System.out.println("testArrays shift JsO toString: " + ary.toString()); ary.push(jso); System.out.println("testArrays push JsO toString: " + ary.toString()); jsWin.call("displayArray", ary); jso.setTestName("Altered Test 1"); jsWin.call("displayArray", ary); System.out.println("testArrays alter JsO toString: " + ary.toString()); Object jso2 = ary.get(ary.length() - 1); System.out.println("testArrays get JsO2: " + jso2); jsWin.call("iterateArray", ary); jsWin.call("displayTestEnd", new Object[]{null}); } class TestJSO extends JavascriptObject { public TestJSO() { super("Object"); } public String getTestName() { return getProperty("testName", String.class); } public void setTestName(String testName) { setProperty("testName", testName); } @Override public String toString() { return getTestName(); } } }
{'content_hash': '4a6f099ccff7f883373fc342bd6e6ce4', 'timestamp': '', 'source': 'github', 'line_count': 140, 'max_line_length': 107, 'avg_line_length': 28.12857142857143, 'alnum_prop': 0.6069070594210259, 'repo_name': 'devinmcgloin/UCSDGraphs', 'id': '7c49974c63043c8707c1e541f1e456c98db44e6a', 'size': '4535', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/gmapsfx/ArrayTester.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '554'}, {'name': 'HTML', 'bytes': '601'}, {'name': 'Java', 'bytes': '304502'}, {'name': 'JavaScript', 'bytes': '839'}]}
package net.chrisrichardson.foodToGo.viewOrdersTransactionScripts.dao; import java.util.*; import net.chrisrichardson.foodToGo.domain.*; import net.chrisrichardson.foodToGo.util.*; import org.jmock.cglib.*; import org.jmock.core.*; import org.springframework.orm.ibatis.*; public class OrderDAOIBatisImplMockTests extends MockObjectTestCase { private Mock mockSqlMapClientTemplate; private OrderDAOIBatisImpl dao; private Mock mockPagedQueryExecutor; protected void setUp() throws Exception { super.setUp(); mockSqlMapClientTemplate = new Mock(SqlMapClientTemplate.class); SqlMapClientTemplate sqlMapClientTemplate = (SqlMapClientTemplate) mockSqlMapClientTemplate .proxy(); mockPagedQueryExecutor = new Mock(IBatisPagedQueryExecutor.class); dao = new OrderDAOIBatisImpl(sqlMapClientTemplate, (IBatisPagedQueryExecutor) mockPagedQueryExecutor.proxy()); } public void testFindOrders() throws Exception { OrderSearchCriteria criteria = new OrderSearchCriteria(); PagedQueryResult executorResult = new PagedQueryResult( Collections.EMPTY_LIST, true); mockPagedQueryExecutor.expects(once()).method("execute").with( new Constraint[] { eq("findOrders"), eq(0), eq(10), eq(criteria), eq(true) }).will( returnValue(executorResult)); PagedQueryResult result = dao.findOrders(0, 10, criteria); assertSame(result, executorResult); } }
{'content_hash': '0ea7a932152f47d334f2aaca3148aab8', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 93, 'avg_line_length': 30.0, 'alnum_prop': 0.7541666666666667, 'repo_name': 'cer/pia', 'id': '0ea5a9691678f274e73095cbc0d3d9ff70d1839d', 'size': '2061', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pia-ch-11-queries-ibatis/src/test/java/net/chrisrichardson/foodToGo/viewOrdersTransactionScripts/dao/OrderDAOIBatisImplMockTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '712638'}]}
This is Zeppelin's frontend project. ## Compile Zeppelin web ### New environment If you want to compile the WebApplication only, you will have to simply run `mvn package` in this folder. This will Download all the dependencies including node js and npm (you will find the binaries in the folder `zeppelin-web/node`). We are supposed to provide some **helper script** for __bower__ and __grunt__, but they are currently outdated, so you might want install them on your machine and use them instead. ### Configured environment Here are the basic commands to compile the WebApplication with a configured environment (Installed grunt, bower, npm) **Build the application for production** `./grunt build` **Run the application in dev mode** ``./grunt serve`` This will launch a Zeppelin WebApplication on port **9000** and update on code changes. (You will need to have Zeppelin running on the side) #### Troubleshooting In case of the error `ECMDERR Failed to execute "git ls-remote --tags --heads git://xxxxx", exit code of #128` change your git config with `git config --global url."https://".insteadOf git://` **OR** Try to add to the `.bowerrc` file the following content: ``` "proxy" : "http://<host>:<port>", "https-proxy" : "http://<host>:<port>" ``` and retry to build again. ## Contribute on Zeppelin Web If you wish to help us and contribute to Zeppelin WebApplication, please look at [Zeppelin WebApplication's contribution guideline](CONTRIBUTING.md).
{'content_hash': '09aac5d9ed00c8da39fa27bffb93e654', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 180, 'avg_line_length': 30.958333333333332, 'alnum_prop': 0.7355316285329744, 'repo_name': 'keedio/incubator-zeppelin', 'id': 'cbd7d73b2d3befcf07a760aa85a1dfc98a02d79c', 'size': '1513', 'binary': False, 'copies': '49', 'ref': 'refs/heads/master', 'path': 'zeppelin-web/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '41797'}, {'name': 'HTML', 'bytes': '204868'}, {'name': 'Java', 'bytes': '1502160'}, {'name': 'JavaScript', 'bytes': '123723'}, {'name': 'Python', 'bytes': '20714'}, {'name': 'Scala', 'bytes': '114379'}, {'name': 'Shell', 'bytes': '37890'}, {'name': 'Thrift', 'bytes': '2528'}, {'name': 'XSLT', 'bytes': '1326'}]}
wx_option(wxUSE_GUI "Use GUI" ON) if(CMAKE_OSX_SYSROOT MATCHES iphoneos) set(IPHONE ON) # workaround a bug where try_compile (and functions using it, # like find_package, check_c_source_compiles) fails set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) endif() if(WIN32) set(wxDEFAULT_TOOLKIT msw) set(wxTOOLKIT_OPTIONS msw gtk2 gtk3 qt) set(wxPLATFORM WIN32) elseif(APPLE AND IPHONE) set(wxDEFAULT_TOOLKIT osx_iphone) set(wxTOOLKIT_OPTIONS osx_iphone) set(wxPLATFORM OSX) elseif(APPLE) set(wxDEFAULT_TOOLKIT osx_cocoa) set(wxTOOLKIT_OPTIONS osx_cocoa gtk2 gtk3 gtk4 qt) set(wxPLATFORM OSX) elseif(UNIX) set(wxDEFAULT_TOOLKIT gtk3) set(wxTOOLKIT_OPTIONS gtk2 gtk3 gtk4 motif qt) set(wxPLATFORM UNIX) else() message(FATAL_ERROR "Unsupported platform") endif() wx_option(wxBUILD_TOOLKIT "Toolkit used by wxWidgets" ${wxDEFAULT_TOOLKIT} STRINGS ${wxTOOLKIT_OPTIONS}) # TODO: set to univ for universal build set(wxBUILD_WIDGETSET "") # Create shortcut variable for easy toolkit tests string(TOUPPER ${wxBUILD_TOOLKIT} toolkit_upper) set(WX${toolkit_upper} ON) if(wxBUILD_TOOLKIT MATCHES "^gtk*") set(WXGTK ON) elseif(wxBUILD_TOOLKIT MATCHES "^osx*") set(WXOSX ON) elseif(wxBUILD_TOOLKIT MATCHES "qt") set(WXQT ON) endif() set(wxTOOLKIT_DEFINITIONS __WX${toolkit_upper}__) if(NOT wxUSE_GUI) set(wxBUILD_TOOLKIT "base") string(TOUPPER ${wxBUILD_TOOLKIT} toolkit_upper) set(WX${toolkit_upper} ON) set(wxTOOLKIT_DEFINITIONS __WX${toolkit_upper}__) endif() # Initialize toolkit variables if(wxUSE_GUI) set(wxTOOLKIT_INCLUDE_DIRS) set(wxTOOLKIT_LIBRARIES) set(wxTOOLKIT_VERSION) if(WXGTK) if(WXGTK4) set(gtk_lib GTK4) elseif(WXGTK3) set(gtk_lib GTK3) elseif(WXGTK2) set(gtk_lib GTK2) endif() find_package(${gtk_lib} REQUIRED) list(APPEND wxTOOLKIT_INCLUDE_DIRS ${${gtk_lib}_INCLUDE_DIRS}) list(APPEND wxTOOLKIT_LIBRARIES ${${gtk_lib}_LIBRARIES}) list(APPEND wxTOOLKIT_DEFINITIONS ${${gtk_lib}_DEFINITIONS}) list(APPEND wxTOOLKIT_DEFINITIONS __WXGTK__) set(wxTOOLKIT_VERSION ${${gtk_lib}_VERSION}) if(WIN32 AND MSVC) if(WXGTK4) list(APPEND wxTOOLKIT_LIBRARIES libgtk-4.dll.a libgdk-4.dll.a ) elseif(WXGTK3) list(APPEND wxTOOLKIT_LIBRARIES libgtk-3.dll.a libgdk-3.dll.a ) elseif(WXGTK2) list(APPEND wxTOOLKIT_LIBRARIES gtk-win32-2.0 gdk-win32-2.0 ) endif() list(APPEND wxTOOLKIT_LIBRARIES gio-2.0 pangocairo-1.0 gdk_pixbuf-2.0 cairo pango-1.0 gobject-2.0 gthread-2.0 glib-2.0 ) endif() endif() # We need X11 for non-GTK Unix ports (X11, Motif) and for GTK with X11 # support, but not for Wayland-only GTK (which is why we have to do this after # find_package(GTKx) above, as this is what sets wxHAVE_GDK_X11). if(UNIX AND NOT APPLE AND NOT WIN32 AND (WXX11 OR WXMOTIF OR (WXGTK AND wxHAVE_GDK_X11))) find_package(X11 REQUIRED) list(APPEND wxTOOLKIT_INCLUDE_DIRS ${X11_INCLUDE_DIR}) list(APPEND wxTOOLKIT_LIBRARIES ${X11_LIBRARIES}) endif() if(WXQT) set(QT_COMPONENTS Core Widgets Gui OpenGL Test) foreach(QT_COMPONENT ${QT_COMPONENTS}) find_package(Qt5 COMPONENTS ${QT_COMPONENT} REQUIRED) list(APPEND wxTOOLKIT_INCLUDE_DIRS ${Qt5${QT_COMPONENT}_INCLUDE_DIRS}) list(APPEND wxTOOLKIT_LIBRARIES ${Qt5${QT_COMPONENT}_LIBRARIES}) list(APPEND wxTOOLKIT_DEFINITIONS ${Qt5${QT_COMPONENT}_COMPILE_DEFINITIONS}) endforeach() set(wxTOOLKIT_VERSION ${Qt5Core_VERSION}) endif() if(APPLE) list(APPEND wxTOOLKIT_DEFINITIONS __WXMAC__ __WXOSX__) endif() endif() # wxUSE_GUI
{'content_hash': 'b410f0c07f85c361faa4becd02546890', 'timestamp': '', 'source': 'github', 'line_count': 132, 'max_line_length': 89, 'avg_line_length': 29.613636363636363, 'alnum_prop': 0.6566896904579176, 'repo_name': 'ric2b/Vivaldi-browser', 'id': 'bcbbd75491dd07d14351de23c23796b3da5af862', 'size': '4345', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'update_notifier/thirdparty/wxWidgets/build/cmake/toolkit.cmake', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=utf-8"> <TITLE>NIST DOM HTML Test - Applet</TITLE> <script type='text/javascript' src='selfhtml.js'></script><script charset='UTF-8' type='text/javascript' src='HTMLAppletElement03.js'></script><script type='text/javascript'>function loadComplete() { startTest(); }</script></HEAD> <BODY onload="loadComplete()"> <P> <APPLET ALIGN="bottom" ALT="Applet Number 1" ARCHIVE="" CODE="org/w3c/domts/DOMTSApplet.class" CODEBASE="applets" HEIGHT="306" HSPACE="0" NAME="applet1" VSPACE="0" WIDTH="301"></APPLET> </P> </BODY> </HTML>
{'content_hash': '63a66461db7d640619a8fa822ac46202', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 230, 'avg_line_length': 55.166666666666664, 'alnum_prop': 0.7099697885196374, 'repo_name': 'ondra-novak/blink', 'id': '75e8e594c29fe84d1d248e904beeba241e238b15', 'size': '662', 'binary': False, 'copies': '36', 'ref': 'refs/heads/nw', 'path': 'LayoutTests/dom/html/level2/html/HTMLAppletElement03.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '12983'}, {'name': 'Bison', 'bytes': '64327'}, {'name': 'C', 'bytes': '1487362'}, {'name': 'C++', 'bytes': '40237536'}, {'name': 'CSS', 'bytes': '537586'}, {'name': 'Java', 'bytes': '66510'}, {'name': 'JavaScript', 'bytes': '26502253'}, {'name': 'Makefile', 'bytes': '677'}, {'name': 'Objective-C', 'bytes': '23525'}, {'name': 'Objective-C++', 'bytes': '377730'}, {'name': 'PHP', 'bytes': '166434'}, {'name': 'Perl', 'bytes': '585757'}, {'name': 'Python', 'bytes': '3997910'}, {'name': 'Ruby', 'bytes': '141818'}, {'name': 'Shell', 'bytes': '8806'}, {'name': 'XSLT', 'bytes': '49099'}]}
docid: sample-code title: Sample code layout: docs permalink: /docs/sample-code.html prev: building-from-source.html --- *Note: the samples are licensed for non-commercial or evaluation purposes only, not the BSD license used for Fresco itself.* Fresco's GitHub repository contains several samples to demonstrate how to use Fresco in your apps. The samples are available in source form only. Follow the [build instructions](building-from-source.html) to set up your dev environment to build and run them. ### The zoomable library The [zoomable library](https://github.com/facebook/fresco/blob/master/samples/zoomable) features a `ZoomableDraweeView` class that supports gestures such as pinch-to-zoom and panning of a Drawee image. ### The comparison app The comparison app lets the user do a proper, apples-to-apples comparison of Fresco with [Picasso](http://square.github.io/picasso), [Universal Image Loader](https://github.com/nostra13/Android-Universal-Image-Loader), [Volley](https://developer.android.com/training/volley/index.html)'s image loader, and [Glide](https://github.com/bumptech/glide). Fresco allows you to also compare its performance with OkHttp as its network layer. You can also see the performance of Drawee running over Volley instead of Fresco's image pipeline. The app offers you a choice of images from your local camera or from the Internet. The network images come from [Imgur](http://imgur.com). You can build, install, and run a controlled test of any combination of loaders using the [run_comparison.py](https://github.com/facebook/fresco/blob/master/run_comparison.py) script. The following command will run them all on a connected ARM v7 device: ```./run_comparison.py -c armeabi-v7a``` ### The demo app The demo app shows the wide variety of images Fresco supports - baseline and progressive JPEG, both simple, extended, and animated WebP, PNG, and animated GIF. We also show an image from a data URI. ### The round app The round app shows the same image scaled in several different ways, with and without a circle applied. ### The uri app The uri app loads an image from an uri provided via TextView. It's handy to test whether Fresco is able to display a particular image.
{'content_hash': '59fa356343750a5f025e760239a69d37', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 349, 'avg_line_length': 55.7, 'alnum_prop': 0.7791741472172352, 'repo_name': 'desmond1121/fresco', 'id': '63458b69f198d018290a8da4f4aa677ad046b751', 'size': '2232', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/_docs/06-sample-apps.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '22418'}, {'name': 'C++', 'bytes': '212041'}, {'name': 'IDL', 'bytes': '1003'}, {'name': 'Java', 'bytes': '2750756'}, {'name': 'Makefile', 'bytes': '7247'}, {'name': 'Prolog', 'bytes': '153'}, {'name': 'Python', 'bytes': '10351'}, {'name': 'Shell', 'bytes': '102'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '0edfedab85f72258319cf699aefb63cc', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '4b400aa39fdbb676768ffce6d8468711b0e0d40e', 'size': '172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Rosaceae/Pyrus/Pyrus spectabilis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
id: using-a-listview title: Using List Views layout: docs category: The Basics permalink: docs/using-a-listview.html next: network previous: using-a-scrollview --- React Native provides a suite of components for presenting lists of data. Generally, you'll want to use either [FlatList](docs/flatlist.html) or [SectionList](docs/sectionlist.html). The `FlatList` component displays a scrolling list of changing, but similarly structured, data. `FlatList` works well for long lists of data, where the number of items might change over time. Unlike the more generic [`ScrollView`](docs/using-a-scrollview.html), the `FlatList` only renders elements that are currently showing on the screen, not all the elements at once. The `FlatList` component requires two props: `data` and `renderItem`. `data` is the source of information for the list. `renderItem` takes one item from the source and returns a formatted component to render. This example creates a simple `FlatList` of hardcoded data. Each item in the `data` props is rendered as a `Text` component. The `FlatListBasics` component then renders the `FlatList` and all `Text` components. ```SnackPlayer?name=FlatList%20Basics import React, { Component } from 'react'; import { AppRegistry, FlatList, StyleSheet, Text, View } from 'react-native'; export default class FlatListBasics extends Component { render() { return ( <View style={styles.container}> <FlatList data={[ {key: 'Devin'}, {key: 'Jackson'}, {key: 'James'}, {key: 'Joel'}, {key: 'John'}, {key: 'Jillian'}, {key: 'Jimmy'}, {key: 'Julie'}, ]} renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 22 }, item: { padding: 10, fontSize: 18, height: 44, }, }) // skip this line if using Create React Native App AppRegistry.registerComponent('AwesomeProject', () => FlatListBasics); ``` If you want to render a set of data broken into logical sections, maybe with section headers, similar to `UITableView`s on iOS, then a [SectionList](docs/sectionlist.html) is the way to go. ```SnackPlayer?name=SectionList%20Basics import React, { Component } from 'react'; import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native'; export default class SectionListBasics extends Component { render() { return ( <View style={styles.container}> <SectionList sections={[ {title: 'D', data: ['Devin']}, {title: 'J', data: ['Jackson', 'James', 'Jillian', 'Jimmy', 'Joel', 'John', 'Julie']}, ]} renderItem={({item}) => <Text style={styles.item}>{item}</Text>} renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>} keyExtractor={(item, index) => index} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 22 }, sectionHeader: { paddingTop: 2, paddingLeft: 10, paddingRight: 10, paddingBottom: 2, fontSize: 14, fontWeight: 'bold', backgroundColor: 'rgba(247,247,247,1.0)', }, item: { padding: 10, fontSize: 18, height: 44, }, }) // skip this line if using Create React Native App AppRegistry.registerComponent('AwesomeProject', () => SectionListBasics); ``` One of the most common uses for a list view is displaying data that you fetch from a server. To do that, you will need to [learn about networking in React Native](docs/network.html).
{'content_hash': 'f78c7037f24ef51c018dc78db5dc8a4c', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 370, 'avg_line_length': 33.99082568807339, 'alnum_prop': 0.6547908232118759, 'repo_name': 'kesha-antonov/react-native', 'id': '5a80df16862acb4ed6945b296ee61d0fbe3eb744', 'size': '3709', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'docs/using-a-listview.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '15392'}, {'name': 'Batchfile', 'bytes': '683'}, {'name': 'C', 'bytes': '52068'}, {'name': 'C++', 'bytes': '879246'}, {'name': 'CSS', 'bytes': '45523'}, {'name': 'HTML', 'bytes': '162528'}, {'name': 'IDL', 'bytes': '2122'}, {'name': 'Java', 'bytes': '3031180'}, {'name': 'JavaScript', 'bytes': '3751921'}, {'name': 'Kotlin', 'bytes': '698'}, {'name': 'Makefile', 'bytes': '7452'}, {'name': 'Objective-C', 'bytes': '1721900'}, {'name': 'Objective-C++', 'bytes': '310766'}, {'name': 'Prolog', 'bytes': '287'}, {'name': 'Python', 'bytes': '109316'}, {'name': 'Ruby', 'bytes': '15238'}, {'name': 'Shell', 'bytes': '47663'}]}
namespace Apex.AI.Teaching { /// <summary> /// Action class for nulling the resource target. /// </summary> /// <seealso cref="Apex.AI.ActionBase" /> public sealed class SetResourceTargetToNull : ActionBase { public override void Execute(IAIContext context) { ((AIContext)context).resourceTarget = null; } } }
{'content_hash': '8a85dfeb2efbd63590f46e407c94c3da', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 60, 'avg_line_length': 26.714285714285715, 'alnum_prop': 0.6096256684491979, 'repo_name': 'RamiAhmed/ApexTeaching', 'id': '1ed2ea3eea582daf04e79c4c717216dc8f89a629', 'size': '376', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ApexTeaching/Assets/Apex Teaching/04_UtilityAI/Scripts/Actions/SetResourceTargetToNull.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '176173'}, {'name': 'GLSL', 'bytes': '186'}]}
Metrics* g_metrics = NULL; namespace { #ifndef _WIN32 /// Compute a platform-specific high-res timer value that fits into an int64. int64_t HighResTimer() { timeval tv; if (gettimeofday(&tv, NULL) < 0) Fatal("gettimeofday: %s", strerror(errno)); return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec; } /// Convert a delta of HighResTimer() values to microseconds. int64_t TimerToMicros(int64_t dt) { // No conversion necessary. return dt; } #else int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) { return ((int64_t)i.HighPart) << 32 | i.LowPart; } int64_t HighResTimer() { LARGE_INTEGER counter; if (!QueryPerformanceCounter(&counter)) Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str()); return LargeIntegerToInt64(counter); } int64_t TimerToMicros(int64_t dt) { static int64_t ticks_per_sec = 0; if (!ticks_per_sec) { LARGE_INTEGER freq; if (!QueryPerformanceFrequency(&freq)) Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str()); ticks_per_sec = LargeIntegerToInt64(freq); } // dt is in ticks. We want microseconds. return (dt * 1000000) / ticks_per_sec; } #endif } // anonymous namespace ScopedMetric::ScopedMetric(Metric* metric) { metric_ = metric; if (!metric_) return; start_ = HighResTimer(); } ScopedMetric::~ScopedMetric() { if (!metric_) return; metric_->count++; int64_t dt = TimerToMicros(HighResTimer() - start_); metric_->sum += dt; } Metric* Metrics::NewMetric(const string& name) { Metric* metric = new Metric; metric->name = name; metric->count = 0; metric->sum = 0; metrics_.push_back(metric); return metric; } void Metrics::Report() { int width = 0; for (vector<Metric*>::iterator i = metrics_.begin(); i != metrics_.end(); ++i) { width = max((int)(*i)->name.size(), width); } printf("%-*s\t%-6s\t%-9s\t%s\n", width, "metric", "count", "avg (us)", "total (ms)"); for (vector<Metric*>::iterator i = metrics_.begin(); i != metrics_.end(); ++i) { Metric* metric = *i; double total = metric->sum / (double)1000; double avg = metric->sum / (double)metric->count; printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(), metric->count, avg, total); } } uint64_t Stopwatch::Now() const { return TimerToMicros(HighResTimer()); } int64_t GetTimeMillis() { return TimerToMicros(HighResTimer()) / 1000; }
{'content_hash': '17a3e7a2bda5f0c08756fc2030098233', 'timestamp': '', 'source': 'github', 'line_count': 97, 'max_line_length': 77, 'avg_line_length': 25.061855670103093, 'alnum_prop': 0.6417112299465241, 'repo_name': 'lizh06/ninja', 'id': 'a7d3c7ad5b95f0449a0887148fe4af5aa441a209', 'size': '3235', 'binary': False, 'copies': '59', 'ref': 'refs/heads/master', 'path': 'src/metrics.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '20345'}, {'name': 'C++', 'bytes': '566171'}, {'name': 'Emacs Lisp', 'bytes': '3333'}, {'name': 'Python', 'bytes': '54913'}, {'name': 'Shell', 'bytes': '3455'}, {'name': 'Vim script', 'bytes': '2623'}]}
package org.apache.sling.launchpad.webapp.integrationtest.issues; import java.util.HashMap; import java.util.Map; import org.apache.sling.launchpad.webapp.integrationtest.RenderingTestBase; /** Test the SLING-2094 JSP errorpage statement */ public class SLING2094Test extends RenderingTestBase { public final static String TEST_ROOT = "/apps/sling2094"; private String testNodePath; @Override protected void setUp() throws Exception { super.setUp(); scriptPath = TEST_ROOT; testClient.mkdirs(HTTP_BASE_URL, TEST_ROOT); for(String file : new String[] { "custom-error-page.jsp", "sling2094.jsp" }) { uploadTestScript("issues/sling2094/" + file, file); } final Map<String, String> props = new HashMap<String, String>(); props.put(SLING_RESOURCE_TYPE, TEST_ROOT); testNodePath = testClient.createNode(HTTP_BASE_URL + TEST_ROOT, props); } @Override protected void tearDown() throws Exception { super.tearDown(); testClient.delete(HTTP_BASE_URL + TEST_ROOT); } public void testWithoutError() throws Exception { final String expected = "All good, no exception"; final String url = testNodePath + ".html"; assertContains(getContent(url, CONTENT_TYPE_HTML), expected); } public void testWithError() throws Exception { final String expected = "witherror selector was specified"; final String url = testNodePath + ".witherror.html"; assertContains(getContent(url, CONTENT_TYPE_HTML), expected); } }
{'content_hash': '282b7bb7054ad71e1c599c6066b97af8', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 86, 'avg_line_length': 35.26086956521739, 'alnum_prop': 0.6609124537607891, 'repo_name': 'mikibrv/sling', 'id': '13a8097a764d30e7d1f0033a94bfad1e2573a508', 'size': '2429', 'binary': False, 'copies': '35', 'ref': 'refs/heads/trunk', 'path': 'launchpad/integration-tests/src/main/java/org/apache/sling/launchpad/webapp/integrationtest/issues/SLING2094Test.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '7690'}, {'name': 'Batchfile', 'bytes': '194'}, {'name': 'CSS', 'bytes': '80802'}, {'name': 'Groovy', 'bytes': '7745'}, {'name': 'HTML', 'bytes': '106621'}, {'name': 'Java', 'bytes': '21694104'}, {'name': 'JavaScript', 'bytes': '332686'}, {'name': 'Makefile', 'bytes': '1519'}, {'name': 'Python', 'bytes': '2586'}, {'name': 'Ruby', 'bytes': '4896'}, {'name': 'Scala', 'bytes': '127988'}, {'name': 'Shell', 'bytes': '24834'}, {'name': 'XProc', 'bytes': '2290'}, {'name': 'XSLT', 'bytes': '8575'}]}
package com.jtanks.view.arena; import java.awt.Color; import org.jmock.Expectations; import org.jmock.Mockery; import org.junit.Before; import org.junit.Test; import com.jtanks.config.GameConfiguration; import com.jtanks.view.gui.GUIStyle; import com.jtanks.view.gui.JTCanvas; import com.jtanks.view.gui.JTFrame; import com.jtanks.view.gui.JTGraphics; public class ArenaDisplayTest { private static final int ARENA_SIZE = 600; private static final String TITLE = "arena title"; private static final int ARENA_X = 0; private static final int ARENA_Y = 0; private Mockery context = new Mockery(); private GUIStyle guiStyle = context.mock(GUIStyle.class); // Policy private JTCanvas canvas = context.mock(JTCanvas.class); // Part private EntityStyle entityStyle = context.mock(EntityStyle.class); // Policy private EntityPainter entityPainter = context.mock(EntityPainter.class); // Part (local to each Painter) private RenderingStrategy renderingStrategy = context.mock(RenderingStrategy.class); // Policy private Renderer renderer = context.mock(Renderer.class); // Part (local to update()) private Drawable drawable = context.mock(Drawable.class); // Part (local to update()) private GameConfiguration config = new GameConfiguration(); // Non-peers - used only in methods private JTFrame frame = context.mock(JTFrame.class); private Painter painter1 = context.mock(Painter.class, "painter1"); private Painter painter2 = context.mock(Painter.class, "painter2"); private JTGraphics graphics = context.mock(JTGraphics.class); @Before public void setUp() { context.checking(new Expectations() {{ allowing (guiStyle).makeCanvas(); will(returnValue(canvas)); allowing (guiStyle).makeFrame(); will(returnValue(frame)); allowing (entityStyle).makeEntityPainter(); will(returnValue(entityPainter)); allowing (renderingStrategy).makeRenderer(canvas); will(returnValue(renderer)); allowing (renderingStrategy).makeScaledDrawable(renderer); will(returnValue(drawable)); }}); config.arenaXCoordinate = ARENA_X; config.arenaYCoordinate = ARENA_Y; config.arenaDimension = ARENA_SIZE; config.arenaTitle = TITLE; } @Test public void setsUpCanvas() { context.checking(new Expectations() {{ oneOf (canvas).setBackground(Color.BLACK); oneOf (canvas).setSize(ARENA_SIZE, ARENA_SIZE); }}); new ArenaDisplay(guiStyle, entityStyle, renderingStrategy, config); context.assertIsSatisfied(); } @Test public void passesRepaintToCanvas() { ArenaDisplay arenaDisplay = makeArenaDisplay(); context.checking(new Expectations() {{ oneOf (canvas).repaint(); }}); arenaDisplay.update(); context.assertIsSatisfied(); } @Test public void showAddsListenerAndMakesVisibleWithTitle() { final ArenaDisplay arenaDisplay = makeArenaDisplay(); context.checking(new Expectations() {{ oneOf (canvas).addListener(arenaDisplay); oneOf (canvas).addTo(frame); oneOf (frame).pack(); oneOf (frame).setLocation(ARENA_X, ARENA_Y); oneOf (frame).setVisible(true); oneOf (frame).setTitle(TITLE); }}); arenaDisplay.show(); context.assertIsSatisfied(); } @Test(expected = IllegalStateException.class) public void canOnlyDisplayOnce() { ArenaDisplay arenaDisplay = makeArenaDisplay(); context.checking(new Expectations() {{ ignoring (canvas); ignoring (frame); }}); arenaDisplay.show(); arenaDisplay.show(); } @Test public void updatePaintsEachPainterThenRenders() { ArenaDisplay arenaDisplay = makeArenaDisplay(painter1, painter2); context.checking(new Expectations() {{ ignoring (canvas); oneOf (painter1).paint(drawable); oneOf (painter2).paint(drawable); oneOf (renderer).renderIn(graphics); }}); arenaDisplay.update(graphics); context.assertIsSatisfied(); } private ArenaDisplay makeArenaDisplay(final Painter ...painters) { context.checking(new Expectations() {{ allowing (canvas).setBackground(with(any(Color.class))); allowing (canvas).setSize(with(any(Integer.class)), with(any(Integer.class))); for (Painter painter : painters) { oneOf (painter).paintWith(entityPainter); } }}); return new ArenaDisplay(guiStyle, entityStyle, renderingStrategy, config, painters); } }
{'content_hash': '92f7e40683ccccb65317242dee3c34ee', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 108, 'avg_line_length': 37.74803149606299, 'alnum_prop': 0.6545682102628285, 'repo_name': 'timfremote/jtanks', 'id': 'c25678eb9141ec0626a2d71461433badced78480', 'size': '4794', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/com/jtanks/view/arena/ArenaDisplayTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '247562'}, {'name': 'Shell', 'bytes': '31'}]}
require File.expand_path('../../../spec_helper', __FILE__) describe "Process.pid" do it "returns the process id of this process" do pid = Process.pid pid.should be_kind_of(Fixnum) Process.pid.should == pid end end
{'content_hash': '4acdbc5af8e8ce2f2a1db0a70528f29a', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 58, 'avg_line_length': 25.77777777777778, 'alnum_prop': 0.6551724137931034, 'repo_name': 'freerange/rubyspec', 'id': 'cdf2cc3700ae03864bf3d343a51f5159ef8a1de0', 'size': '232', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'core/process/pid_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '134543'}, {'name': 'Ruby', 'bytes': '4407478'}]}
using System; using System.Collections.Generic; using System.Threading.Tasks; using DotNet.Basics.Diagnostics; using DotNet.Basics.Diagnostics.Console; using DotNet.Basics.Sys; using Microsoft.Extensions.Configuration; namespace DotNet.Basics.Cli { public class CliHost<T> : CliHost { public CliHost(T args, ICliHost host) : base(host.CliArgs, host.Config, host.Log) { Args = args; } public T Args { get; } } public class CliHost : ICliHost { public CliHost(IReadOnlyList<string> cliArgs, IConfigurationRoot config, ILogger log) { CliArgs = cliArgs ?? throw new ArgumentNullException(nameof(cliArgs)); Config = config ?? throw new ArgumentNullException(nameof(config)); Log = log ?? Logger.NullLogger; } public string this[string key, int index] => this[key] ?? this[index]; public string this[string key] => Config[key]; public string this[int index] => index < CliArgs.Count ? CliArgs[index] : null; public IReadOnlyList<string> CliArgs { get; } public IConfigurationRoot Config { get; } public IReadOnlyCollection<string> Environments => Config.Environments(); public ILogger Log { get; } public bool IsSet(string key) => Config.IsSet(key) || CliArgs.IsSet(key); public bool HasValue(string key) => Config.HasValue(key); public virtual Task<int> RunAsync(string name, Func<ICliConfiguration, ILogger, Task<int>> asyncAction) { return RunAsync(name, asyncAction, 1.Minutes()); } public virtual async Task<int> RunAsync(string name, Func<ICliConfiguration, ILogger, Task<int>> asyncAction, TimeSpan longRunningOperationsPingInterval) { if (asyncAction == null) throw new ArgumentNullException(nameof(asyncAction)); try { LongRunningOperations.Init(Log, longRunningOperationsPingInterval); return await LongRunningOperations.StartAsync(name, async () => await asyncAction.Invoke(this, Log).ConfigureAwait(false)) .ConfigureAwait(false); } catch (CliException e) { Log.Error(e.Message.Highlight(), e.ConsoleLogOptions == ConsoleLogOptions.IncludeStackTrace ? e : null); return e.ExitCode; } catch (Exception e) { Log.Error(e.Message.Highlight(), e); return 500; } } } }
{'content_hash': '570843a2db3da8a2788acadb9bcb2cb5', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 161, 'avg_line_length': 37.59154929577465, 'alnum_prop': 0.5976020981641064, 'repo_name': 'rzmoz/DotNet.Basics', 'id': 'd6a2c15d14675b63e7d74c70560cea5f65ae1c5f', 'size': '2671', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'DotNet.Basics.Cli/CliHost.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '387029'}]}
namespace Microsoft.Azure.Management.CognitiveServices.Models { using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.Runtime; using System.Runtime.Serialization; /// <summary> /// Defines values for ResourceIdentityType. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum ResourceIdentityType { [EnumMember(Value = "None")] None, [EnumMember(Value = "SystemAssigned")] SystemAssigned, [EnumMember(Value = "UserAssigned")] UserAssigned, [EnumMember(Value = "SystemAssigned, UserAssigned")] SystemAssignedUserAssigned } internal static class ResourceIdentityTypeEnumExtension { internal static string ToSerializedValue(this ResourceIdentityType? value) { return value == null ? null : ((ResourceIdentityType)value).ToSerializedValue(); } internal static string ToSerializedValue(this ResourceIdentityType value) { switch( value ) { case ResourceIdentityType.None: return "None"; case ResourceIdentityType.SystemAssigned: return "SystemAssigned"; case ResourceIdentityType.UserAssigned: return "UserAssigned"; case ResourceIdentityType.SystemAssignedUserAssigned: return "SystemAssigned, UserAssigned"; } return null; } internal static ResourceIdentityType? ParseResourceIdentityType(this string value) { switch( value ) { case "None": return ResourceIdentityType.None; case "SystemAssigned": return ResourceIdentityType.SystemAssigned; case "UserAssigned": return ResourceIdentityType.UserAssigned; case "SystemAssigned, UserAssigned": return ResourceIdentityType.SystemAssignedUserAssigned; } return null; } } }
{'content_hash': 'ba99cdd5572e56b0c328d002d72b95df', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 92, 'avg_line_length': 34.516129032258064, 'alnum_prop': 0.5925233644859813, 'repo_name': 'AsrOneSdk/azure-sdk-for-net', 'id': 'ed475e41066d196914a97aac33320f84699e57b1', 'size': '2493', 'binary': False, 'copies': '2', 'ref': 'refs/heads/psSdkJson6Current', 'path': 'sdk/cognitiveservices/Microsoft.Azure.Management.CognitiveServices/src/Generated/Models/ResourceIdentityType.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '15473'}, {'name': 'Bicep', 'bytes': '13438'}, {'name': 'C#', 'bytes': '72203239'}, {'name': 'CSS', 'bytes': '6089'}, {'name': 'Dockerfile', 'bytes': '5652'}, {'name': 'HTML', 'bytes': '6169271'}, {'name': 'JavaScript', 'bytes': '16012'}, {'name': 'PowerShell', 'bytes': '649218'}, {'name': 'Shell', 'bytes': '31287'}, {'name': 'Smarty', 'bytes': '11135'}]}
from django.core.management.base import LabelCommand from django.template.loader import find_template from django.template import TemplateDoesNotExist import sys def get_template_path(path): try: template = find_template(path) return template[1].name except TemplateDoesNotExist: return None class Command(LabelCommand): help = "Finds the location of the given template by resolving its path" args = "[template_path]" label = 'template path' def handle_label(self, template_path, **options): path = get_template_path(template_path) if path is None: sys.stderr.write("No template found\n") sys.exit(1) else: print path
{'content_hash': 'f8454caa05d5b697b23126778366fdf4', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 75, 'avg_line_length': 28.115384615384617, 'alnum_prop': 0.6689466484268126, 'repo_name': 'mozilla/mozilla-ignite', 'id': 'e6f14dcb89b81ac35fa6aac8b9cd885a05ba0836', 'size': '731', 'binary': False, 'copies': '28', 'ref': 'refs/heads/master', 'path': 'vendor-local/lib/python/django_extensions/management/commands/find_template.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '230222'}, {'name': 'JavaScript', 'bytes': '457971'}, {'name': 'Puppet', 'bytes': '11448'}, {'name': 'Python', 'bytes': '4064774'}, {'name': 'SQL', 'bytes': '71'}, {'name': 'Shell', 'bytes': '1462'}, {'name': 'TeX', 'bytes': '19491'}]}
/* Commentary: * */ /* Change log: * */ #pragma once #include <dtkDistributedExport.h> #include <QtCore> class dtkDistributedCommunicator; class dtkDistributedPolicy; class dtkDistributedApplicationPrivate; class DTKDISTRIBUTED_EXPORT dtkDistributedApplication: public QCoreApplication { public: dtkDistributedApplication(int& argc, char **argv); virtual ~dtkDistributedApplication(void); public: virtual void initialize(void); virtual void exec(QRunnable *task); virtual void spawn(QMap<QString, QString> options = QMap<QString, QString>() ); virtual void unspawn(void); public: QCommandLineParser *parser(void); public: bool isMaster(void); virtual bool noGui(void); dtkDistributedCommunicator *communicator(void); dtkDistributedPolicy *policy(void); private: dtkDistributedApplicationPrivate *d; };
{'content_hash': 'd7cc9de5399020295745859fc628450b', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 83, 'avg_line_length': 18.51063829787234, 'alnum_prop': 0.7413793103448276, 'repo_name': 'd-tk/dtk', 'id': 'a849c14713c58f4dab2bcc5016424991c8172971', 'size': '1022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/dtkDistributed/dtkDistributedApplication.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '3061'}, {'name': 'C++', 'bytes': '4888561'}, {'name': 'CMake', 'bytes': '189979'}, {'name': 'HTML', 'bytes': '4722'}, {'name': 'JavaScript', 'bytes': '60221'}, {'name': 'Objective-C++', 'bytes': '4190'}, {'name': 'Python', 'bytes': '2637'}, {'name': 'QML', 'bytes': '25085'}, {'name': 'Shell', 'bytes': '1944'}]}
M101P-MongoDbForDevelopers ========================== Classwork associated with the M101P-MongoDbForDevelopers class. Please use this as a reference only (ie. don't use it to cheat). Thanks!
{'content_hash': 'dd807d745ae7211f176cbde57b484e0e', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 64, 'avg_line_length': 24.125, 'alnum_prop': 0.694300518134715, 'repo_name': 'ChrisEby/M101P-MongoDbForDevelopers', 'id': '21c223e3a22c0e684859099ef8cae852849566fd', 'size': '193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '20670'}, {'name': 'Python', 'bytes': '186472'}, {'name': 'Shell', 'bytes': '4216'}]}
/* * metismenu - v1.1.1 * Easy menu jQuery plugin for Twitter Bootstrap 3 * https://github.com/onokumus/metisMenu * * Made by Osman Nuri Okumus * Under MIT License */ ;(function($, window, document, undefined) { var pluginName = "metisMenu", defaults = { toggle: true, doubleTapToGo: false }; function Plugin(element, options) { this.element = $(element); this.settings = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function() { var $this = this.element, $toggle = this.settings.toggle, obj = this; if (this.isIE() <= 9) { $this.find("li.active").has("ul").children("ul").collapse("show"); $this.find("li").not(".active").has("ul").children("ul").collapse("hide"); } else { $this.find("li.active").has("ul").children("ul").addClass("collapse in"); $this.find("li").not(".active").has("ul").children("ul").addClass("collapse"); } //add the "doubleTapToGo" class to active items if needed if (obj.settings.doubleTapToGo) { $this.find("li.active").has("ul").children("a").addClass("doubleTapToGo"); } $this.find("li").has("ul").children("a").on("click" + "." + pluginName, function(e) { e.preventDefault(); //Do we need to enable the double tap if (obj.settings.doubleTapToGo) { //if we hit a second time on the link and the href is valid, navigate to that url if (obj.doubleTapToGo($(this)) && $(this).attr("href") !== "#" && $(this).attr("href") !== "") { e.stopPropagation(); document.location = $(this).attr("href"); return; } } $(this).parent("li").toggleClass("active").children("ul").collapse("toggle"); if ($toggle) { $(this).parent("li").siblings().removeClass("active").children("ul.in").collapse("hide"); } }); }, isIE: function() { //https://gist.github.com/padolsey/527683 var undef, v = 3, div = document.createElement("div"), all = div.getElementsByTagName("i"); while ( div.innerHTML = "<!--[if gt IE " + (++v) + "]><i></i><![endif]-->", all[0] ) { return v > 4 ? v : undef; } }, //Enable the link on the second click. doubleTapToGo: function(elem) { var $this = this.element; //if the class "doubleTapToGo" exists, remove it and return if (elem.hasClass("doubleTapToGo")) { elem.removeClass("doubleTapToGo"); return true; } //does not exists, add a new class and return false if (elem.parent().children("ul").length) { //first remove all other class $this.find(".doubleTapToGo").removeClass("doubleTapToGo"); //add the class on the current element elem.addClass("doubleTapToGo"); return false; } }, remove: function() { this.element.off("." + pluginName); this.element.removeData(pluginName); } }; $.fn[pluginName] = function(options) { this.each(function () { var el = $(this); if (el.data(pluginName)) { el.data(pluginName).remove(); } el.data(pluginName, new Plugin(this, options)); }); return this; }; })(jQuery, window, document);
{'content_hash': '9ebfa343ddb2afe87d70aa7662f51e94', 'timestamp': '', 'source': 'github', 'line_count': 120, 'max_line_length': 116, 'avg_line_length': 33.141666666666666, 'alnum_prop': 0.47824993713854663, 'repo_name': 'daijiale/DaiJiale-ProfessionalNotes', 'id': '6daf7d40049b34252b8bf4ebb7e04cef5dac561d', 'size': '3977', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'DaiJiale-Front-End/FE_Templates/三种组合式个人主页/js/metisMenu.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '26382'}, {'name': 'C', 'bytes': '1399048'}, {'name': 'C++', 'bytes': '115442'}, {'name': 'CSS', 'bytes': '6773433'}, {'name': 'CoffeeScript', 'bytes': '12044'}, {'name': 'HTML', 'bytes': '14216926'}, {'name': 'Java', 'bytes': '35097'}, {'name': 'JavaScript', 'bytes': '9616123'}, {'name': 'Makefile', 'bytes': '1041'}, {'name': 'PHP', 'bytes': '2792948'}, {'name': 'Python', 'bytes': '17429'}, {'name': 'Ruby', 'bytes': '6694'}, {'name': 'Shell', 'bytes': '32467'}, {'name': 'Smarty', 'bytes': '1249389'}, {'name': 'TypeScript', 'bytes': '15724'}]}
ManageIQ::Application.routes.draw do VERSION_PATTERN = /master|latest|v?([0-9_\-\.]+)/ unless defined?(VERSION_PATTERN) if Rails.env.development? mount MailPreview => 'mail_view' end namespace :api, defaults: { format: :json } do namespace :v1 do get 'metrics' => 'metrics#show' get 'health' => 'health#show' get 'extensions' => 'extensions#index' get 'search' => 'extensions#search' get 'extensions/:username/:extension' => 'extensions#show', as: :extension get 'extensions/:username/:extension/versions/:version' => 'extension_versions#show', as: :extension_version, constraints: { version: VERSION_PATTERN } get 'extensions/:username/:extension/versions/:version/download' => 'extension_versions#download', as: :extension_version_download, constraints: { version: VERSION_PATTERN } delete 'extensions/:username/:extension/versions/:version' => 'extension_uploads#destroy_version', constraints: { version: VERSION_PATTERN } get 'users/:user' => 'users#show', as: :user resources :tags, only: [:index] end end get 'extensions-directory' => 'extensions#directory' get 'universe' => 'api/v1/universe#index', defaults: { format: :json } get 'status' => 'api/v1/health#show', defaults: { format: :json } get 'unsubscribe/:token' => 'email_preferences#unsubscribe', as: :unsubscribe put 'extensions/:username/:id/transfer_ownership' => 'transfer_ownership#transfer', as: :transfer_ownership get 'ownership_transfer/:token/accept' => 'transfer_ownership#accept', as: :accept_transfer get 'ownership_transfer/:token/decline' => 'transfer_ownership#decline', as: :decline_transfer resources :extensions, only: [:index] resources :extensions, path: "", only: [:new] do scope "/extensions/:username" do member do get :show patch :update get :download put :follow delete :unfollow put :deprecate delete :deprecate, action: 'undeprecate' put :toggle_featured get :deprecate_search post :webhook put :disable put :enable put :report end end scope "/extensions" do collection do post :create end end member do post :adoption end end get '/extensions/:username/:extension_id/versions/:version/download' => 'extension_versions#download', as: :extension_version_download, constraints: { version: VERSION_PATTERN } get '/extensions/:username/:extension_id/versions/:version' => 'extension_versions#show', as: :extension_version, constraints: { version: VERSION_PATTERN } put "/extensions/:username/:extension_id/versions/:version/update_platforms" => "extension_versions#update_platforms", as: :extension_update_platforms, constraints: { version: VERSION_PATTERN } resources :collaborators, only: [:index, :new, :create, :destroy] do member do put :transfer end end resources :users, only: [:show] do member do put :make_admin put :disable put :enable delete :revoke_admin get :followed_extension_activity, format: :atom end collection do get :accessible_repos end resources :accounts, only: [:destroy] end resource :profile, controller: 'profile', only: [:update, :edit] do post :update_install_preference, format: :json collection do patch :change_password get :link_github, path: 'link-github' end end resources :invitations, constraints: proc { ROLLOUT.active?(:cla) && ROLLOUT.active?(:github) }, only: [:show] do member do get :accept get :decline end end resources :organizations, constraints: proc { ROLLOUT.active?(:cla) && ROLLOUT.active?(:github) }, only: [:show, :destroy] do member do put :combine get :requests_to_join, constraints: proc { ROLLOUT.active?(:join_ccla) && ROLLOUT.active?(:github) } end resources :contributors, only: [:update, :destroy], controller: :contributors, constraints: proc { ROLLOUT.active?(:cla) && ROLLOUT.active?(:github) } resources :invitations, only: [:index, :create, :update], constraints: proc { ROLLOUT.active?(:cla) && ROLLOUT.active?(:github) }, controller: :organization_invitations do member do patch :resend delete :revoke end end end get 'become-a-contributor' => 'contributors#become_a_contributor', constraints: proc { ROLLOUT.active?(:cla) && ROLLOUT.active?(:github) } get 'contributors' => 'contributors#index' get 'chat' => 'irc_logs#index' get 'chat/:channel' => 'irc_logs#show' get 'chat/:channel/:date' => 'irc_logs#show' # when signing in or up with chef account # match 'auth/chef_oauth2/callback' => 'sessions#create', as: :auth_session_callback, via: [:get, :post] match 'auth/github/callback' => 'sessions#create', as: :auth_session_callback, via: [:get, :post] get 'auth/failure' => 'sessions#failure', as: :auth_failure get 'login' => redirect('/sign-in'), as: nil get 'signin' => redirect('/sign-in'), as: nil get 'sign-in' => 'sessions#new', as: :sign_in get 'sign-up' => 'sessions#new', as: :sign_up delete 'logout' => redirect('/sign-out'), as: nil delete 'signout' => redirect('/sign-out'), as: nil delete 'sign-out' => 'sessions#destroy', as: :sign_out # when linking an oauth account match 'auth/:provider/callback' => 'accounts#create', as: :auth_callback, via: [:get, :post] # this is what a logged in user sees after login get 'dashboard' => 'pages#dashboard' get 'robots.:format' => 'pages#robots' root 'extensions#directory' require "sidekiq/web" mount Sidekiq::Web => "/sidekiq" end
{'content_hash': '91bbcf7af5b804c6b97af344711b9176', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 195, 'avg_line_length': 36.50955414012739, 'alnum_prop': 0.65648988136776, 'repo_name': 'ManageIQ/depot.manageiq.org', 'id': '544ad8db4e772ab5adf480accabfae4ca7e8bb8a', 'size': '5732', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/routes.rb', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '60508'}, {'name': 'HTML', 'bytes': '102007'}, {'name': 'JavaScript', 'bytes': '14542'}, {'name': 'Ruby', 'bytes': '553086'}, {'name': 'Shell', 'bytes': '12379'}]}
class DeployKeysController < ServerBaseController def index @server = Server.find(params[:server_id]) @deploy_keys = @server.deploy_keys @deploy_key = DeployKey.new end def create @server = Server.find(params[:server_id]) @deploy_key = @server.deploy_keys.new(deploy_key_params) if @deploy_key.save CreateDeployKeyJob.perform_later(@server, @deploy_key) flash[:success] = "Deploy key has been added" else flash[:error] = "Not all fields are filled in." end redirect_to server_deploy_keys_path(@server) end def destroy @server = Server.find(params[:server_id]) deploy_key = @server.deploy_keys.find(params[:id]) DeleteDeployKeyJob.perform_later(@server, deploy_key.name) deploy_key.destroy redirect_to server_deploy_keys_path(@server) end private def deploy_key_params params.require(:deploy_key).permit(:name, :key) end end
{'content_hash': 'b9c21087027f57c51146226353d69676', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 62, 'avg_line_length': 28.0, 'alnum_prop': 0.6861471861471862, 'repo_name': 'jvanbaarsen/intercity-next', 'id': '9dba8f2e8f22743aa051bcdeb6a98a515280773a', 'size': '924', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/controllers/deploy_keys_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12461'}, {'name': 'CoffeeScript', 'bytes': '2587'}, {'name': 'HTML', 'bytes': '49967'}, {'name': 'JavaScript', 'bytes': '519'}, {'name': 'Ruby', 'bytes': '144961'}, {'name': 'Shell', 'bytes': '681'}]}
import config, time, langid from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream from tweepy import API from tweepy.models import Status from tweepy.utils import import_simplejson json = import_simplejson() class StreamDownloader(StreamListener): """ A downloader which saves tweets received from the stream to a sample.json file. > Duration in minutes > Language in ISO 639-1 code """ def __init__(self, duration, lang, lang_threshold): self.api = API() self.lang = lang self.lang_threshold = lang_threshold self.counter = {lang + '-above':0, lang + '-below':0, 'excluded':0} self.started = time.time() self.duration = 10 self.first_tweet_id = '' self.last_tweet_id = '' self.above_output = open('{0}-sample-above-{1}.json'.format(int(self.started), self.lang), 'w+') self.below_output = open('{0}-sample-below-{1}.json'.format(int(self.started), self.lang), 'w+') self.excl_output = open('{0}-sample-excluded.json'.format(int(self.started)), 'w+') def on_data(self, data): if time.time() >= self.started + self.duration: stats = open('{0}-sample.stats'.format(int(self.started)), 'w+') stats.write("================= STATISTICS =================" + "\n") stats.write("Start time: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.started)) + "\n") stats.write("End time: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "\n") stats.write("First Tweet ID: " + self.first_tweet_id + "\n") stats.write("Last Tweet ID: " + self.last_tweet_id + "\n") stats.write("Language: " + self.lang + "\n") stats.write("Language classification threshold: " + str(self.lang_threshold) + "\n") stats.write("Above threshold: " + str(self.counter[self.lang + '-above']) + "\n") stats.write("Below threshold: " + str(self.counter[self.lang + '-below']) + "\n") stats.write("Exluded: " + str(self.counter['excluded']) + "\n") return False elif 'in_reply_to_status_id' in data: status = Status.parse(self.api, json.loads(data)) langclass = langid.classify(status.text) if (self.counter == {self.lang + '-above':0, self.lang + '-below':0, 'excluded':0}): self.first_tweet_id = str(status.id) self.last_tweet_id = str(status.id) if (langclass[0] == self.lang): if langclass[1] >= self.lang_threshold: self.above_output.write(data) self.counter[self.lang + '-above'] += 1 else: self.below_output.write(data) self.counter[self.lang + '-below'] += 1 else: self.excl_output.write(data) self.counter['excluded'] += 1 return True if __name__ == '__main__': downloader = StreamDownloader(duration = 10, lang = 'en', lang_threshold = 0.9) auth = OAuthHandler(config.twitter_consumer_key, config.twitter_consumer_secret) auth.set_access_token(config.twitter_access_token, config.twitter_access_token_secret) stream = Stream(auth, downloader) stream.sample()
{'content_hash': 'ce23af7f4cefda871d4992f9679b50f1', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 113, 'avg_line_length': 46.586666666666666, 'alnum_prop': 0.5543789353176874, 'repo_name': 'royyeah/wse', 'id': '9b2c1bdf569c7f4551988d6f5c0cdefdad819265', 'size': '3554', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'twitter_weka_assignment/SampleDownloader.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '30066'}]}
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sdm.core.response.model; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * * @author Htoonlin */ @JsonPropertyOrder({"count", "data"}) public class ListModel<T extends Serializable> implements Serializable { /** * */ private static final long serialVersionUID = 522782444980983172L; public ListModel() { } public ListModel(List<T> data) { this.data = data; } public int getCount() { return this.data.size(); } private List<T> data; public void addData(T entity) { if (this.data == null) { this.data = new ArrayList<>(); } this.data.add(entity); } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ListModel other = (ListModel) obj; if (data == null) { if (other.data != null) { return false; } } else if (!data.equals(other.data)) { return false; } return true; } }
{'content_hash': 'cd58ab138deb6553afb3b323ee769f48', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 79, 'avg_line_length': 22.85542168674699, 'alnum_prop': 0.5276752767527675, 'repo_name': 'Htoonlin/MasterAPI', 'id': '40d47ceb9cefefc9e275732d60ac727a6f7d5121', 'size': '1897', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/sdm/core/response/model/ListModel.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '361538'}]}
layout: post title: "Acronyms @ Mozilla" permalink: 2020-mozilla-acronyms layout: post tags: [mozilla, 2020, acronyms, jargon, nicknames] categories: mozilla --- Acronyms, Nicknames, and specific definitions @ Mozilla --- A confusing part of being a software engineer at Mozilla is all of the acronyms at play. Given the open source nature of Mozilla, I have created a listing of those that I encounter often and am sharing those here along with links that point to those resources. There are certainly tons more but these have been beneficial to me as I ramp up. Acronyms: * AMO -> addons.mozilla.org * BMO -> Bugzilla * FxA -> Firefox Accounts * IC -> Individual Contributor * MAU -> Monthly Average User * MDN -> Mozilla Developer Network * MoCo -> Mozilla Corporation * MoFo -> Mozilla Foundation * ML -> Machine Learning * SUMO -> support.mozilla.org Nicknames: * Fenix -> Firefox Android Browser * Mana -> Confluence Jargon: * Chemspill -> an urgent problem in a product that requires immediate effort in response. * Face mute -> When you are on a video call and turn your camera off. Example: "I am going face mute while I fetch a cup of coffee." Random Learning of the Day: The word Hydra has many meanings: * [Hydra of Mythology](https://en.wikipedia.org/wiki/Lernaean_Hydra) * [Hydra of comics](https://en.wikipedia.org/wiki/Hydra_(comics)) I only knew of the first and apparently am not well versed in comics.
{'content_hash': '753aa058af404b5044b4705f7edb4a00', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 182, 'avg_line_length': 26.410714285714285, 'alnum_prop': 0.7268424611223799, 'repo_name': 'bowlofstew/bowlofstew.github.io', 'id': '96e5bf0547b274d913bc0bbdd2ffd3da3253e68c', 'size': '1483', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/mozilla/2020-04-09-mozilla-acronyms.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '17054'}, {'name': 'HTML', 'bytes': '19259'}, {'name': 'JavaScript', 'bytes': '4758'}, {'name': 'Ruby', 'bytes': '2053'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>equations: 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.11.2 / equations - 1.2~beta+8.9</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> equations <small> 1.2~beta+8.9 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-11 16:27:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-11 16:27:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; authors: [ &quot;Matthieu Sozeau &lt;[email protected]&gt;&quot; &quot;Cyprien Mangin &lt;[email protected]&gt;&quot; ] dev-repo: &quot;git+https://github.com/mattam82/Coq-Equations.git&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://mattam82.github.io/Coq-Equations&quot; bug-reports: &quot;https://github.com/mattam82/Coq-Equations/issues&quot; license: &quot;LGPL 2.1&quot; build: [ [&quot;coq_makefile&quot; &quot;-f&quot; &quot;_CoqProject&quot; &quot;-o&quot; &quot;Makefile&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Equations&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10&quot;} ] synopsis: &quot;A function definition package for Coq&quot; description: &quot;&quot;&quot; Equations is a function definition plugin for Coq, that allows the definition of functions by dependent pattern-matching and well-founded, mutual or nested structural recursion and compiles them into core terms. It automatically derives the clauses equations, the graph of the function and its associated elimination principle.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/mattam82/Coq-Equations/archive/v1.2-beta-8.9.tar.gz&quot; checksum: &quot;md5=6ad92e28066f1c50bc15efc1a79ef896&quot; } </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-equations.1.2~beta+8.9 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-equations -&gt; coq &lt; 8.10 -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints 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-equations.1.2~beta+8.9</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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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': '7699e04b3cee28f4143dfca11fcbaec5', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 157, 'avg_line_length': 41.660919540229884, 'alnum_prop': 0.5529038488067319, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'f64ce0b1a1fc2492d2828333ecdc83e68b015c43', 'size': '7251', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.05.0-2.0.6/released/8.11.2/equations/1.2~beta+8.9.html', 'mode': '33188', 'license': 'mit', 'language': []}
<?php namespace RocketTheme\Toolbox\File; /** * Implements Universal File Reader. * * @package RocketTheme\Toolbox\File * @author RocketTheme * @license MIT */ class File implements FileInterface { /** * @var string */ protected $filename; /** * @var resource */ protected $handle; /** * @var bool|null */ protected $locked; /** * @var string */ protected $extension; /** * @var string Raw file contents. */ protected $raw; /** * @var array Parsed file contents. */ protected $content; /** * @var array */ protected $settings = []; /** * @var array|File[] */ static protected $instances = []; /** * Get file instance. * * @param string $filename * @return static */ public static function instance($filename) { if (!is_string($filename) && $filename) { throw new \InvalidArgumentException('Filename should be non-empty string'); } if (!isset(static::$instances[$filename])) { static::$instances[$filename] = new static; static::$instances[$filename]->init($filename); } return static::$instances[$filename]; } /** * Set/get settings. * * @param array $settings * @return array */ public function settings(array $settings = null) { if ($settings !== null) { $this->settings = $settings; } return $this->settings; } /** * Get setting. * * @param string $setting * @param mixed $default * @return mixed */ public function setting($setting, $default = null) { return isset($this->settings[$setting]) ? $this->settings[$setting] : $default; } /** * Prevent constructor from being used. */ protected function __construct() { } /** * Prevent cloning. */ protected function __clone() { //Me not like clones! Me smash clones! } /** * Set filename. * * @param $filename */ protected function init($filename) { $this->filename = $filename; } /** * Free the file instance. */ public function free() { if ($this->locked) { $this->unlock(); } $this->content = null; $this->raw = null; unset(static::$instances[$this->filename]); } /** * Get/set the file location. * * @param string $var * @return string */ public function filename($var = null) { if ($var !== null) { $this->filename = $var; } return $this->filename; } /** * Return basename of the file. * * @return string */ public function basename() { return basename($this->filename, $this->extension); } /** * Check if file exits. * * @return bool */ public function exists() { return is_file($this->filename); } /** * Return file modification time. * * @return int|bool Timestamp or false if file doesn't exist. */ public function modified() { return is_file($this->filename) ? filemtime($this->filename) : false; } /** * Lock file for writing. You need to manually unlock(). * * @param bool $block For non-blocking lock, set the parameter to false. * @return bool * @throws \RuntimeException */ public function lock($block = true) { if (!$this->handle) { if (!$this->mkdir(dirname($this->filename))) { throw new \RuntimeException('Creating directory failed for ' . $this->filename); } $this->handle = @fopen($this->filename, 'cb+'); if (!$this->handle) { $error = error_get_last(); throw new \RuntimeException("Opening file for writing failed on error {$error['message']}"); } } $lock = $block ? LOCK_EX : LOCK_EX | LOCK_NB; return $this->locked = $this->handle ? flock($this->handle, $lock) : false; } /** * Returns true if file has been locked for writing. * * @return bool|null True = locked, false = failed, null = not locked. */ public function locked() { return $this->locked; } /** * Unlock file. * * @return bool */ public function unlock() { if (!$this->handle) { return false; } if ($this->locked) { flock($this->handle, LOCK_UN); $this->locked = null; } fclose($this->handle); $this->handle = null; return true; } /** * Check if file can be written. * * @return bool */ public function writable() { return is_writable($this->filename) || $this->writableDir(dirname($this->filename)); } /** * (Re)Load a file and return RAW file contents. * * @return string */ public function load() { $this->raw = $this->exists() ? (string) file_get_contents($this->filename) : ''; $this->content = null; return $this->raw; } /** * Get/set raw file contents. * * @param string $var * @return string */ public function raw($var = null) { if ($var !== null) { $this->raw = (string) $var; $this->content = null; } if (!is_string($this->raw)) { $this->raw = $this->load(); } return $this->raw; } /** * Get/set parsed file contents. * * @param mixed $var * @return string|array * @throws \RuntimeException */ public function content($var = null) { if ($var !== null) { $this->content = $this->check($var); // Update RAW, too. $this->raw = $this->encode($this->content); } elseif ($this->content === null) { // Decode RAW file. try { $this->content = $this->decode($this->raw()); } catch (\Exception $e) { throw new \RuntimeException(sprintf('Failed to read %s: %s', $this->filename, $e->getMessage()), 500, $e); } } return $this->content; } /** * Save file. * * @param mixed $data Optional data to be saved, usually array. * @throws \RuntimeException */ public function save($data = null) { if ($data !== null) { $this->content($data); } if (!$this->locked) { // Obtain blocking lock or fail. if (!$this->lock()) { throw new \RuntimeException('Obtaining write lock failed on file: ' . $this->filename); } $lock = true; } // As we are using non-truncating locking, make sure that the file is empty before writing. if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $this->raw()) === false) { $this->unlock(); throw new \RuntimeException('Saving file failed: ' . $this->filename); } if (isset($lock)) { $this->unlock(); } // Touch the directory as well, thus marking it modified. @touch(dirname($this->filename)); } /** * Rename file in the filesystem if it exists. * * @param $filename * @return bool */ public function rename($filename) { if ($this->exists() && !@rename($this->filename, $filename)) { return false; } unset(static::$instances[$this->filename]); static::$instances[$filename] = $this; $this->filename = $filename; return true; } /** * Delete file from filesystem. * * @return bool */ public function delete() { return unlink($this->filename); } /** * Check contents and make sure it is in correct format. * * Override in derived class. * * @param string $var * @return string */ protected function check($var) { return (string) $var; } /** * Encode contents into RAW string. * * Override in derived class. * * @param string $var * @return string */ protected function encode($var) { return (string) $var; } /** * Decode RAW string into contents. * * Override in derived class. * * @param string $var * @return string mixed */ protected function decode($var) { return (string) $var; } /** * @param string $dir * @return bool * @throws \RuntimeException * @internal */ protected function mkdir($dir) { // Silence error for open_basedir; should fail in mkdir instead. if (!@is_dir($dir)) { $success = @mkdir($dir, 0777, true); if (!$success) { $error = error_get_last(); throw new \RuntimeException("Creating directory '{$dir}' failed on error {$error['message']}"); } } return true; } /** * @param string $dir * @return bool * @internal */ protected function writableDir($dir) { if ($dir && !file_exists($dir)) { return $this->writableDir(dirname($dir)); } return $dir && is_dir($dir) && is_writable($dir); } }
{'content_hash': 'ae40be68586d9768d0b2871743f57b6f', 'timestamp': '', 'source': 'github', 'line_count': 443, 'max_line_length': 122, 'avg_line_length': 21.857787810383748, 'alnum_prop': 0.4974697924197046, 'repo_name': 'gregorykelleher/gregorykelleher_website_2016', 'id': 'e2dcef77fa71c1cbb528a03217a014eaf7d55a2f', 'size': '9683', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'vendor/rockettheme/toolbox/File/src/File.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3414'}, {'name': 'CSS', 'bytes': '278131'}, {'name': 'HTML', 'bytes': '46019'}, {'name': 'JavaScript', 'bytes': '281561'}, {'name': 'Nginx', 'bytes': '1491'}, {'name': 'PHP', 'bytes': '758979'}, {'name': 'Shell', 'bytes': '311'}]}
<?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>com.facebook.presto</groupId> <artifactId>presto-root</artifactId> <version>0.113-SNAPSHOT</version> </parent> <artifactId>presto-raptor</artifactId> <description>Presto - Raptor Connector</description> <packaging>presto-plugin</packaging> <properties> <air.main.basedir>${project.parent.basedir}</air.main.basedir> </properties> <dependencies> <dependency> <groupId>io.airlift</groupId> <artifactId>concurrent</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>json</artifactId> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-orc</artifactId> </dependency> <dependency> <groupId>com.facebook.presto.hive</groupId> <artifactId>hive-apache</artifactId> </dependency> <dependency> <groupId>com.facebook.presto.hadoop</groupId> <artifactId>hadoop-apache2</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>bootstrap</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>configuration</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>dbpool</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>log</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>units</artifactId> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>stats</artifactId> </dependency> <dependency> <groupId>org.weakref</groupId> <artifactId>jmxutils</artifactId> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> </dependency> <dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> <dependency> <groupId>com.google.code.findbugs</groupId> <artifactId>annotations</artifactId> </dependency> <dependency> <groupId>org.jdbi</groupId> <artifactId>jdbi</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> <!-- Presto SPI --> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-spi</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>slice</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <scope>provided</scope> </dependency> <!-- for testing --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.airlift</groupId> <artifactId>testing</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-client</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-main</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-main</artifactId> <type>test-jar</type> <scope>test</scope> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-tests</artifactId> <scope>test</scope> </dependency> <!-- for benchmark --> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-benchmark</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.facebook.presto</groupId> <artifactId>presto-tpch</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>io.airlift.tpch</groupId> <artifactId>tpch</artifactId> <scope>test</scope> </dependency> </dependencies> </project>
{'content_hash': '09a36b68cf90cfd18ca1032723105695', 'timestamp': '', 'source': 'github', 'line_count': 220, 'max_line_length': 204, 'avg_line_length': 29.004545454545454, 'alnum_prop': 0.5572794232878859, 'repo_name': 'saidalaoui/presto', 'id': 'd563ace3a4eb09721e14a77e316f8e38efed466a', 'size': '6381', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'presto-raptor/pom.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '17800'}, {'name': 'HTML', 'bytes': '44755'}, {'name': 'Java', 'bytes': '11939930'}, {'name': 'JavaScript', 'bytes': '1431'}, {'name': 'Makefile', 'bytes': '6819'}, {'name': 'PLSQL', 'bytes': '3849'}, {'name': 'Python', 'bytes': '4481'}, {'name': 'SQLPL', 'bytes': '6363'}, {'name': 'Shell', 'bytes': '2069'}]}
#ifndef _MSC_UNICODE_H_ #define _MSC_UNICODE_H_ typedef struct unicode_map unicode_map; #include <apr_file_io.h> #include "modsecurity.h" #include "apr_hash.h" struct unicode_map { apr_file_t *map; const char *mapfn; }; int DSOLOCAL unicode_map_init(directory_config *dcfg, const char *mapfn, char **error_msg); #endif
{'content_hash': 'cdf889f923a8496059d581069a713407', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 91, 'avg_line_length': 17.57894736842105, 'alnum_prop': 0.7005988023952096, 'repo_name': 'p0pr0ck5/ModSecurity', 'id': '1eaf3d6625d29ee5e061dfce2d03a2f365356f78', 'size': '858', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'apache2/msc_unicode.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '18307'}, {'name': 'C', 'bytes': '1834007'}, {'name': 'C++', 'bytes': '271029'}, {'name': 'HTML', 'bytes': '6'}, {'name': 'Lua', 'bytes': '1510'}, {'name': 'M4', 'bytes': '48149'}, {'name': 'Makefile', 'bytes': '15468'}, {'name': 'Perl', 'bytes': '928228'}, {'name': 'Perl 6', 'bytes': '709'}, {'name': 'Shell', 'bytes': '6343'}]}
module PropertyTestMacros def relax_requirements_for(obj) allow(obj).to receive(:ensure_required_attributes_set) allow(obj).to receive(:ensure_required_choices) end def xml(obj) relax_requirements_for(obj) doc = Nokogiri::XML::Builder.new do |xml| xml.root("xmlns:a" => "http://anamespace.org", "xmlns:r" => "http://rnamespace.org") { obj.to_xml(xml) } end.to_xml doc_pattern =~ doc ? $1 : "" end def doc_pattern /<\?xml\sversion="1.0"\?>\n<root xmlns:a="http:\/\/anamespace.org" xmlns:r="http:\/\/rnamespace.org">\n\s+([^\s].+)\n<\/root>/m end def self.included(base) attr_reader :instance, :value, :attribute base.extend ClassMethods end module ClassMethods def it_should_use(tag: nil, name: nil, namespace: :a, value: nil) context "always" do before(:each) do allow_any_instance_of(described_class).to receive(:build_required_properties) if value.nil? @instance = described_class.new else @instance = described_class.new(*value) end end it "should use the correct tag" do expect(instance.tag).to eq(tag) end it "should use the correct name" do expect(instance.name).to eq(name) end it "should use the correct namespace" do expect(instance.namespace).to eq(namespace) end end end def it_should_output(expected_xml, *values, assign: true) it "should output the correct XML" do allow_any_instance_of(described_class).to receive(:build_required_properties) @instance = described_class.new(*values) instance.send "#{attribute}=", value if assign expect(xml(instance)).to eq(expected_xml) end end def it_should_have_properties(*properties, value: nil) properties.each do |property| it "should have the property #{property}" do allow_any_instance_of(described_class).to receive(:build_required_properties) expect(described_class.new(value).respond_to?(property)).to be true end end end alias it_should_have_property it_should_have_properties def it_should_have_value_properties(*properties, value: nil) properties.each do |property| it "should have the value property #{property}" do allow_any_instance_of(described_class).to receive(:build_required_properties) @instance = described_class.new(value) expect(instance.respond_to?(property)).to be true expect(instance.respond_to?(:"#{property}=")).to be true end end end alias it_should_have_value_property it_should_have_value_properties def for_attribute(attribute, &block) attribute_context = context "for the #{attribute} attribute" do before(:each) do @attribute = attribute end end attribute_context.class_eval &block end def with_value(value, &block) value_context = context "with the value as #{value}" do before(:each) do @value = value end end value_context.class_eval &block end def it_should_assign_successfully(*values) it "should assign successfully" do expect do allow_any_instance_of(described_class).to receive(:build_required_properties) obj = described_class.new *values obj.send "#{attribute}=", value end.to_not raise_error end end def it_should_raise_an_exception it "should raise an exception" do expect do allow_any_instance_of(described_class).to receive(:build_required_properties) obj = described_class.new obj.send "#{attribute}=", value end.to raise_error(ArgumentError) end end def with_no_attributes_set(&block) attribute_context = context "with no attributes set" do before(:each) do allow_any_instance_of(described_class).to receive(:build_required_properties) @instance = described_class.new end end attribute_context.class_eval &block end def with_these_attributes_set(attributes, &block) attribute_context = context "with valid attributes set" do before(:each) do allow_any_instance_of(described_class).to receive(:build_required_properties) @instance = described_class.new attributes.each do |attr, val| instance.send "#{attr}=", val end end end attribute_context.class_eval &block end def it_should_output_expected_xml(*values, expected_xml: nil) it "should output the correct XML" do allow_any_instance_of(described_class).to receive(:build_required_properties) @instance = described_class.new *values instance.send "#{attribute}=", value property_name, property_namespace = instance.attributes[attribute] expected_xml ||= "<a:#{instance.tag} #{property_namespace}#{property_namespace.nil? ? "" : ":"}#{property_name}=\"#{value}\"/>" expect(xml(instance)).to eq(expected_xml) end end def it_should_assign_and_output_xml(values) values = [values] unless values.respond_to? :each values.each do |value| with_value(value) do it_should_assign_successfully it_should_output_expected_xml end end end def it_should_behave_like_a_boolean_attribute with_value(true) do it_should_assign_successfully it_should_output_expected_xml end with_value(false) do it_should_assign_successfully it_should_output_expected_xml end end def it_should_not_allow_invalid_value with_value(:invalid) do it_should_raise_an_exception end end def it_should_not_allow_integers with_value(1) do it_should_raise_an_exception end end def it_should_not_allow_floats with_value(12.1) do it_should_raise_an_exception end end def it_should_not_allow_negative_numbers with_value(-1) do it_should_raise_an_exception end end def it_should_not_allow_nil with_value(nil) do it_should_raise_an_exception end end end end
{'content_hash': 'fd057911ff284fe438a8b471c76ceef9', 'timestamp': '', 'source': 'github', 'line_count': 214, 'max_line_length': 135, 'avg_line_length': 29.733644859813083, 'alnum_prop': 0.6223479490806223, 'repo_name': 'openxml/openxml-drawingml', 'id': 'ceb65bb44f69359ff188e5177a3460c80eaf2d73', 'size': '6363', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/support/property_test_macros.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '311929'}, {'name': 'Shell', 'bytes': '131'}]}
<?php function smarty_compiler_html($arrParams, $smarty){ $strAttr = ''; foreach ($arrParams as $_key => $_value) { $strAttr .= ' ' . $_key . '="<?php echo ' . $_value . ';?>"'; } return "<!doctype html>\n<html{$strAttr}>"; } function smarty_compiler_htmlclose($arrParams, $smarty){ $strCode = '<?php '; $strCode .= '$_smarty_tpl->registerFilter(\'output\', array(\'FISResource\', \'renderResponse\'));'; $strCode .= '?>'; $strCode .= '</html>'; return $strCode; }
{'content_hash': 'b72ef25eb652f06b96ae0a05784972d3', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 104, 'avg_line_length': 30.11764705882353, 'alnum_prop': 0.548828125, 'repo_name': 'fex-team/fis-kernel', 'id': 'a609832eee68085625fd9f7e5b1e4d8cfaffd3b2', 'size': '512', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'test/ut/release/test2/plugin/compiler.html.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '3437'}, {'name': 'HTML', 'bytes': '58250'}, {'name': 'JavaScript', 'bytes': '248189'}, {'name': 'PHP', 'bytes': '80728'}, {'name': 'Smarty', 'bytes': '6811'}]}
<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="../node_modules/video.js/dist/video-js/video-js.css" /> <script src="../node_modules/video.js/dist/video-js/video.js"></script> <script src="../src/youtube.js"></script> </head> <body> <video id="vid1" src="" class="video-js vjs-default-skin" controls preload="auto" width="640" height="360"> </video> <script> videojs('vid1', { "techOrder": ["youtube"], "src": "http://www.youtube.com/watch?v=xjS6SftYQaQ" }).ready(function() { // Cue a video using ended event // Most video.js events are supported this.one('ended', function() { this.src('http://www.youtube.com/watch?v=jofNR_WkoCE'); this.play(); }); }); </script> </body> </html>
{'content_hash': '8c6ad19a2bd5216850f27f3a17834e23', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 119, 'avg_line_length': 32.608695652173914, 'alnum_prop': 0.6333333333333333, 'repo_name': 'reachwill/clipper-lite-mongodb1', 'id': '948867f9712d20163a16c0def0e941d0949676f5', 'size': '750', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'vendors/videojs-youtube-master/examples/javascript.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9190'}, {'name': 'HTML', 'bytes': '19019'}, {'name': 'JavaScript', 'bytes': '16691'}, {'name': 'TypeScript', 'bytes': '52045'}]}
<!DOCTYPE html> <!--html5--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <!-- Mirrored from www.arduino.cc/en/Reference/YunServerWrite by HTTrack Website Copier/3.x [XR&CO'2010], Mon, 26 Oct 2015 14:08:13 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack --> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8" /> <title>Arduino - YunServerWrite </title> <link rel="shortcut icon" type="image/x-icon" href="../favicon.png" /> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <link rel="stylesheet" href="../../fonts/fonts.css" type="text/css" /> <link rel="stylesheet" href="../../css/arduino-icons.css"> <link rel="stylesheet" href="../../css/animation.css"><!--[if IE 7]> <link rel="stylesheet" href="//arduino.cc/css/arduino-icons-ie7.css"><![endif]--> <!--[if gte IE 9]><!--> <link rel='stylesheet' href='../../css/foundation2.css' type='text/css' /> <!--<![endif]--> <!--[if IE 8]> <link rel='stylesheet' href='//arduino.cc/css/foundation_ie8.css' type='text/css' /> <![endif]--> <link rel='stylesheet' href='../../css/arduino_code_highlight.css' type='text/css' /> <link rel="stylesheet" type="text/css" media="screen" href="../../css/typeplate.css"> <link rel='stylesheet' href='../pub/skins/arduinoWide_SSO/css/arduinoWide_SSO.css' type='text/css' /> <link rel='stylesheet' href='../../css/common.css' type='text/css' /> <link rel="stylesheet" href="../../css/download_page.css" /> <link href="https://plus.google.com/114839908922424087554" rel="publisher" /> <!-- embedded JS and CSS from PmWiki plugins --> <!--HeaderText--><style type='text/css'><!-- ul, ol, pre, dl, p { margin-top:0px; margin-bottom:0px; } code { white-space: nowrap; } .vspace { margin-top:1.33em; } .indent { margin-left:40px; } .outdent { margin-left:40px; text-indent:-40px; } a.createlinktext { text-decoration:none; border-bottom:1px dotted gray; } a.createlink { text-decoration:none; position:relative; top:-0.5em; font-weight:bold; font-size:smaller; border-bottom:none; } img { border:0px; } span.anchor { float: left; font-size: 10px; margin-left: -10px; width: 10px; position:relative; top:-0.1em; text-align: center; } span.anchor a { text-decoration: none; } span.anchor a:hover { text-decoration: underline; } ol.toc { text-indent:-20px; list-style: none; } ol.toc ol.toc { text-indent:-40px; } div.tocfloat { font-size: smaller; margin-bottom: 10px; border-top: 1px dotted #555555; border-bottom: 1px dotted #555555; padding-top: 5px; padding-bottom: 5px; width: 38%; float: right; margin-left: 10px; clear: right; margin-right:-13px; padding-right: 13px; padding-left: 13px; background-color: #eeeeee; } div.toc { font-size: smaller; padding: 5px; border: 1px dotted #cccccc; background: #f7f7f7; margin-bottom: 10px; } div.toc p { background-color: #f9f6d6; margin-top:-5px; padding-top: 5px; margin-left:-5px; padding-left: 5px; margin-right:-5px; padding-right: 5px; padding-bottom: 3px; border-bottom: 1px dotted #cccccc; }.editconflict { color:green; font-style:italic; margin-top:1.33em; margin-bottom:1.33em; } table.markup { border: 2px dotted #ccf; width:90%; } td.markup1, td.markup2 { padding-left:10px; padding-right:10px; } td.markup1 { border-bottom: 1px solid #ccf; } div.faq { margin-left:2em; } div.faq p.question { margin: 1em 0 0.75em -2em; font-weight:bold; } div.faq hr { margin-left: -2em; } .frame { border:1px solid #cccccc; padding:4px; background-color:#f9f9f9; } .lfloat { float:left; margin-right:0.5em; } .rfloat { float:right; margin-left:0.5em; } a.varlink { text-decoration:none; } --></style><script type="text/javascript"> function toggle(obj) { var elstyle = document.getElementById(obj).style; var text = document.getElementById(obj + "tog"); if (elstyle.display == 'none') { elstyle.display = 'block'; text.innerHTML = "hide"; } else { elstyle.display = 'none'; text.innerHTML = "show"; } } </script><script src="http://www.arduino.cc/en/pub/galleria/galleria-1.2.6.min.js"></script><script type="text/javascript">Galleria.loadTheme("http://www.arduino.cc/en/pub/galleria/themes/classic/galleria.classic.min.js");</script> <meta name='robots' content='index,follow' /> <script src="http://arduino.cc/js/vendor/custom.modernizr.js"></script> <!-- do not remove none of those lines, comments embedding in pages will break! --> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js" type="text/javascript"></script> <script src="http://arduino.cc/en/pub/js/newsletter_subscribe_popup.js" type="text/javascript"></script> <script src="https://checkout.stripe.com/checkout.js" type="text/javascript"></script> <script src="https://www.arduino.cc/en/pub/js/software_download.js" type="text/javascript"></script><!-- keep https! --> <link rel='stylesheet' href='../../../code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.min.css' type='text/css' /> </head> <body> <div id="menuWings" class="fixed"></div> <div id="page"> <script> var userAgent = (navigator.userAgent || navigator.vendor || window.opera).toLowerCase(); if(userAgent.indexOf('mac')>0){ $("head").append('<style type="text/css">@-moz-document url-prefix() {h1 a, h2 a, h3 a, h4 a, h5 a, h1 a:hover, h2 a:hover, th a, th a:hover, h3 a:hover, h4 a:hover, h5 a:hover, #wikitext h2 a:hover, #wikitext h3 a:hover, #wikitext h4 a:hover {padding-bottom: 0.5em!important;} #pageheader .search input{font-family: "TyponineSans Regular 18";} #pagefooter .monospace{margin-top: -4px;} #navWrapper ul.left &gt; li{margin-top: -2px; padding-bottom: 2px;}#navWrapper ul.right &gt; li{margin-top: -5px; padding-bottom: 5px;}#navWrapper ul.right &gt; li ul{margin-top: 4px;} .slider-container .fixed-caption p{padding:8px 0 14px 0}}</style>'); } </script> <!--[if IE]> <link rel='stylesheet' href='https://id.arduino.cc//css/ie-monospace.css' type='text/css' /> <![endif]--> <div id="menuWings" class="fixed"></div> <!--[if IE 8]> <div class="alert-box panel ie8alert"> <p><strong>Arduino.cc offers limited compatibility for Internet Explorer 8. Get a modern browser as Chrome, Firefox or Safari.</strong></p> <a href="" class="close">&times;</a> </div> <![endif]--> <div id="pageheader"> <div class="row" class="contain-to-grid"> <div class="small-6 large-8 eight columns"> <div class="title"><a href="http://www.arduino.cc/">Arduino</a></div> </div> <div class="small-6 large-4 four columns search"> <div class="row collapse"> <form method="GET" action="http://www.google.com/search"> <div class="small-12 twelve columns"> <i class="icon-search-2"></i> <input type="hidden" name="ie" value="UTF-8"> <input type="hidden" name="oe" value="UTF-8"> <input type="text" name="q" size="25" maxlength="255" value="" placeholder="Search the Arduino Website"> <input type="submit" name="btnG" VALUE="search"> <input type="hidden" name="domains" value="http://www.arduino.cc"> <input type="hidden" name="sitesearch" value="http://www.arduino.cc"> </div> </form> </div> </div> </div> <!--[if gte IE 9]><!--> <div id="navWrapper" class="sticky"> <!--<![endif]--> <!--[if IE 8]> <div id="navWrapper"> <![endif]--> <nav class="top-bar" data-options="is_hover:true" > <ul class="title-area"> <li class="name"></li> </ul> <section class="top-bar-section"> <ul class="left"> <li id="navLogo"> <a href="http://www.arduino.cc/"> <img src="../../img/logo_46.png" alt="userpicture" /> </a> </li> <li id="navHome"><a href="http://www.arduino.cc/">Home</a></li> <li><a href="http://store.arduino.cc/">Buy</a></li> <li><a href="http://www.arduino.cc/en/Main/Software">Download</a></li> <li class="has-dropdown"><a href="#">Products</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Main/Products">Arduino <span class="menudescription">(USA only)</span></a></li> <li><a href="http://www.arduino.cc/en/Main/GenuinoProducts">Genuino <span class="menudescription">(outside USA)</span></a></li> <li><a href="http://www.arduino.cc/en/ArduinoAtHeart/Products">AtHeart</a></li> <li><a href="http://www.arduino.cc/en/ArduinoCertified/Products">Certified</a></li> </ul> </li> <li class="has-dropdown active"><a href="#">Learning</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Guide/HomePage">Getting started</a></li> <li><a href="http://www.arduino.cc/en/Tutorial/HomePage">Tutorials</a></li> <li><a href="HomePage.html">Reference</a></li> <li><a href="http://www.arduino.cc/en/Main/CTCprogram">CTC Program</a></li> <li><a href="http://playground.arduino.cc/">Playground</a></li> </ul> </li> <li><a href="http://forum.arduino.cc/">Forum</a></li> <li class="has-dropdown"><a href="#">Support</a> <ul class="dropdown"> <li><a href="http://www.arduino.cc/en/Main/FAQ">FAQ</a></li> <li><a href="http://www.arduino.cc/en/ContactUs">Contact Us</a></li> </ul> </li> <li><a href="http://blog.arduino.cc/">Blog</a></li> </ul> <ul class="right"> <li><a href="https://id.arduino.cc/auth/login/?returnurl=http%3A%2F%2Fwww.arduino.cc%2Fen%2FReference%2FYunServerWrite" class="cart">LOG IN</a></li> <li><a href="https://id.arduino.cc/auth/signup" class="cart">SIGN UP</a></li> </ul> </section> </nav> </div> </div> <br class="clear"/> <div id="pagetext"> <!--PageText--> <div id='wikitext'> <p><strong>Reference</strong> &nbsp; <a class='wikilink' href='HomePage.html'>Language</a> | <a class='wikilink' href='Libraries.html'>Libraries</a> | <a class='wikilink' href='Comparison.html'>Comparison</a> | <a class='wikilink' href='Changes.html'>Changes</a> </p> <p class='vspace'></p><p><a class='wikilink' href='YunBridgeLibrary.html'>YunBridgeLibrary</a> : <em><span class='wikiword'>YunServer</span></em> class </p> <p class='vspace'></p><h2>write()</h2> <h4>Description</h4> <p>Write data to all the clients connected to a server. </p> <p class='vspace'></p><h4>Syntax</h4> <p><em>server</em>.write(data) </p> <p class='vspace'></p><h4>Parameters</h4> <ul><li><em>server</em> : the named instance of <span class='wikiword'>YunServer</span> </li><li><em>data</em> : the value to write (byte or char) </li></ul><p class='vspace'></p><h4>Returns</h4> <p>byte<br />write() returns the number of bytes written. It is not necessary to read this. </p> <p class='vspace'></p><h4>Functions</h4> <ul><li><a class='wikilink' href='YunServerBegin.html'>begin()</a> </li><li><a class='wikilink' href='YunServerListenOnLocalhost.html'>listenOnLocalhost()</a> </li><li><a class='wikilink' href='YunServerNoListenOnLocoalhost.html'>noListenOnLocoalhost()</a> </li></ul><p><a class='wikilink' href='HomePage.html'>Reference Home</a> </p> <p class='vspace'></p><p><em>Corrections, suggestions, and new documentation should be posted to the <a class='urllink' href='http://arduino.cc/forum/index.php/board,23.0.html' rel='nofollow'>Forum</a>.</em> </p> <p class='vspace'></p><p>The text of the Arduino reference is licensed under a <a class='urllink' href='http://creativecommons.org/licenses/by-sa/3.0/' rel='nofollow'>Creative Commons Attribution-ShareAlike 3.0 License</a>. Code samples in the reference are released into the public domain. </p> </div> <!-- AddThis Button Style BEGIN --> <style> .addthis_toolbox { margin: 2em 0 1em; } .addthis_toolbox img { float: left; height: 25px; margin-right: 10px; width: auto; } .addthis_toolbox .social-container { float: left; height: 27px; width: auto; } .addthis_toolbox .social-container .social-content { float: left; margin-top: 2px; max-width: 0; overflow: hidden; -moz-transition: max-width .3s ease-out; -webkit-transition: max-width .3s ease-out; -o-transition: max-width .3s ease-out; transition: max-width .3s ease-out; } .addthis_toolbox .social-container:hover .social-content { max-width: 100px; -moz-transition: max-width .2s ease-in; -webkit-transition: max-width .2s ease-in; -o-transition: max-width .2s ease-in; transition: max-width .2s ease-in; } .addthis_toolbox .social-container .social-content a { float: left; margin-right: 5px; } .addthis_toolbox h3 { font-size: 24px; text-align: left; } </style> <!-- AddThis Button Style END --> <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style"> <h3>Share</h3> <!-- FACEBOOK --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/facebook.png" /> <div class="social-content"> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> </div> </div> <!-- TWITTER --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/twitter.png"> <div class="social-content"> <a class="addthis_button_tweet"></a> </div> </div> <!-- PINTEREST --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/pinterest.png"> <div class="social-content"> <a class="addthis_button_pinterest_pinit" pi:pinit:url="//www.addthis.com/features/pinterest" pi:pinit:media="//www.addthis.com/cms-content/images/features/pinterest-lg.png"></a> </div> </div> <!-- G+ --> <div class="social-container"> <img src="../pub/skins/arduinoWide_SSO/img/gplus.png"> <div class="social-content"> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> </div> </div> <script type="text/javascript">var addthis_config = {"data_track_addressbar":false};</script> <script type="text/javascript" src="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-50573fab238b0d34"></script> </div> <!-- AddThis Button END --> </div> <!-- eof pagetext --> </div> <!-- eof page --> <!--PageFooterFmt--> <div id="pagefooter"> <div id="newsletterModal" class="reveal-modal small"> <form action="http://www.arduino.cc/subscribe.php" method="post" name="sendy-subscribe-form" id="sendy-subscribe-form" class="form-popup"> <div class="modalHeader"> <h3 style="line-height: 1.8rem;" class="modal-header-alt">This link has expired. <br>Please re-subscribe to our Newsletters.</h3> <h3 class="modal-header-main">Subscribe to our Newsletters</h3> </div> <div class="modalBody" id="newsletterModalBody"> <div id="newsletterEmailField" class="row" style="padding-left: 0"> <div class="large-2 columns"> <label for="email" class="newsletter-form-label inline">Email</label> </div> <div class="large-10 columns" style="padding-left: 0"> <input placeholder="Enter your email address" type="email" name="email" class="subscribe-form-input" /> <p id="emailMissing" class="newsletterPopupError">Please enter a valid email to subscribe</p> </div> </div> <div style="margin-left:20px"> <div style="margin-bottom:0.3em"> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_newsletter_id" id="worldwide" class="newsletter-form-checkbox" /> <label for="worldwide"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Newsletter</div> </div> <div> <input style="display:none" type="checkbox" checked name="list[]" value="arduino_store_newsletter_id" id="store" class="newsletter-form-checkbox" /> <label for="store"></label> <div style="display:inline-block" class="newsletter-form-label">Arduino Store Newsletter</div> </div> </div> <div> <p class="newsletterPopupError2" id="newsletterSubscribeStatus"></p> </div> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button type="button" value="Cancel" class="popup-form-button white cancel-modal close-reveal-modal">Cancel</button> <button type="submit" name="Subscribe" id="subscribe-submit-btn" class="popup-form-button">Next</button> </div> </div> </form> <!-- step 2, confirm popup --> <div class="confirm-popup" style="margin-bottom:1em"> <div class="modalHeader"> <h3>Confirm your email address</h3> </div> <div class="modalBody" id="newsletterModalBody" style="padding-right:1em;margin-bottom:0"> <p style="margin-bottom:1em;font-size:15px"> We need to confirm your email address.<br> To complete the subscription, please click the link in the email we just sent you. </p> <p style="margin-bottom:1em;font-size:15px"> Thank you for subscribing! </p> <p style="margin-bottom:1em;font-size:15px"> Arduino<br> via Egeo 16<br> Torino, 10131<br> Italy<br> </p> </div> <div class="row modalFooter"> <div class="form-buttons-row"> <button name="Ok" class="popup-form-button" id="close-confirm-popup">Ok</button> </div> </div> </div> </div> <div id="pagefooter" class="pagefooter"> <div class="row"> <div class="large-8 eight columns"> <div class="large-4 four columns newsletter-box"> <!-- Begin Sendy Signup Form --> <h6>Newsletter</h6> <div> <input type="email" name="email" class="email" id="sendy-EMAIL" placeholder="Enter your email to sign up"> <i class="icon-right-small"></i> <input value="Subscribe" name="subscribe" id="sendy-subscribe" class="newsletter-button"> </div> <!--End sendy_embed_signup--> </div> <div class="clearfix"></div> <ul class="inline-list"> <li class="monospace">&copy;2015 Arduino</li> <li><a href="http://www.arduino.cc/en/Main/CopyrightNotice">Copyright Notice</a></li> <li><a href='http://www.arduino.cc/en/Main/ContactUs'>Contact us</a></li> <li><a href='http://www.arduino.cc/en/Main/AboutUs'>About us</a></li> <li><a href='http://www.arduino.cc/Careers'>Careers</a></li> </ul> </div> <div class="large-4 four columns"> <ul id="arduinoSocialLinks" class="arduino-social-links"> <li> <a href="https://twitter.com/arduino"> <img src="../../img/twitter.png" /> </a> </li> <li> <a href="https://www.facebook.com/official.arduino"> <img src="../../img/facebook.png" /> </a> </li> <li> <a href="https://plus.google.com/+Arduino"> <img src="../../img/gplus.png" /> </a> </li> <li> <a href="https://www.flickr.com/photos/arduino_cc"> <img src="../../img/flickr.png" /> </a> </li> <li> <a href="https://youtube.com/arduinoteam"> <img src="../../img/youtube.png" /> </a> </li> </ul> </div> </div> </div> </div> <!--/PageFooterFmt--> <!--[if gte IE 9]><!--> <script src="http://arduino.cc/js/foundation.min.js"></script> <script src="http://arduino.cc/js/foundation.topbar.custom.js"></script> <script> $(document).foundation(); </script> <!--<![endif]--> <!--[if IE 8]> <script src="//arduino.cc/js/foundation_ie8.min.js"></script> <script src="//arduino.cc/js/ie8/jquery.foundation.orbit.js"></script> <script src="//arduino.cc/js/ie8/jquery.foundation.alerts.js"></script> <script src="//arduino.cc/js/app.js"></script> <script> $(window).load(function(){ $("#featured").orbit(); }); </script> <![endif]--> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22581631-3']); _gaq.push(['_setDomainName', 'arduino.cc']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <script> $(window).load(function(){ $('a').each (function () { href = $(this).attr ('href'); if (href !== undefined && href.substring (0, 4) == 'http' && href.indexOf ('https://www.arduino.cc/en/Reference/arduino.cc') == -1) $(this).attr ('target', '_blank'); }); // js for language dropdown $('.language-dropdown .current').on('click', function(e){ e.stopPropagation(); $('.language-dropdown ul').toggle(); }); $('.language-dropdown .selector').on('click', function(e){ e.stopPropagation(); $('.language-dropdown ul').toggle(); }); $(document).on('click', function(){ $('.language-dropdown ul:visible').hide(); }); $('.language-dropdown li a').on('click', function(e){ $('.language-dropdown .current').text($(this).text()); }); //js for product pages navbar var menu = $(".product-page-nav"); var menuItems = menu.find("a"); var timeoutId = null; var limitTop = 600; var menuOffset = $('.product-page-nav li').first().offset(); if(menuOffset) { limitTop = menuOffset.top; } var limitBottom = $('.addthis_toolbox').offset().top; var activateSection = function($sectionToActivate) { var label=$sectionToActivate.attr('label'); $(".product-page-nav").find('li').removeClass('active'); $sectionToActivate.addClass('active'); }; menuItems.click(function(e){ e.preventDefault(); var href = $(this).attr("href"), offsetTop = href === "#" ? 0 : $(href).offset().top, adjust = 0; if($(this).parent('li').hasClass('active') === false) { adjust = 80; $('html, body').animate({ scrollTop: offsetTop - adjust }, 1500, 'easeOutExpo'); } }); $(window).scroll(function () { var windscroll = $(window).scrollTop(); if(windscroll < limitTop) { $('.menu').removeClass('sticky'); $('.menu').removeClass('fixed'); } else { $('.menu').addClass('sticky'); } var menuEdgeBottomOffset = $('.menu.columns').offset(); var menuEdgeBottom = 0; if(menuEdgeBottomOffset) { menuEdgeBottom = menuEdgeBottomOffset.top + $('.menu.columns').height(); } if(menuEdgeBottom > limitBottom) { $('.menu').fadeOut(); } else { $('.menu').fadeIn(); } menuItems.each(function(i) { var href = $(this).attr("href"); if ($(href).offset().top <= windscroll + 150) { if(timeoutId) { clearTimeout(timeoutId); } timeoutId = setTimeout(activateSection, 60, $(".product-page-nav").find('li').eq(i)); } }); }); }); </script> </body> <!-- Mirrored from www.arduino.cc/en/Reference/YunServerWrite by HTTrack Website Copier/3.x [XR&CO'2010], Mon, 26 Oct 2015 14:08:13 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><!-- /Added by HTTrack --> </html>
{'content_hash': '739d4fde8cbf089387236d9124b76ca9', 'timestamp': '', 'source': 'github', 'line_count': 608, 'max_line_length': 642, 'avg_line_length': 39.13322368421053, 'alnum_prop': 0.6120287479510781, 'repo_name': 'MakerCollider/curie-smartnode-mac', 'id': '7743bdb15e2a4df22815d74c580e19b83d7b65b0', 'size': '23793', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'curie-smartnode/Arduino.app/Contents/Java/reference/www.arduino.cc/en/Reference/YunServerWrite.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '886730'}, {'name': 'Assembly', 'bytes': '8144'}, {'name': 'Batchfile', 'bytes': '47753'}, {'name': 'C', 'bytes': '33464958'}, {'name': 'C++', 'bytes': '11285136'}, {'name': 'CSS', 'bytes': '279648'}, {'name': 'Go', 'bytes': '2607'}, {'name': 'HTML', 'bytes': '19284702'}, {'name': 'Java', 'bytes': '2947'}, {'name': 'JavaScript', 'bytes': '652378'}, {'name': 'Logos', 'bytes': '229868'}, {'name': 'Makefile', 'bytes': '159063'}, {'name': 'Objective-C', 'bytes': '1018078'}, {'name': 'Perl', 'bytes': '4173'}, {'name': 'Python', 'bytes': '196949'}, {'name': 'Roff', 'bytes': '2787716'}, {'name': 'Shell', 'bytes': '60895'}, {'name': 'XS', 'bytes': '17413'}]}
TestApp::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_assets = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify end
{'content_hash': '531a2d17ed8209e6fe926631e8f81ca7', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 104, 'avg_line_length': 36.125, 'alnum_prop': 0.7469723183391004, 'repo_name': 'ravensnowbird/activeadmin-mongoid-rails4', 'id': '76814e83155251c7d3e143a84a5a92d6c85d263a', 'size': '2312', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'test_app/config/environments/production.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '546'}, {'name': 'JavaScript', 'bytes': '809'}, {'name': 'Ruby', 'bytes': '61320'}]}
package oceania.entity; import net.minecraft.block.Block; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.Item; import net.minecraft.world.World; import oceania.items.ItemMulti.ItemMultiType; import oceania.items.Items; public class EntityOceaniaBoatNormal extends EntityOceaniaBoat { public EntityOceaniaBoatNormal(World world) { super(world); } public EntityOceaniaBoatNormal(World world, double x, double y, double z) { super(world, x, y, z); } @Override public float getBoatWidth() { return 1.5f; } @Override public float getBoatLength() { return 1.5f; } @Override public float getBoatHeight() { return 0.6f; } @Override public float getMaxSpeed() { return 0.35f + ((float) getBoatType().ordinal() * 0.05f); } @Override public double getMountedYOffset() { return 1.0f; } @SuppressWarnings("incomplete-switch") @Override public void dropItemsOnDeath() { switch (getBoatType()) { case ATLANTIUM: EntityItem item = this.dropItem(Items.itemMulti.itemID, 5); item.getEntityItem().setItemDamage(ItemMultiType.ATLANTIUM.ordinal()); break; case IRON: this.dropItem(Item.ingotIron.itemID, 5); break; case WOOD: this.dropItem(Item.stick.itemID, 3); this.dropItem(Block.planks.blockID, 2); break; } } }
{'content_hash': '38becba328c9a5d917689592172ed74e', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 74, 'avg_line_length': 18.013513513513512, 'alnum_prop': 0.7066766691672918, 'repo_name': 'TrainerGuy22/Oceania', 'id': '9a5ed4007de9d47916cbb8d0b70e62ec563da195', 'size': '1333', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/oceania/entity/EntityOceaniaBoatNormal.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Groovy', 'bytes': '1613'}, {'name': 'Java', 'bytes': '211677'}]}
Make sure you read the Wiki https://github.com/AngularClass/angular2-webpack-starter/wiki ## Submitting Pull Requests If you're changing the structure of the repository please create an issue first ## Submitting bug reports Make sure you are on latest changes and that you ran this command `npm run clean:install` after updating your local repository. If you can, please provide more infomation about your environment such as browser, operating system, node version, and npm version
{'content_hash': 'f32a89352b37dd14d896e355786ad1a7', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 258, 'avg_line_length': 53.888888888888886, 'alnum_prop': 0.8082474226804124, 'repo_name': 'plantener/WebPackSetup', 'id': '230120722b249c7218775a793637e4b64dc9f79b', 'size': '521', 'binary': False, 'copies': '41', 'ref': 'refs/heads/master', 'path': '.github/CONTRIBUTING.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2706'}, {'name': 'HTML', 'bytes': '7966'}, {'name': 'JavaScript', 'bytes': '29818'}, {'name': 'Shell', 'bytes': '195'}, {'name': 'TypeScript', 'bytes': '22338'}]}
<?xml version="1.0" ?> <!DOCTYPE FTCS SYSTEM "futuretense_cs.dtd"> <FTCS Version="1.1"> <!-- $Logfile: /VerticalApps/XcelerateB/install/Gator/Populate/ElementCatalog/OpenMarket/Xcelerate/AssetType/PageDefinition/AppendSelectDetailsSE.xml $ $Revision: 2 $ $Modtime: 7/08/02 4:51p $ --> <!-- - Confidential and Proprietary Information of FutureTense Inc. - All Rights Reserved. - - AppendSelectDetailsSE.xml - - DESCRIPTION - Add to search engine query for Article-specific search parameters - (as defined by Article/SearchForm.xml). - - ARGUMENTS - seQuery - SEARCH WHAT query string. Append to this. - seType - SEARCH TYPE value. Change it or leave it alone. - seRelevance - SEARCH RELEVANCE value. Change it or leave it alone. - sqlQueryend - Tail end of WHERE expression for secondary SQL query. - (FORM fields) - All form fields defined by SearchForm.xml - seLeft, seRight - Left and right strings. Used as - fieldname Variables.seLeft fieldvalue Variables.seRight - - HISTORY --> <callelement NAME="OpenMarket/Gator/FlexibleAssets/Common/AppendSelectDetailsSE"/> </FTCS>
{'content_hash': 'a8c79582a6edb964445e26743242ad19', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 147, 'avg_line_length': 27.285714285714285, 'alnum_prop': 0.7146596858638743, 'repo_name': 'sciabarra/AgileSites', 'id': '1ce8f23f3934621bd29eb4f4c909faa8a2651dae', 'size': '1146', 'binary': False, 'copies': '3', 'ref': 'refs/heads/1.8.1', 'path': 'export/envision/Demo-11.6/src/_metadata/ELEMENTS/OpenMarket/Xcelerate/AssetType/PageDefinition/AppendSelectDetailsSE.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3000'}, {'name': 'CSS', 'bytes': '28291'}, {'name': 'HTML', 'bytes': '23822'}, {'name': 'Java', 'bytes': '906893'}, {'name': 'JavaScript', 'bytes': '12920'}, {'name': 'Scala', 'bytes': '61202'}, {'name': 'Shell', 'bytes': '2956'}]}
using System; using System.IO; using System.Xml; using System.Collections.Generic; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility { /// <summary> /// Fixture Class for the v9 OM Public Interface Compatibility Tests. UsingTaskCollection Class. /// Also see Toolset tests in the Project test class. /// </summary> [TestFixture] public class UsingTaskCollection_Tests { /// <summary> /// Imports Cache issue causes xml not to be loaded /// This is a test case to reproduce some quirkiness found when running tests out of order. /// </summary> [Test] public void ImportsUsingTask() { string importPath = String.Empty; try { importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.Content3SimpleTargetsDefaultSpecified); Project p = new Project(); p.Save(importPath); // required to reproduce importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskFile); Project p2 = new Project(); // new Engine() here fixes testcase p2.AddNewImport(importPath, "true"); object o = p2.EvaluatedProperties; // evaluate the import Assertion.AssertNull(CompatibilityTestHelpers.FindUsingTaskByName("TaskName", p2.UsingTasks)); // fails to find task } finally { CompatibilityTestHelpers.RemoveFile(importPath); } } /// <summary> /// Count Test. Increment Count on Import Add in OM /// </summary> [Test] public void Count_IncrementOnAddFile() { Project p = new Project(new Engine()); Assertion.AssertEquals(0, p.UsingTasks.Count); p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll"); Assertion.AssertEquals(0, p.UsingTasks.Count); object o = p.EvaluatedProperties; Assertion.AssertEquals(1, p.UsingTasks.Count); } /// <summary> /// Count Test. Increment Count on Import Add in OM /// </summary> [Test] public void Count_IncrementOnAddName() { Project p = new Project(new Engine()); Assertion.AssertEquals(0, p.UsingTasks.Count); p.AddNewUsingTaskFromAssemblyName("TaskName", "AssemblyName"); Assertion.AssertEquals(0, p.UsingTasks.Count); object o = p.EvaluatedProperties; Assertion.AssertEquals(1, p.UsingTasks.Count); } /// <summary> /// Count Test. Increment Count on Import Add in XML /// </summary> [Test] public void Count_IncrementOnAddFileXml() { string projectPath = String.Empty; try { projectPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.proj", TestData.ContentUsingTaskFile); Project p = new Project(new Engine()); Assertion.AssertEquals(0, p.UsingTasks.Count); p.Load(projectPath); Assertion.AssertEquals(1, p.UsingTasks.Count); } finally { CompatibilityTestHelpers.RemoveFile(projectPath); } } /// <summary> /// Count Test. Decrement\Reset Count to 0 on reload project xml /// </summary> [Test] public void Count_DecrementOnRemove() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll"); object o = p.EvaluatedProperties; Assertion.AssertEquals(1, p.UsingTasks.Count); p.LoadXml(TestData.ContentSimpleTools35); Assertion.AssertEquals(0, p.UsingTasks.Count); o = p.EvaluatedProperties; Assertion.AssertEquals(0, p.UsingTasks.Count); } /// <summary> /// IsSynchronized Test /// </summary> [Test] public void IsSynchronized() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName", "AssemblyFile.dll"); Assertion.AssertEquals(false, p.UsingTasks.IsSynchronized); } /// <summary> /// SyncRoot Test, ensure that SyncRoot returns and we can take a lock on it. /// </summary> [Test] public void SyncRoot() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll"); p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll"); UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count]; p.UsingTasks.CopyTo(usingTasks, 0); lock (p.UsingTasks.SyncRoot) { int i = 0; foreach (UsingTask usingTask in p.UsingTasks) { Assertion.AssertEquals(usingTasks[i].AssemblyFile, usingTask.AssemblyFile); i++; } } } /// <summary> /// SyncRoot Test, copy into a strongly typed array and assert content against the source collection. /// </summary> [Test] public void CopyTo_ZeroIndex() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll"); p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll"); UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count]; p.UsingTasks.CopyTo(usingTasks, 0); int i = 0; foreach (UsingTask usingTask in p.UsingTasks) { Assertion.AssertEquals(usingTasks[i].AssemblyFile, usingTask.AssemblyFile); i++; } } /// <summary> /// SyncRoot Test, copy into a strongly typed array and assert content against the source collection. /// </summary> [Test] public void CopyTo_OffsetIndex() { int offSet = 3; Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll"); p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll"); UsingTask[] taskArray = new UsingTask[p.UsingTasks.Count + offSet]; p.UsingTasks.CopyTo(taskArray, offSet); int i = offSet - 1; Assertion.AssertNull(taskArray[offSet - 1]); foreach (UsingTask usingTask in p.UsingTasks) { Assertion.AssertEquals(taskArray[i].AssemblyFile, usingTask.AssemblyFile); i++; } } /// <summary> /// SyncRoot Test, copy into a strongly typed array with an offset where the array is too small /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void CopyTo_OffsetIndexArrayTooSmall() { int offSet = 3; Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll"); p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll"); UsingTask[] usingTasks = new UsingTask[p.UsingTasks.Count]; p.UsingTasks.CopyTo(usingTasks, offSet); } /// <summary> /// Copy to a weakly typed array, no offset. Itterate over collection /// </summary> [Test] public void CopyTo_WeakAndGetEnumerator() { Project p = new Project(new Engine()); p.AddNewUsingTaskFromAssemblyFile("TaskName1", "AssemblyFile1.dll"); p.AddNewUsingTaskFromAssemblyFile("TaskName2", "AssemblyFile2.dll"); Array taskArray = Array.CreateInstance(typeof(UsingTask), p.UsingTasks.Count); p.UsingTasks.CopyTo(taskArray, 0); Assertion.AssertEquals(p.UsingTasks.Count, taskArray.Length); int i = 0; foreach (UsingTask usingTask in p.UsingTasks) { Assertion.AssertEquals(((UsingTask)taskArray.GetValue(i)), usingTask.AssemblyFile); i++; } } } }
{'content_hash': 'ec4e4a162d96937574e3f90688fef58f', 'timestamp': '', 'source': 'github', 'line_count': 219, 'max_line_length': 144, 'avg_line_length': 39.52054794520548, 'alnum_prop': 0.5792027729636049, 'repo_name': 'nikson/msbuild', 'id': '7605ad5a88db0b2df46512ed254e031748050c5e', 'size': '9225', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/OrcasEngine/UnitTests/Compatibility/UsingTaskCollection_Tests.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '6858'}, {'name': 'C', 'bytes': '961'}, {'name': 'C#', 'bytes': '25829525'}, {'name': 'C++', 'bytes': '6'}, {'name': 'Groovy', 'bytes': '3271'}, {'name': 'Scilab', 'bytes': '8'}, {'name': 'Shell', 'bytes': '230'}, {'name': 'XSLT', 'bytes': '69632'}]}
 #pragma once #include <aws/glue/Glue_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace Glue { namespace Model { /** * <p>Specifies a transform that merges a <code>DynamicFrame</code> with a staging * <code>DynamicFrame</code> based on the specified primary keys to identify * records. Duplicate records (records with the same primary keys) are not * de-duplicated. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/glue-2017-03-31/Merge">AWS API * Reference</a></p> */ class AWS_GLUE_API Merge { public: Merge(); Merge(Aws::Utils::Json::JsonView jsonValue); Merge& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the transform node.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the transform node.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the transform node.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the transform node.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the transform node.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the transform node.</p> */ inline Merge& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the transform node.</p> */ inline Merge& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the transform node.</p> */ inline Merge& WithName(const char* value) { SetName(value); return *this;} /** * <p>The data inputs identified by their node names.</p> */ inline const Aws::Vector<Aws::String>& GetInputs() const{ return m_inputs; } /** * <p>The data inputs identified by their node names.</p> */ inline bool InputsHasBeenSet() const { return m_inputsHasBeenSet; } /** * <p>The data inputs identified by their node names.</p> */ inline void SetInputs(const Aws::Vector<Aws::String>& value) { m_inputsHasBeenSet = true; m_inputs = value; } /** * <p>The data inputs identified by their node names.</p> */ inline void SetInputs(Aws::Vector<Aws::String>&& value) { m_inputsHasBeenSet = true; m_inputs = std::move(value); } /** * <p>The data inputs identified by their node names.</p> */ inline Merge& WithInputs(const Aws::Vector<Aws::String>& value) { SetInputs(value); return *this;} /** * <p>The data inputs identified by their node names.</p> */ inline Merge& WithInputs(Aws::Vector<Aws::String>&& value) { SetInputs(std::move(value)); return *this;} /** * <p>The data inputs identified by their node names.</p> */ inline Merge& AddInputs(const Aws::String& value) { m_inputsHasBeenSet = true; m_inputs.push_back(value); return *this; } /** * <p>The data inputs identified by their node names.</p> */ inline Merge& AddInputs(Aws::String&& value) { m_inputsHasBeenSet = true; m_inputs.push_back(std::move(value)); return *this; } /** * <p>The data inputs identified by their node names.</p> */ inline Merge& AddInputs(const char* value) { m_inputsHasBeenSet = true; m_inputs.push_back(value); return *this; } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline const Aws::String& GetSource() const{ return m_source; } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline bool SourceHasBeenSet() const { return m_sourceHasBeenSet; } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline void SetSource(const Aws::String& value) { m_sourceHasBeenSet = true; m_source = value; } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline void SetSource(Aws::String&& value) { m_sourceHasBeenSet = true; m_source = std::move(value); } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline void SetSource(const char* value) { m_sourceHasBeenSet = true; m_source.assign(value); } /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline Merge& WithSource(const Aws::String& value) { SetSource(value); return *this;} /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline Merge& WithSource(Aws::String&& value) { SetSource(std::move(value)); return *this;} /** * <p>The source <code>DynamicFrame</code> that will be merged with a staging * <code>DynamicFrame</code>.</p> */ inline Merge& WithSource(const char* value) { SetSource(value); return *this;} /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline const Aws::Vector<Aws::Vector<Aws::String>>& GetPrimaryKeys() const{ return m_primaryKeys; } /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline bool PrimaryKeysHasBeenSet() const { return m_primaryKeysHasBeenSet; } /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline void SetPrimaryKeys(const Aws::Vector<Aws::Vector<Aws::String>>& value) { m_primaryKeysHasBeenSet = true; m_primaryKeys = value; } /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline void SetPrimaryKeys(Aws::Vector<Aws::Vector<Aws::String>>&& value) { m_primaryKeysHasBeenSet = true; m_primaryKeys = std::move(value); } /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline Merge& WithPrimaryKeys(const Aws::Vector<Aws::Vector<Aws::String>>& value) { SetPrimaryKeys(value); return *this;} /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline Merge& WithPrimaryKeys(Aws::Vector<Aws::Vector<Aws::String>>&& value) { SetPrimaryKeys(std::move(value)); return *this;} /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline Merge& AddPrimaryKeys(const Aws::Vector<Aws::String>& value) { m_primaryKeysHasBeenSet = true; m_primaryKeys.push_back(value); return *this; } /** * <p>The list of primary key fields to match records from the source and staging * dynamic frames.</p> */ inline Merge& AddPrimaryKeys(Aws::Vector<Aws::String>&& value) { m_primaryKeysHasBeenSet = true; m_primaryKeys.push_back(std::move(value)); return *this; } private: Aws::String m_name; bool m_nameHasBeenSet = false; Aws::Vector<Aws::String> m_inputs; bool m_inputsHasBeenSet = false; Aws::String m_source; bool m_sourceHasBeenSet = false; Aws::Vector<Aws::Vector<Aws::String>> m_primaryKeys; bool m_primaryKeysHasBeenSet = false; }; } // namespace Model } // namespace Glue } // namespace Aws
{'content_hash': 'a8b7f3ad49c6d102f357ca4e834cc9c8', 'timestamp': '', 'source': 'github', 'line_count': 242, 'max_line_length': 159, 'avg_line_length': 33.50413223140496, 'alnum_prop': 0.6372718302910706, 'repo_name': 'aws/aws-sdk-cpp', 'id': '392978627ec417aab05ac92ad5f60cb39bf2a0f5', 'size': '8227', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'aws-cpp-sdk-glue/include/aws/glue/model/Merge.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]}
import React, {Component} from 'react' import { AppRegistry, StyleSheet, ListView, Image, Text, View } from 'react-native'; let movieDatas = require("./data.json") let movies = movieDatas.movies export default class MoveListView extends Component { constructor(props) { super(props) const ds = new ListView.DataSource({rowHasChanged: (oldRow, newRow)=>oldRow !== newRow}) this.state={ dataSource:ds.cloneWithRows(movies) } } _renderRow(movie){ return ( <View style={styles.row} key={movie.id}> <Image source={{uri: movie.posters.thumbnail}} style={styles.thumbnail}/> <View style={styles.rightCon}> <Text style={styles.title}>{movie.title}</Text> <Text style={styles.year}>{movie.year}</Text> </View> </View> ) } _renderHeader(){ return ( <View style={styles.header}> <Text style={styles.header_text}>Movies List</Text> <View style={styles.header_line}></View> </View> ) } _renderSeparator(sectionId,rowId){ return ( <View style={styles.separator} key={sectionId+rowId}></View> ) } render() { return ( <ListView style={styles.container} dataSource={this.state.dataSource} renderRow={this._renderRow} renderHeader={this._renderHeader} renderSeparator={this._renderSeparator} initialListSize={10}/> ) } } const styles = StyleSheet.create({ container:{ flex:1 }, row:{ flexDirection:"row", padding:5, margin:3, alignItems:"center", backgroundColor:"#F5FCFF", borderRadius:10, borderColor:"gray", borderWidth:0.1 }, thumbnail:{ width:81, height:81, borderRadius:10, }, rightCon:{ marginLeft:10, flex:1 }, title:{ fontSize:18, marginTop:3, marginBottom:3, textAlign:"center" }, year:{ marginBottom:3, textAlign:"center" }, header:{ height:44, backgroundColor:"#F5FCFF" }, header_text:{ flex:1, fontSize:20, textAlign:"center", lineHeight:44 }, header_line:{ height:1, backgroundColor:"#CCCCCC" }, separator:{ height:1, backgroundColor:"#CCCCCC" } })
{'content_hash': '4caf97ef4d9c769a69b7dbb893943ad4', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 96, 'avg_line_length': 23.283185840707965, 'alnum_prop': 0.5119726339794755, 'repo_name': 'lvtanxi/HelloReactNative', 'id': '303275011e7ba91ec4f36c488bb8ab7aaea0bd79', 'size': '2631', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MoveListView.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '4540'}, {'name': 'JavaScript', 'bytes': '71752'}, {'name': 'Objective-C', 'bytes': '4422'}, {'name': 'Python', 'bytes': '1657'}]}
.oo-ui-icon-alert { background-image: url('themes/wikimediaui/images/icons/alert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/alert.svg'); } .oo-ui-icon-bell { background-image: url('themes/wikimediaui/images/icons/bell.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bell.svg'); } .oo-ui-icon-error { background-image: url('themes/wikimediaui/images/icons/error.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/error.svg'); } .oo-ui-icon-message { background-image: url('themes/wikimediaui/images/icons/message.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/message.svg'); } .oo-ui-icon-notice { background-image: url('themes/wikimediaui/images/icons/notice.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/notice.svg'); } .oo-ui-icon-speechBubble { background-image: url('themes/wikimediaui/images/icons/speechBubble-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/speechBubble-rtl.svg'); } .oo-ui-icon-speechBubbleAdd { background-image: url('themes/wikimediaui/images/icons/speechBubbleAdd-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/speechBubbleAdd-rtl.svg'); } .oo-ui-icon-speechBubbles { background-image: url('themes/wikimediaui/images/icons/speechBubbles-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/speechBubbles-rtl.svg'); } .oo-ui-icon-tray { background-image: url('themes/wikimediaui/images/icons/tray.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/tray.svg'); }
{'content_hash': 'a24f3bf004a58bd0353733850c68a116', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 139, 'avg_line_length': 55.810810810810814, 'alnum_prop': 0.752542372881356, 'repo_name': 'sufuf3/cdnjs', 'id': 'f82d0bbaf112739df4ff75c2284776470f9c76f5', 'size': '2287', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ajax/libs/oojs-ui/0.32.0/oojs-ui-apex-icons-alerts.rtl.css', 'mode': '33188', 'license': 'mit', 'language': []}
/* =============================================================================================================================== Put your custom CSS in this file. =============================================================================================================================== */ /* CSS to hide sidebar numbering (uncomment to enable) */ /* #sidebar ul.topics > li > a b { visibility: hidden; } */ /* CSS to hide clipboard icon (uncomment to enable) */ /* .copy-to-clipboard { display:none; } */
{'content_hash': '2231dff91fba563179f21156cfddf451', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 127, 'avg_line_length': 26.1, 'alnum_prop': 0.3218390804597701, 'repo_name': 'Gold-Sabre/raspi-grav', 'id': 'e692d1b263f23c81688a79aa4b0f576f39c613d9', 'size': '522', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'themes/mytheme/css/custom.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '102066'}, {'name': 'HTML', 'bytes': '20694'}, {'name': 'JavaScript', 'bytes': '11180'}, {'name': 'PHP', 'bytes': '268'}, {'name': 'Shell', 'bytes': '41'}]}
package greenapi.core.model.software.os.commands; import greenapi.core.model.resources.net.NetworkInterface; public interface NetworkInterfaceDescription extends Command<NetworkInterface> { /** * Return an instance of the {@link NetworkInterface} that has the given id. * * @param id * The id of the network interface to be returned. Might not be <code>null</code>. * @return An instance of the {@link NetworkInterface} that has the given id */ NetworkInterface execute(String id); }
{'content_hash': '7f3e37c5927f4398ade70aea5dafcc35', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 97, 'avg_line_length': 31.647058823529413, 'alnum_prop': 0.7044609665427509, 'repo_name': 'alessandroleite/greenapi', 'id': 'eaac0e260e1161b0b44eebb42185caa4e38ae809', 'size': '1654', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/greenapi/core/model/software/os/commands/NetworkInterfaceDescription.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '424194'}]}
<?php namespace garethp\ews\API\Type; use garethp\ews\API\Type; /** * Class representing WorkingHoursType * * * XSD Type: WorkingHours * * @method SerializableTimeZoneType getTimeZone() * @method WorkingHoursType setTimeZone(SerializableTimeZoneType $timeZone) * @method WorkingHoursType addWorkingPeriodArray(WorkingPeriodType $workingPeriodArray) * @method WorkingPeriodType[] getWorkingPeriodArray() * @method WorkingHoursType setWorkingPeriodArray(array $workingPeriodArray) */ class WorkingHoursType extends Type { /** * @var \garethp\ews\API\Type\SerializableTimeZoneType */ protected $timeZone = null; /** * @var \garethp\ews\API\Type\WorkingPeriodType[] */ protected $workingPeriodArray = null; }
{'content_hash': '2a1672cd210219a24b8ee2324a43039e', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 88, 'avg_line_length': 24.419354838709676, 'alnum_prop': 0.7397622192866579, 'repo_name': 'Garethp/php-ews', 'id': '21eef0ccc6029c3e7dd4a133d7c994d9abd236eb', 'size': '757', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/API/Type/WorkingHoursType.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'PHP', 'bytes': '1046851'}]}
const test = require('tape') const fs = require('fs') const path = require('path') const WebTorrent = require('webtorrent') const torrentPoster = require('../build/renderer/lib/torrent-poster') const client = new WebTorrent() test("get cover from: 'wiredCd.torrent'", (t) => { const torrentPath = path.join(__dirname, '..', 'static', 'wiredCd.torrent') const torrentData = fs.readFileSync(torrentPath) client.add(torrentData, (torrent) => { torrentPoster(torrent, (err, buf, extension) => { if (err) { t.fail(err) } else { t.equals(extension, '.jpg') t.end() } }) }) })
{'content_hash': 'e44c3733b0c6d5db3b3e39e733825c03', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 77, 'avg_line_length': 25.32, 'alnum_prop': 0.617693522906793, 'repo_name': 'feross/webtorrent-app', 'id': '501acdfe4375a0b6a164a879160794d8a280e702', 'size': '633', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'test/test-select-poster.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '11189'}, {'name': 'HTML', 'bytes': '339'}, {'name': 'JavaScript', 'bytes': '63283'}, {'name': 'Shell', 'bytes': '438'}]}
define({ "_widgetLabel": "Pārskata karte" });
{'content_hash': 'a29920c0b36df8ac069561ced11b95e5', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 34, 'avg_line_length': 15.666666666666666, 'alnum_prop': 0.6382978723404256, 'repo_name': 'tmcgee/cmv-wab-widgets', 'id': '4ff948ee4894b3a5df971192e55d25dcfcf7cb76', 'size': '48', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'wab/2.13/widgets/OverviewMap/nls/lv/strings.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1198579'}, {'name': 'HTML', 'bytes': '946685'}, {'name': 'JavaScript', 'bytes': '22190423'}, {'name': 'Pascal', 'bytes': '4207'}, {'name': 'TypeScript', 'bytes': '102918'}]}
module BetterRadar::Element module CategoricalInformation def retrieve_name(language = nil) preferred_language ||= language || BetterRadar.configuration.language self.names.find { |name| name[:language] == preferred_language }[:name] end end end
{'content_hash': '77eb1209d7192e33de45accebddf4e15', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 77, 'avg_line_length': 27.2, 'alnum_prop': 0.7132352941176471, 'repo_name': 'wegotcoders/better_radar', 'id': '94fc1d0bb51a8e7d2bf6421bead50591ec56e18d', 'size': '272', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/better_radar/element/categorical_information.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '64465'}]}
from __future__ import unicode_literals import warnings from django.test.utils import override_settings from reviewboard.scmtools.crypto_utils import (aes_decrypt, aes_encrypt, decrypt, decrypt_password, encrypt, encrypt_password, get_default_aes_encryption_key) from reviewboard.testing.testcase import TestCase @override_settings(SECRET_KEY='abcdefghijklmnopqrstuvwxyz012345') class CryptoUtilsTests(TestCase): """Unit tests for reviewboard.scmtools.crypto_utils.""" PLAIN_TEXT = 'this is a test 123 ^&*' CUSTOM_KEY = b'0123456789abcdef' def test_aes_decrypt(self): """Testing aes_decrypt""" # The encrypted value was made with PyCrypto, to help with # compatibility testing from older installs. encrypted = ( b'\xfb\xdc\xb5h\x15\xa1\xb2\xdc\xec\xf1\x14\xa9\xc6\xab\xb2J\x10' b'\'\xd4\xf6&\xd4k9\x82\xf6\xb5\x8bmu\xc8E\x9c\xac\xc5\x04@B' ) self.assertEqual(aes_decrypt(encrypted), self.PLAIN_TEXT) def test_aes_decrypt_with_custom_key(self): """Testing aes_decrypt with custom key""" # The encrypted value was made with PyCrypto, to help with # compatibility testing from older installs. encrypted = ( b'\x9cd$e\xb1\x9e\xe0z\xb8[\x9e!\xf2h\x90\x8d\x82f%G4\xc2\xf0' b'\xda\x8dr\x81ER?S6\x12%7\x98\x89\x90' ) self.assertEqual(aes_decrypt(encrypted, key=self.CUSTOM_KEY), self.PLAIN_TEXT) def test_aes_encrypt(self): """Testing aes_encrypt""" # The encrypted value will change every time, since the iv changes, # so we can't compare a direct value. Instead, we need to ensure that # we can decrypt what we encrypt. self.assertEqual(aes_decrypt(aes_encrypt(self.PLAIN_TEXT)), self.PLAIN_TEXT) def test_aes_encrypt_with_custom_key(self): """Testing aes_encrypt with custom key""" # The encrypted value will change every time, since the iv changes, # so we can't compare a direct value. Instead, we need to ensure that # we can decrypt what we encrypt. encrypted = aes_encrypt(self.PLAIN_TEXT, key=self.CUSTOM_KEY) self.assertEqual(aes_decrypt(encrypted, key=self.CUSTOM_KEY), self.PLAIN_TEXT) def test_decrypt(self): """Testing decrypt (deprecated)""" # The encrypted value was made with PyCrypto, to help with # compatibility testing from older installs. encrypted = ( b'\xfb\xdc\xb5h\x15\xa1\xb2\xdc\xec\xf1\x14\xa9\xc6\xab\xb2J\x10' b'\'\xd4\xf6&\xd4k9\x82\xf6\xb5\x8bmu\xc8E\x9c\xac\xc5\x04@B' ) with warnings.catch_warnings(record=True) as w: self.assertEqual(decrypt(encrypted), self.PLAIN_TEXT) self.assertEqual( unicode(w[0].message), 'decrypt() is deprecated. Use aes_decrypt() instead.') def test_encrypt(self): """Testing encrypt (deprecated)""" with warnings.catch_warnings(record=True) as w: # The encrypted value will change every time, since the iv changes, # so we can't compare a direct value. Instead, we need to ensure # that we can decrypt what we encrypt. self.assertEqual(aes_decrypt(encrypt(self.PLAIN_TEXT)), self.PLAIN_TEXT) self.assertEqual( unicode(w[0].message), 'encrypt() is deprecated. Use aes_encrypt() instead.') def test_decrypt_password(self): """Testing decrypt_password""" # The encrypted value was made with PyCrypto, to help with # compatibility testing from older installs. encrypted = b'AjsUGevO3UiVH7iN3zO9vxvqr5X5ozuAbOUByTATsitkhsih1Zc=' self.assertEqual(decrypt_password(encrypted), self.PLAIN_TEXT) def test_decrypt_password_with_custom_key(self): """Testing decrypt_password with custom key""" # The encrypted value was made with PyCrypto, to help with # compatibility testing from older installs. encrypted = b'/pOO3VWHRXd1ZAeHZo8MBGQsNClD4lS7XK9WAydt8zW/ob+e63E=' self.assertEqual(decrypt_password(encrypted, key=self.CUSTOM_KEY), self.PLAIN_TEXT) def test_encrypt_password(self): """Testing encrypt_password""" # The encrypted value will change every time, since the iv changes, # so we can't compare a direct value. Instead, we need to ensure that # we can decrypt what we encrypt. self.assertEqual( decrypt_password(encrypt_password(self.PLAIN_TEXT)), self.PLAIN_TEXT) def test_encrypt_password_with_custom_key(self): """Testing encrypt_password with custom key""" # The encrypted value will change every time, since the iv changes, # so we can't compare a direct value. Instead, we need to ensure that # we can decrypt what we encrypt. encrypted = encrypt_password(self.PLAIN_TEXT, key=self.CUSTOM_KEY) self.assertEqual(decrypt_password(encrypted, key=self.CUSTOM_KEY), self.PLAIN_TEXT) def test_get_default_aes_encryption_key(self): """Testing get_default_aes_encryption_key""" self.assertEqual(get_default_aes_encryption_key(), 'abcdefghijklmnop')
{'content_hash': '76e631998787d8dcf12cb0be5d983eb4', 'timestamp': '', 'source': 'github', 'line_count': 130, 'max_line_length': 79, 'avg_line_length': 43.784615384615385, 'alnum_prop': 0.6101546029515109, 'repo_name': 'brennie/reviewboard', 'id': '2a1600fa4f8524342799b85b9fcba4f509204b6f', 'size': '5692', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'reviewboard/scmtools/tests/test_crypto_utils.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '247208'}, {'name': 'HTML', 'bytes': '204351'}, {'name': 'JavaScript', 'bytes': '2557855'}, {'name': 'Python', 'bytes': '5241630'}, {'name': 'Shell', 'bytes': '20225'}]}
package org.apache.axis2.jaxws.api; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamException; import javax.xml.ws.WebServiceException; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.impl.MTOMXMLStreamWriter; import org.apache.axis2.Constants; import org.apache.axis2.jaxws.core.MessageContext; import org.apache.axis2.jaxws.message.Message; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Value of the Constants.JAXWS_MESSAGE_ACCESSOR property * Allows a user to gain access to certain Message information * that are not exposed by the Message on the * javax.xml.ws.handler.MessageContext * * The MessageAccessor is created with MessageAccessorFactory. * This allows embedding software to extend the MessageAccessor */ public class MessageAccessor { private static final Log log = LogFactory.getLog(MessageAccessor.class); private MessageContext mc; MessageAccessor(MessageContext mc) { super(); this.mc = mc; } /** * @return message as String */ public String getMessageAsString() { if (log.isDebugEnabled()) { log.debug("Enter MessageAccessor"); } Message msg = mc.getMessage(); String text = null; if (msg != null) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); OMOutputFormat format = new OMOutputFormat(); String charSetEncoding = (String) mc.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING); charSetEncoding = (charSetEncoding == null) ? "UTF-8" : charSetEncoding; format.setCharSetEncoding(charSetEncoding); MTOMXMLStreamWriter writer = new MTOMXMLStreamWriter(baos, format); msg.outputTo(writer, false); writer.flush(); text = baos.toString(charSetEncoding); } catch (Throwable t) { if (log.isDebugEnabled()) { log.debug("Cannot access message as string", t); } text = null; } } if (log.isDebugEnabled()) { log.debug("Exit MessageAccessor"); } return text; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return getMessageAsString(); } }
{'content_hash': 'ca15d789eed1588935eb0ba7183df887', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 113, 'avg_line_length': 34.25974025974026, 'alnum_prop': 0.623199393479909, 'repo_name': 'arunasujith/wso2-axis2', 'id': '42a7736cfb313930436ad0aec398512d6bb56a6f', 'size': '3456', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'modules/jaxws/src/org/apache/axis2/jaxws/api/MessageAccessor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '21836'}, {'name': 'CSS', 'bytes': '7295'}, {'name': 'GAP', 'bytes': '21127'}, {'name': 'HTML', 'bytes': '30579'}, {'name': 'Java', 'bytes': '20894248'}, {'name': 'JavaScript', 'bytes': '827'}, {'name': 'Shell', 'bytes': '17988'}, {'name': 'XSLT', 'bytes': '1449269'}]}
namespace Tekconf.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<Tekconf.Data.Entities.ConferenceContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Tekconf.Data.Entities.ConferenceContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
{'content_hash': 'ee150fd7f8498b4de65a4251cad27123', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 108, 'avg_line_length': 32.96774193548387, 'alnum_prop': 0.5645792563600783, 'repo_name': 'tekconf/tekconfauth', 'id': 'c026887b99ec21ee304501901bce1612911bbfe7', 'size': '1022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Tekconf.Data/Migrations/Configuration.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '214'}, {'name': 'C#', 'bytes': '67938'}, {'name': 'CSS', 'bytes': '513'}, {'name': 'HTML', 'bytes': '5302'}, {'name': 'JavaScript', 'bytes': '10918'}]}
using System; using SharpDX.Mathematics.Interop; using System.Runtime.InteropServices; namespace SharpDX.DirectWrite { public partial class GdiInterop { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public class LogFont { public int lfHeight; public int lfWidth; public int lfEscapement; public int lfOrientation; public int lfWeight; public byte lfItalic; public byte lfUnderline; public byte lfStrikeOut; public byte lfCharSet; public byte lfOutPrecision; public byte lfClipPrecision; public byte lfQuality; public byte lfPitchAndFamily; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] public string lfFaceName; } /// <summary> /// Creates a font object that matches the properties specified by the LOGFONT structure. /// </summary> /// <param name="logFont">A structure containing a GDI-compatible font description. </param> /// <returns>a reference to a newly created <see cref="SharpDX.DirectWrite.Font"/>. </returns> /// <unmanaged>HRESULT IDWriteGdiInterop::CreateFontFromLOGFONT([In] const LOGFONTW* logFont,[Out] IDWriteFont** font)</unmanaged> public Font FromLogFont(object logFont) { unsafe { int sizeOfLogFont = Marshal.SizeOf(logFont); byte* nativeLogFont = stackalloc byte[sizeOfLogFont]; Marshal.StructureToPtr(logFont, new IntPtr(nativeLogFont), false); Font font; CreateFontFromLOGFONT(new IntPtr(nativeLogFont), out font); return font; } } /// <summary> /// Initializes a LOGFONT structure based on the GDI-compatible properties of the specified font. /// </summary> /// <remarks> /// The conversion to a LOGFONT by using ConvertFontToLOGFONT operates at the logical font level and does not guarantee that it will map to a specific physical font. It is not guaranteed that GDI will select the same physical font for displaying text formatted by a LOGFONT as the <see cref="SharpDX.DirectWrite.Font"/> object that was converted. /// </remarks> /// <param name="font">An <see cref="SharpDX.DirectWrite.Font"/> object to be converted into a GDI-compatible LOGFONT structure. </param> /// <param name="logFont">When this method returns, contains a structure that receives a GDI-compatible font description. </param> /// <returns> TRUE if the specified font object is part of the system font collection; otherwise, FALSE. </returns> /// <unmanaged>HRESULT IDWriteGdiInterop::ConvertFontToLOGFONT([None] IDWriteFont* font,[In] LOGFONTW* logFont,[Out] BOOL* isSystemFont)</unmanaged> public bool ToLogFont(Font font, object logFont) { unsafe { int sizeOfLogFont = Marshal.SizeOf(logFont); byte* nativeLogFont = stackalloc byte[sizeOfLogFont]; RawBool isSystemFont; ConvertFontToLOGFONT(font, new IntPtr(nativeLogFont), out isSystemFont); Marshal.PtrToStructure(new IntPtr(nativeLogFont), logFont); return isSystemFont; } } } }
{'content_hash': 'd68bb99dc06271f6dd24027f08c0af67', 'timestamp': '', 'source': 'github', 'line_count': 72, 'max_line_length': 358, 'avg_line_length': 48.263888888888886, 'alnum_prop': 0.6241726618705036, 'repo_name': 'weltkante/SharpDX', 'id': '549bd7d5622acc2b09c3a521728418b3c126e2d4', 'size': '4606', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'Source/SharpDX.Direct2D1/DirectWrite/GdiInterop.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '3277'}, {'name': 'C', 'bytes': '2259871'}, {'name': 'C#', 'bytes': '11540136'}, {'name': 'C++', 'bytes': '6540722'}, {'name': 'Groff', 'bytes': '15315'}, {'name': 'HTML', 'bytes': '13912'}, {'name': 'PowerShell', 'bytes': '2056'}]}
<?php /** * Class generated by the backend to respond to DELETE requests on a resource. * * If a {@link ezcWebdavBackend} receives an instance of {@link * ezcWebdavDeleteRequest} it might react with an instance of {@link * ezcWebdavDeleteResponse} or with producing an error. * * @version 1.1.4 * @package Webdav */ class ezcWebdavDeleteResponse extends ezcWebdavResponse { /** * Creates a new response object. * * @return void */ public function __construct() { parent::__construct( ezcWebdavResponse::STATUS_204 ); } } ?>
{'content_hash': '7d9f62f3b7fae03d73fd7033fcb7c216', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 78, 'avg_line_length': 22.307692307692307, 'alnum_prop': 0.6637931034482759, 'repo_name': 'faclib/ezcomponents', 'id': 'e925c2b4e130510c2aee32b8f0961fed31adbfef', 'size': '813', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'Webdav/src/responses/delete.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '4095'}, {'name': 'DOT', 'bytes': '30400'}, {'name': 'Erlang', 'bytes': '2224'}, {'name': 'JavaScript', 'bytes': '12499'}, {'name': 'PHP', 'bytes': '24328435'}, {'name': 'Python', 'bytes': '54500'}, {'name': 'Shell', 'bytes': '403'}]}
/* This class manages the database access. If the database does not exist then it is created Need to pass the database location, username, and password */ package millerpintgame; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * * @author David Crosbie */ public class DatabaseCreate { public int DatabaseCreate() { return 0; } // Pre - Must supply: // databaseName = "jdbc.mysql://localhost/MillerLiteGame"; // databaseUser = "admin"; // databasePassword = "password // Function returns 0 if it creates successfully // It returns an error code if there is an SQL failure public static int DatabaseCreate(String databaseName, String databaseUser, String databasePassword ) throws SQLException, ClassNotFoundException { try { // Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); System.out.println("Database loaded"); // Connect to an existing database Connection connection = DriverManager.getConnection (databaseName,databaseUser,databasePassword ); System.out.println("Database connected"); // Create a statement Statement statement = connection.createStatement(); // Now we have a database connected and we can use connection to ferry commands // Now create the schema called 'games' String sqlCommand; sqlCommand = " CREATE SCHEMA IF NOT EXISTS 'games' " + "DEFAULT CHARACTER SET utf8 ;\n" + "USE `game` ;"; statement.executeUpdate(sqlCommand); System.out.println("Database schema created successfully..."); // Now create the GAMES table in the 'games' schema // Each game has a state. GAME_STATE // State 0 is created but not started // State 10 is playing // State 20 is ended sqlCommand = " CREATE TABLE IF NOT EXISTS 'games', 'GAMES' {" + "`idGAME` INT UNSIGNED NOT NULL AUTO_INCREMENT," + "`GAME_NAME` VARCHAR(45) NULL DEFAULT '\\\"Standard\\\"'," + "`GAME_STATE` INT UNSIGNED NOT NULL," + "PRIMARY KEY ('idGAME'), ENGINE = InnoDB "; statement.executeUpdate(sqlCommand); System.out.println("Database table GAMES created"); // Create the PLAYERS table // Each player has a Name that must be unique sqlCommand = " CREATE TABLE IF NOT EXISTS 'games', 'PLAYERS' {" + "`idPLAYER` INT UNSIGNED NOT NULL AUTO_INCREMENT," + "`PLAYER_NAME` VARCHAR(45) NULL DEFAULT '\\\"John Doe\\\"'," + "`idRULES` INT UNSIGNED NOT NULL ," + "PRIMARY KEY ('idPLAYER')," + "ENGINE = InnoDB "; statement.executeUpdate(sqlCommand); System.out.println("Database table GAMES created"); // Now create a ROUNDS table // This table stores the round and the associated scores // There is a unique ID for each round // The Foreign Keys are the idGAME and the idPLAYER sqlCommand = " CREATE TABLE IF NOT EXISTS 'games', 'ROUNDS' {" + "`idROUND` INT UNSIGNED NOT NULL AUTO_INCREMENT," + " INT UNSIGNED NOT NULL," + "`idPLAYER` INT UNSIGNED NOT NULL," + "`SCORE` INT UNSIGNED NOT NULL," + "FOREIGN KEY {`idGAME`) REFERENCES " + "PRIMARY KEY ('idROUND'), ENGINE = InnoDB "; statement.executeUpdate(sqlCommand); System.out.println("Database table ROUNDS created"); // The RULES table specifies the rules for that particular game sqlCommand = " CREATE TABLE IF NOT EXISTS 'games', 'RULES' {" + "`idRULES` INT UNSIGNED NOT NULL AUTO_INCREMENT," + "PRIMARY KEY ('idRULES'), ENGINE = InnoDB "; statement.executeUpdate(sqlCommand); System.out.println("Database table RULES created"); // The LABELS database stores text for the application // in various languages // I think the primary key is idLABEL plus LANGUAGE sqlCommand = " CREATE TABLE IF NOT EXISTS 'games', 'LABELS' {" + "`idLABEL` INT UNSIGNED NOT NULL," + "`LANGUAGE` VARCHAR(45) NULL DEFAULT '\\\"English\\\"'," + "`LABEL` VARCHAR(128) NULL DEFAULT '\\\"Empty\\\"'," + "PRIMARY KEY ('idLABEL'), ENGINE = InnoDB "; statement.executeUpdate(sqlCommand); System.out.println("Database table LABELS created"); /* FOREIGN KEY (`idROUNDS`) REFERENCES `mydb`.`Games` (`Game_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION) */ statement.close(); connection.close(); return 0; } // end of try catch (SQLException ex) { int databaseError = ex.getErrorCode(); return (databaseError); } finally { // nothing } // end of finally } // end of throw } // end of class
{'content_hash': 'a8aa1be05d95e8f2cbf57286e4041074', 'timestamp': '', 'source': 'github', 'line_count': 150, 'max_line_length': 106, 'avg_line_length': 38.873333333333335, 'alnum_prop': 0.521865889212828, 'repo_name': 'dcrosbie/BHCC_Game', 'id': '2e86a8c2db89027bb096bdb835510a905f60409a', 'size': '5831', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'MillerPintGame/src/millerpintgame/DatabaseCreate.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '188'}, {'name': 'Java', 'bytes': '25132'}]}
<button title="Enabling presentation mode will change the hovering effect so that it simulates a flashlight"> <span>Presentation mode</span> <i class="presentation-mode-icon fa fa-television"></i> <mat-slide-toggle [checked]="isPresentationModeEnabled$ | async" (change)="setPresentationModeEnabled($event)" [title]="(isPresentationModeEnabled$ | async) ? 'Disable presentation mode' : 'Enable presentation mode'" > </mat-slide-toggle> </button>
{'content_hash': '95031dd63c33adec2b21d4f23969ed1b', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 109, 'avg_line_length': 38.25, 'alnum_prop': 0.7472766884531591, 'repo_name': 'MaibornWolff/codecharta', 'id': 'd75a3bde88a313eb4e6f8025875f586bcfc22e2e', 'size': '459', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'visualization/app/codeCharta/ui/toolBar/presentationModeButton/presentationModeButton.component.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Dockerfile', 'bytes': '1716'}, {'name': 'GLSL', 'bytes': '49972'}, {'name': 'HTML', 'bytes': '65867'}, {'name': 'Java', 'bytes': '9555'}, {'name': 'JavaScript', 'bytes': '9558'}, {'name': 'Kotlin', 'bytes': '780683'}, {'name': 'Python', 'bytes': '6692'}, {'name': 'Ruby', 'bytes': '474'}, {'name': 'SCSS', 'bytes': '39045'}, {'name': 'Shell', 'bytes': '10656'}, {'name': 'TypeScript', 'bytes': '1497292'}]}
<?php /** * PHPExcel_Worksheet_ColumnDimension * * @category PHPExcel * @package PHPExcel_Worksheet * @copyright Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Worksheet_ColumnDimension { /** * Column index * * @var int */ private $_columnIndex; /** * Column width * * When this is set to a negative value, the column width should be ignored by IWriter * * @var double */ private $_width; /** * Auto size? * * @var bool */ private $_autoSize; /** * Visible? * * @var bool */ private $_visible; /** * Outline level * * @var int */ private $_outlineLevel = 0; /** * Collapsed * * @var bool */ private $_collapsed; /** * Create a new PHPExcel_Worksheet_RowDimension * * @param string $pIndex Character column index */ public function __construct($pIndex = 'A') { // Initialise values $this->_columnIndex = $pIndex; $this->_width = -1; $this->_autoSize = false; $this->_visible = true; $this->_outlineLevel = 0; $this->_collapsed = false; } /** * Get ColumnIndex * * @return string */ public function getColumnIndex() { return $this->_columnIndex; } /** * Set ColumnIndex * * @param string $pValue */ public function setColumnIndex($pValue) { $this->_columnIndex = $pValue; } /** * Get Width * * @return double */ public function getWidth() { return $this->_width; } /** * Set Width * * @param double $pValue */ public function setWidth($pValue = -1) { $this->_width = $pValue; } /** * Get Auto Size * * @return bool */ public function getAutoSize() { return $this->_autoSize; } /** * Set Auto Size * * @param bool $pValue */ public function setAutoSize($pValue = false) { $this->_autoSize = $pValue; } /** * Get Visible * * @return bool */ public function getVisible() { return $this->_visible; } /** * Set Visible * * @param bool $pValue */ public function setVisible($pValue = true) { $this->_visible = $pValue; } /** * Get Outline Level * * @return int */ public function getOutlineLevel() { return $this->_outlineLevel; } /** * Set Outline Level * * Value must be between 0 and 7 * * @param int $pValue * @throws Exception */ public function setOutlineLevel($pValue) { if ($pValue < 0 || $pValue > 7) { throw new Exception("Outline level must range between 0 and 7."); } $this->_outlineLevel = $pValue; } /** * Get Collapsed * * @return bool */ public function getCollapsed() { return $this->_collapsed; } /** * Set Collapsed * * @param bool $pValue */ public function setCollapsed($pValue = true) { $this->_collapsed = $pValue; } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
{'content_hash': '677129abcbe414dbb594500a20d9f207', 'timestamp': '', 'source': 'github', 'line_count': 202, 'max_line_length': 87, 'avg_line_length': 17.297029702970296, 'alnum_prop': 0.5151688609044076, 'repo_name': 'ALTELMA/asset_manager', 'id': 'd5beaed1875d42615c9e2b61f7913e9e02d3c0c0', 'size': '4540', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'application/libraries/PHPExcel/branches/v1.5.5/Classes/PHPExcel/Worksheet/ColumnDimension.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '209'}, {'name': 'Batchfile', 'bytes': '7424'}, {'name': 'CSS', 'bytes': '6892'}, {'name': 'HTML', 'bytes': '1547796'}, {'name': 'JavaScript', 'bytes': '11472'}, {'name': 'PHP', 'bytes': '79520483'}]}
"""Core function for the plotting tools""" import pandas as pd __all__ = ["VizInput2D"] class VizInputSquare(object): def __init__(self, x, verbose=False): self.verbose = verbose self.df = pd.DataFrame(x) class VizInput2D(object): def __init__(self, x, y=None, verbose=False): self.verbose = verbose self.xy_names = ['x', 'y'] if isinstance(x, pd.DataFrame) is True: self.df = x.copy() columns = list(self.df.columns) columns[0] = 'x' columns[1] = 'y' self.xy_names = self.df.columns[0:2] self.df.columns = columns elif y is None: # could be a list of lists, a pandas-compatible dictionary self.df = pd.DataFrame(x) if self.df.shape[1] != 2: if self.df.shape[0] == 2: print("warning transposing data") self.df = self.df.transpose() elif x is not None and y is not None: self.df = pd.DataFrame({'x':x, 'y':y}) else: raise ValueError('not a dataframe or list of items or dictionary.')
{'content_hash': 'c440da5e5684866b751ee2ff1de68ab7', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 79, 'avg_line_length': 28.85, 'alnum_prop': 0.5311958405545927, 'repo_name': 'biokit/biokit', 'id': 'c8513ac858a5bd2c0758d83acc49a67c5a9b059d', 'size': '1154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'biokit/viz/core.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '1476'}, {'name': 'Jupyter Notebook', 'bytes': '3236555'}, {'name': 'Python', 'bytes': '250583'}]}
% DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-login - Log in to a Docker registry. # SYNOPSIS **docker login** [**--help**] [**-p**|**--password**[=*PASSWORD*]] [**-u**|**--username**[=*USERNAME*]] [SERVER] # DESCRIPTION Log in to a Docker Registry located on the specified `SERVER`. You can specify a URL or a `hostname` for the `SERVER` value. If you do not specify a `SERVER`, the command uses Docker's public registry located at `https://registry-1.docker.io/` by default. To get a username/password for Docker's public registry, create an account on Docker Hub. `docker login` requires user to use `sudo` or be `root`, except when: 1. connecting to a remote daemon, such as a `docker-machine` provisioned `docker engine`. 2. user is added to the `docker` group. This will impact the security of your system; the `docker` group is `root` equivalent. See [Docker Daemon Attack Surface](https://docs.docker.com/articles/security/#docker-daemon-attack-surface) for details. You can log into any public or private repository for which you have credentials. When you log in, the command stores encoded credentials in `$HOME/.docker/config.json` on Linux or `%USERPROFILE%/.docker/config.json` on Windows. # OPTIONS **--help** Print usage statement **-p**, **--password**="" Password **-u**, **--username**="" Username # EXAMPLES ## Login to a registry on your localhost # docker login localhost:8080 # See also **docker-logout(1)** to log out from a Docker registry. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit <[email protected]> April 2015, updated by Mary Anthony for v2 <[email protected]> November 2015, updated by Sally O'Malley <[email protected]>
{'content_hash': 'bd7b4dd988a416208af05bac2bf74dd6', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 250, 'avg_line_length': 35.056603773584904, 'alnum_prop': 0.7255113024757804, 'repo_name': 'isotopsweden/docker-farmer', 'id': '6bb0355946cc8d6da5832e7d00b61468af9cf0af', 'size': '1858', 'binary': False, 'copies': '32', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/docker/docker/man/docker-login.1.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1666'}, {'name': 'Dockerfile', 'bytes': '550'}, {'name': 'Go', 'bytes': '17349'}, {'name': 'HTML', 'bytes': '1921'}, {'name': 'JavaScript', 'bytes': '5067'}, {'name': 'Makefile', 'bytes': '50'}]}
license: > Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- # 嵌入 WebViews > 在您自己的專案中實現科爾多瓦 web 視圖。 * Android WebViews * WebViews iOS
{'content_hash': '9b5911ef17da33de2b6f7ffdcde46f69', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 64, 'avg_line_length': 36.28, 'alnum_prop': 0.7375964718853363, 'repo_name': 'cpsloal/cordova-docs', 'id': '46379f98f22111805ae2c77acfe0bcfcbb455c9d', 'size': '949', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'docs/zh/3.1.0/guide/hybrid/webviews/index.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5116'}, {'name': 'CSS', 'bytes': '11129'}, {'name': 'HTML', 'bytes': '113105'}, {'name': 'JavaScript', 'bytes': '69082'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" > <!-- This is comment number 1.--> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>hc_staff</title><script type="text/javascript" src="selfhtml.js"></script><script charset="UTF-8" type="text/javascript" src="createEvent05.js"></script><script type='text/javascript'>function loadComplete() { startTest(); }</script></head><body onload="loadComplete()"> <p> <em>EMP0001</em> <strong>Margaret Martin</strong> <code>Accountant</code> <sup>56,000</sup> <var>Female</var> <acronym title="Yes">1230 North Ave. Dallas, Texas 98551</acronym> </p> <p> <em>EMP0002</em> <strong>Martha RaynoldsThis is a CDATASection with EntityReference number 2 &amp;ent2; This is an adjacent CDATASection with a reference to a tab &amp;tab;</strong> <code>Secretary</code> <sup>35,000</sup> <var>Female</var> <acronym title="Yes" class="Yes">&beta; Dallas, &gamma; 98554</acronym> </p> <p> <em>EMP0003</em> <strong>Roger Jones</strong> <code>Department Manager</code> <sup>100,000</sup> <var>&delta;</var> <acronym title="Yes" class="No">PO Box 27 Irving, texas 98553</acronym> </p> <p> <em>EMP0004</em> <strong>Jeny Oconnor</strong> <code>Personnel Director</code> <sup>95,000</sup> <var>Female</var> <acronym title="Yes" class="Y&alpha;">27 South Road. Dallas, Texas 98556</acronym> </p> <p> <em>EMP0005</em> <strong>Robert Myers</strong> <code>Computer Specialist</code> <sup>90,000</sup> <var>male</var> <acronym title="Yes">1821 Nordic. Road, Irving Texas 98558</acronym> </p> </body></html>
{'content_hash': '7ed11d54388c2ae5c957e45cbdeb13d6', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 356, 'avg_line_length': 34.958333333333336, 'alnum_prop': 0.6728247914183552, 'repo_name': 'highweb-project/highweb-webcl-html5spec', 'id': '2c172d4456eacc12efe24be740a8f9f8fac9456a', 'size': '1678', 'binary': False, 'copies': '73', 'ref': 'refs/heads/highweb-20160310', 'path': 'third_party/WebKit/LayoutTests/dom/html/level2/events/createEvent05.html', 'mode': '33188', 'license': 'bsd-3-clause', '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. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.TodoComments; namespace Microsoft.CodeAnalysis.Editor { /// <summary> /// Returns Roslyn todo list from the workspace. /// </summary> internal interface ITodoListProvider { /// <summary> /// An event that is raised when the todo list has changed. /// /// When an event handler is newly added, this event will fire for the currently available todo items and then /// afterward for any changes since. /// </summary> event EventHandler<TodoItemsUpdatedArgs> TodoListUpdated; ImmutableArray<TodoCommentData> GetTodoItems(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); } }
{'content_hash': 'e231f0b82e82da153fbdacc08fc8928a', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 134, 'avg_line_length': 35.275862068965516, 'alnum_prop': 0.7126099706744868, 'repo_name': 'AlekseyTs/roslyn', 'id': '51ff672c617805595850d5ed59f4efd5bb968358', 'size': '1025', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'src/EditorFeatures/Core/Implementation/TodoComment/ITodoListProvider.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '257760'}, {'name': 'Batchfile', 'bytes': '8025'}, {'name': 'C#', 'bytes': '143434676'}, {'name': 'C++', 'bytes': '5602'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2450'}, {'name': 'F#', 'bytes': '549'}, {'name': 'PowerShell', 'bytes': '253312'}, {'name': 'Shell', 'bytes': '96510'}, {'name': 'Visual Basic .NET', 'bytes': '72293305'}]}
// // ViewController.m // teslaapitest // // Created by tflack on 5/1/14. // Copyright (c) 2014 Idynomite Media. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize textBox; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. /* NSHTTPCookieStorage * sharedCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; NSArray * cookies = [sharedCookieStorage cookies]; for (NSHTTPCookie * cookie in cookies){ NSLog(@"%@",cookie.domain); NSLog(@"deleting"); [sharedCookieStorage deleteCookie:cookie]; } */ tApi = [[TeslaApi alloc] init]; [tApi doLoginWithUserName:@"TESLAEMAIL" andPassword:@"TESLAPASSWORD" andCompletionBlock:^(NSArray *vehicles) { NSLog(@"Logged In %@",vehicles); } andErrorBlock:^(NSError *error) { NSLog(@"Log In Error %@",error); }]; } - (IBAction)chargeStateTouched:(id)sender { [tApi chargeStateWithCompletionBlock:^(NSArray *chargeInfo) { NSLog(@"Charge Info %@",chargeInfo); [self updateTextBox:chargeInfo]; } andErrorBlock:^(NSError *error) { NSLog(@"Error Getting Charge State %@",error); } ]; } - (IBAction)vehicleListTouched:(id)sender { [tApi listVehiclesWithCompletionBlock:^(NSArray *vehicles) { NSLog(@"VEHICLE: %@",vehicles); [self updateTextBox:vehicles]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)vehicleStateTouched:(id)sender { [tApi vehicleStateWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)vehicleStatusTouched:(id)sender { [tApi statusWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)climateStateTouched:(id)sender { [tApi climateStateWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)guiSettingsTouched:(id)sender { [tApi guiSettingsWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)openChargePortTouched:(id)sender { [tApi chargePortDoorOpenWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)flashLightsTouched:(id)sender { [tApi flashLightsWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)honkHornTouched:(id)sender { [tApi honkHornWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)doorLockTouched:(id)sender { [tApi doorLockWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)doorUnlockTouched:(id)sender { [tApi doorUnLockWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)chargeStandardTouched:(id)sender { [tApi chargeStandardWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)startChargeTouched:(id)sender { [tApi chargeStartWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (IBAction)stopChargeTouched:(id)sender { [tApi chargeStopWithCompletionBlock:^(NSArray *data) { NSLog(@"Data: %@",data); [self updateTextBox:data]; } andErrorBlock:^(NSError *error) { NSLog(@"ERROR: %@",error); }]; } - (void) updateTextBox:(NSArray *)data { NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil]; NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; [textBox setText:jsonString]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{'content_hash': 'ad38bbdf5e6613024992c0af67b22b1f', 'timestamp': '', 'source': 'github', 'line_count': 183, 'max_line_length': 111, 'avg_line_length': 27.901639344262296, 'alnum_prop': 0.6249510379945162, 'repo_name': 'tflack/tesla-api-objectivec', 'id': '3cced8162ce2948f670a01011e5a6b01ead81d70', 'size': '5106', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'teslaapitest/ViewController.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '26730'}, {'name': 'Ruby', 'bytes': '661'}]}
struct SCOPED_LOCKABLE LockAnnotation { template <typename Mutex> explicit LockAnnotation(Mutex& mutex) EXCLUSIVE_LOCK_FUNCTION(mutex) { } ~LockAnnotation() UNLOCK_FUNCTION() {} }; #endif // BITCOIN_THREADSAFETY_H
{'content_hash': 'a628b20dda2360725d03ba7cf2f6dfb0', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 72, 'avg_line_length': 23.5, 'alnum_prop': 0.7063829787234043, 'repo_name': 'chaincoin/chaincoin', 'id': '33acddc65cf462c6de5fc84a9301ddfce16993de', 'size': '2959', 'binary': False, 'copies': '10', 'ref': 'refs/heads/0.18', 'path': 'src/threadsafety.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '28453'}, {'name': 'C', 'bytes': '782437'}, {'name': 'C++', 'bytes': '7493134'}, {'name': 'HTML', 'bytes': '21860'}, {'name': 'Java', 'bytes': '30290'}, {'name': 'M4', 'bytes': '199073'}, {'name': 'Makefile', 'bytes': '123254'}, {'name': 'Objective-C', 'bytes': '3901'}, {'name': 'Objective-C++', 'bytes': '5382'}, {'name': 'Python', 'bytes': '2532944'}, {'name': 'QMake', 'bytes': '792'}, {'name': 'Shell', 'bytes': '94132'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>math-classes: 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.7.0 / math-classes - 1.0.4</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> math-classes <small> 1.0.4 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-02-25 20:18:33 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-02-25 20:18:33 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.11 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.7.0 Formal proof management system. num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.09.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.09.0 Official release 4.09.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/math-classes/&quot; doc: &quot;https://github.com/math-classes/&quot; authors: [ &quot;Eelis van der Weegen&quot; &quot;Bas Spitters&quot; &quot;Robbert Krebbers&quot; ] license: &quot;Public Domain&quot; build: [ [ &quot;./configure.sh&quot; ] [ make &quot;-j%{jobs}%&quot; ] ] install: [ make &quot;install&quot; ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;} ] tags: [ &quot;logpath:MathClasses&quot; ] synopsis: &quot;A library of abstract interfaces for mathematical structures in Coq&quot; url { src: &quot;https://github.com/math-classes/math-classes/archive/9853988446ab19ee0618181f8da1d7dbdebcc45f.zip&quot; checksum: &quot;md5=b2293d8e429ab1174160f68c1cba12d2&quot; } </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-math-classes.1.0.4 coq.8.7.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.7.0). The following dependencies couldn&#39;t be met: - coq-math-classes -&gt; coq &lt; 8.6~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; 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-math-classes.1.0.4</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"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </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': '2697a4a56c87bca26409685b00dc7a7a', 'timestamp': '', 'source': 'github', 'line_count': 168, 'max_line_length': 157, 'avg_line_length': 39.00595238095238, 'alnum_prop': 0.5276972379063024, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'af150377c677c413a363c3ef9c3331bc987ea2ef', 'size': '6555', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.09.0-2.0.5/released/8.7.0/math-classes/1.0.4.html', 'mode': '33188', 'license': 'mit', 'language': []}
import { ControlValueAccessor } from './control_value_accessor'; import { AbstractControlDirective } from './abstract_control_directive'; /** * An abstract class that all control directive extend. * * It binds a {@link Control} object to a DOM element. */ export declare class NgControl extends AbstractControlDirective { name: string; valueAccessor: ControlValueAccessor; validator: Function; path: List<string>; viewToModelUpdate(newValue: any): void; }
{'content_hash': '576a75cf3f88432794ed9bf854bc1d23', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 72, 'avg_line_length': 35.285714285714285, 'alnum_prop': 0.7165991902834008, 'repo_name': 'anttisirkiafuturice/angular2todo', 'id': 'ce1e716a4d145638bad225b5ed189628c3311058', 'size': '494', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'node_modules/angular2/es6/dev/src/forms/directives/ng_control.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1316'}, {'name': 'HTML', 'bytes': '3663'}, {'name': 'JavaScript', 'bytes': '1266008'}, {'name': 'TypeScript', 'bytes': '1956'}]}
#include "defs.h" #include "elf-bfd.h" #include "infcall.h" #include "inferior.h" #include "gdbcore.h" #include "objfiles.h" #include "symfile.h" #include "cli/cli-decode.h" #include "gdb_assert.h" static char *default_gcore_target (void); static enum bfd_architecture default_gcore_arch (void); static unsigned long default_gcore_mach (void); static int gcore_memory_sections (bfd *); /* Generate a core file from the inferior process. */ static void gcore_command (char *args, int from_tty) { struct cleanup *old_chain; char *corefilename, corefilename_buffer[40]; asection *note_sec = NULL; bfd *obfd; void *note_data = NULL; int note_size = 0; /* No use generating a corefile without a target process. */ if (!target_has_execution) noprocess (); if (args && *args) corefilename = args; else { /* Default corefile name is "core.PID". */ sprintf (corefilename_buffer, "core.%d", PIDGET (inferior_ptid)); corefilename = corefilename_buffer; } if (info_verbose) fprintf_filtered (gdb_stdout, "Opening corefile '%s' for output.\n", corefilename); /* Open the output file. */ obfd = bfd_openw (corefilename, default_gcore_target ()); if (!obfd) error ("Failed to open '%s' for output.", corefilename); /* Need a cleanup that will close the file (FIXME: delete it?). */ old_chain = make_cleanup_bfd_close (obfd); bfd_set_format (obfd, bfd_core); bfd_set_arch_mach (obfd, default_gcore_arch (), default_gcore_mach ()); /* An external target method must build the notes section. */ note_data = target_make_corefile_notes (obfd, &note_size); /* Create the note section. */ if (note_data != NULL && note_size != 0) { note_sec = bfd_make_section_anyway (obfd, "note0"); if (note_sec == NULL) error ("Failed to create 'note' section for corefile: %s", bfd_errmsg (bfd_get_error ())); bfd_set_section_vma (obfd, note_sec, 0); bfd_set_section_flags (obfd, note_sec, SEC_HAS_CONTENTS | SEC_READONLY | SEC_ALLOC); bfd_set_section_alignment (obfd, note_sec, 0); bfd_set_section_size (obfd, note_sec, note_size); } /* Now create the memory/load sections. */ if (gcore_memory_sections (obfd) == 0) error ("gcore: failed to get corefile memory sections from target."); /* Write out the contents of the note section. */ if (note_data != NULL && note_size != 0) { if (!bfd_set_section_contents (obfd, note_sec, note_data, 0, note_size)) warning ("writing note section (%s)", bfd_errmsg (bfd_get_error ())); } /* Succeeded. */ fprintf_filtered (gdb_stdout, "Saved corefile %s\n", corefilename); /* Clean-ups will close the output file and free malloc memory. */ do_cleanups (old_chain); return; } static unsigned long default_gcore_mach (void) { #if 1 /* See if this even matters... */ return 0; #else #ifdef TARGET_ARCHITECTURE const struct bfd_arch_info *bfdarch = TARGET_ARCHITECTURE; if (bfdarch != NULL) return bfdarch->mach; #endif /* TARGET_ARCHITECTURE */ if (exec_bfd == NULL) error ("Can't find default bfd machine type (need execfile)."); return bfd_get_mach (exec_bfd); #endif /* 1 */ } static enum bfd_architecture default_gcore_arch (void) { #ifdef TARGET_ARCHITECTURE const struct bfd_arch_info * bfdarch = TARGET_ARCHITECTURE; if (bfdarch != NULL) return bfdarch->arch; #endif if (exec_bfd == NULL) error ("Can't find bfd architecture for corefile (need execfile)."); return bfd_get_arch (exec_bfd); } static char * default_gcore_target (void) { /* FIXME: This may only work for ELF targets. */ if (exec_bfd == NULL) return NULL; else return bfd_get_target (exec_bfd); } /* Derive a reasonable stack segment by unwinding the target stack, and store its limits in *BOTTOM and *TOP. Return non-zero if successful. */ static int derive_stack_segment (bfd_vma *bottom, bfd_vma *top) { struct frame_info *fi, *tmp_fi; gdb_assert (bottom); gdb_assert (top); /* Can't succeed without stack and registers. */ if (!target_has_stack || !target_has_registers) return 0; /* Can't succeed without current frame. */ fi = get_current_frame (); if (fi == NULL) return 0; /* Save frame pointer of TOS frame. */ *top = get_frame_base (fi); /* If current stack pointer is more "inner", use that instead. */ if (INNER_THAN (read_sp (), *top)) *top = read_sp (); /* Find prev-most frame. */ while ((tmp_fi = get_prev_frame (fi)) != NULL) fi = tmp_fi; /* Save frame pointer of prev-most frame. */ *bottom = get_frame_base (fi); /* Now canonicalize their order, so that BOTTOM is a lower address (as opposed to a lower stack frame). */ if (*bottom > *top) { bfd_vma tmp_vma; tmp_vma = *top; *top = *bottom; *bottom = tmp_vma; } return 1; } /* Derive a reasonable heap segment for ABFD by looking at sbrk and the static data sections. Store its limits in *BOTTOM and *TOP. Return non-zero if successful. */ static int derive_heap_segment (bfd *abfd, bfd_vma *bottom, bfd_vma *top) { bfd_vma top_of_data_memory = 0; bfd_vma top_of_heap = 0; bfd_size_type sec_size; struct value *zero, *sbrk; bfd_vma sec_vaddr; asection *sec; gdb_assert (bottom); gdb_assert (top); /* This function depends on being able to call a function in the inferior. */ if (!target_has_execution) return 0; /* The following code assumes that the link map is arranged as follows (low to high addresses): --------------------------------- | text sections | --------------------------------- | data sections (including bss) | --------------------------------- | heap | --------------------------------- */ for (sec = abfd->sections; sec; sec = sec->next) { if (bfd_get_section_flags (abfd, sec) & SEC_DATA || strcmp (".bss", bfd_section_name (abfd, sec)) == 0) { sec_vaddr = bfd_get_section_vma (abfd, sec); sec_size = bfd_get_section_size (sec); if (sec_vaddr + sec_size > top_of_data_memory) top_of_data_memory = sec_vaddr + sec_size; } } /* Now get the top-of-heap by calling sbrk in the inferior. */ if (lookup_minimal_symbol ("sbrk", NULL, NULL) != NULL) { sbrk = find_function_in_inferior ("sbrk"); if (sbrk == NULL) return 0; } else if (lookup_minimal_symbol ("_sbrk", NULL, NULL) != NULL) { sbrk = find_function_in_inferior ("_sbrk"); if (sbrk == NULL) return 0; } else return 0; zero = value_from_longest (builtin_type_int, 0); gdb_assert (zero); sbrk = call_function_by_hand (sbrk, 1, &zero); if (sbrk == NULL) return 0; top_of_heap = value_as_long (sbrk); /* Return results. */ if (top_of_heap > top_of_data_memory) { *bottom = top_of_data_memory; *top = top_of_heap; return 1; } /* No additional heap space needs to be saved. */ return 0; } static void make_output_phdrs (bfd *obfd, asection *osec, void *ignored) { int p_flags = 0; int p_type; /* FIXME: these constants may only be applicable for ELF. */ if (strncmp (bfd_section_name (obfd, osec), "load", 4) == 0) p_type = PT_LOAD; else p_type = PT_NOTE; p_flags |= PF_R; /* Segment is readable. */ if (!(bfd_get_section_flags (obfd, osec) & SEC_READONLY)) p_flags |= PF_W; /* Segment is writable. */ if (bfd_get_section_flags (obfd, osec) & SEC_CODE) p_flags |= PF_X; /* Segment is executable. */ bfd_record_phdr (obfd, p_type, 1, p_flags, 0, 0, 0, 0, 1, &osec); } static int gcore_create_callback (CORE_ADDR vaddr, unsigned long size, int read, int write, int exec, void *data) { bfd *obfd = data; asection *osec; flagword flags = SEC_ALLOC | SEC_HAS_CONTENTS | SEC_LOAD; /* If the memory segment has no permissions set, ignore it, otherwise when we later try to access it for read/write, we'll get an error or jam the kernel. */ if (read == 0 && write == 0 && exec == 0) { if (info_verbose) { fprintf_filtered (gdb_stdout, "Ignore segment, %s bytes at 0x%s\n", paddr_d (size), paddr_nz (vaddr)); } return 0; } if (write == 0) { /* See if this region of memory lies inside a known file on disk. If so, we can avoid copying its contents by clearing SEC_LOAD. */ struct objfile *objfile; struct obj_section *objsec; ALL_OBJSECTIONS (objfile, objsec) { bfd *abfd = objfile->obfd; asection *asec = objsec->the_bfd_section; bfd_vma align = (bfd_vma) 1 << bfd_get_section_alignment (abfd, asec); bfd_vma start = objsec->addr & -align; bfd_vma end = (objsec->endaddr + align - 1) & -align; /* Match if either the entire memory region lies inside the section (i.e. a mapping covering some pages of a large segment) or the entire section lies inside the memory region (i.e. a mapping covering multiple small sections). This BFD was synthesized from reading target memory, we don't want to omit that. */ if (((vaddr >= start && vaddr + size <= end) || (start >= vaddr && end <= vaddr + size)) && !(bfd_get_file_flags (abfd) & BFD_IN_MEMORY)) { flags &= ~SEC_LOAD; goto keep; /* break out of two nested for loops */ } } keep: flags |= SEC_READONLY; } if (exec) flags |= SEC_CODE; else flags |= SEC_DATA; osec = bfd_make_section_anyway (obfd, "load"); if (osec == NULL) { warning ("Couldn't make gcore segment: %s", bfd_errmsg (bfd_get_error ())); return 1; } if (info_verbose) { fprintf_filtered (gdb_stdout, "Save segment, %s bytes at 0x%s\n", paddr_d (size), paddr_nz (vaddr)); } bfd_set_section_size (obfd, osec, size); bfd_set_section_vma (obfd, osec, vaddr); bfd_section_lma (obfd, osec) = 0; /* ??? bfd_set_section_lma? */ bfd_set_section_flags (obfd, osec, flags); return 0; } static int objfile_find_memory_regions (int (*func) (CORE_ADDR, unsigned long, int, int, int, void *), void *obfd) { /* Use objfile data to create memory sections. */ struct objfile *objfile; struct obj_section *objsec; bfd_vma temp_bottom, temp_top; /* Call callback function for each objfile section. */ ALL_OBJSECTIONS (objfile, objsec) { bfd *ibfd = objfile->obfd; asection *isec = objsec->the_bfd_section; flagword flags = bfd_get_section_flags (ibfd, isec); int ret; if ((flags & SEC_ALLOC) || (flags & SEC_LOAD)) { int size = bfd_section_size (ibfd, isec); int ret; ret = (*func) (objsec->addr, bfd_section_size (ibfd, isec), 1, /* All sections will be readable. */ (flags & SEC_READONLY) == 0, /* Writable. */ (flags & SEC_CODE) != 0, /* Executable. */ obfd); if (ret != 0) return ret; } } /* Make a stack segment. */ if (derive_stack_segment (&temp_bottom, &temp_top)) (*func) (temp_bottom, temp_top - temp_bottom, 1, /* Stack section will be readable. */ 1, /* Stack section will be writable. */ 0, /* Stack section will not be executable. */ obfd); /* Make a heap segment. */ if (derive_heap_segment (exec_bfd, &temp_bottom, &temp_top)) (*func) (temp_bottom, temp_top - temp_bottom, 1, /* Heap section will be readable. */ 1, /* Heap section will be writable. */ 0, /* Heap section will not be executable. */ obfd); return 0; } static void gcore_copy_callback (bfd *obfd, asection *osec, void *ignored) { bfd_size_type size = bfd_section_size (obfd, osec); struct cleanup *old_chain = NULL; void *memhunk; /* Read-only sections are marked; we don't have to copy their contents. */ if ((bfd_get_section_flags (obfd, osec) & SEC_LOAD) == 0) return; /* Only interested in "load" sections. */ if (strncmp ("load", bfd_section_name (obfd, osec), 4) != 0) return; memhunk = xmalloc (size); /* ??? This is crap since xmalloc should never return NULL. */ if (memhunk == NULL) error ("Not enough memory to create corefile."); old_chain = make_cleanup (xfree, memhunk); if (target_read_memory (bfd_section_vma (obfd, osec), memhunk, size) != 0) warning ("Memory read failed for corefile section, %s bytes at 0x%s\n", paddr_d (size), paddr (bfd_section_vma (obfd, osec))); if (!bfd_set_section_contents (obfd, osec, memhunk, 0, size)) warning ("Failed to write corefile contents (%s).", bfd_errmsg (bfd_get_error ())); do_cleanups (old_chain); /* Frees MEMHUNK. */ } static int gcore_memory_sections (bfd *obfd) { if (target_find_memory_regions (gcore_create_callback, obfd) != 0) return 0; /* FIXME: error return/msg? */ /* Record phdrs for section-to-segment mapping. */ bfd_map_over_sections (obfd, make_output_phdrs, NULL); /* Copy memory region contents. */ bfd_map_over_sections (obfd, gcore_copy_callback, NULL); return 1; } void _initialize_gcore (void) { add_com ("generate-core-file", class_files, gcore_command, "\ Save a core file with the current state of the debugged process.\n\ Argument is optional filename. Default filename is 'core.<process_id>'."); add_com_alias ("gcore", "generate-core-file", class_files, 1); exec_set_find_memory_regions (objfile_find_memory_regions); }
{'content_hash': '375bf30f5397d314aee9374dfeed51ff', 'timestamp': '', 'source': 'github', 'line_count': 482, 'max_line_length': 78, 'avg_line_length': 28.058091286307054, 'alnum_prop': 0.6135758651286601, 'repo_name': 'dplbsd/soc2013', 'id': '3b3a259574f8252b2f0c0914223fd7ed9655e9fa', 'size': '14389', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'head/contrib/gdb/gdb/gcore.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'AGS Script', 'bytes': '62471'}, {'name': 'Assembly', 'bytes': '4478661'}, {'name': 'Awk', 'bytes': '278525'}, {'name': 'Batchfile', 'bytes': '20417'}, {'name': 'C', 'bytes': '383420305'}, {'name': 'C++', 'bytes': '72796771'}, {'name': 'CSS', 'bytes': '109748'}, {'name': 'ChucK', 'bytes': '39'}, {'name': 'D', 'bytes': '3784'}, {'name': 'DIGITAL Command Language', 'bytes': '10640'}, {'name': 'DTrace', 'bytes': '2311027'}, {'name': 'Emacs Lisp', 'bytes': '65902'}, {'name': 'EmberScript', 'bytes': '286'}, {'name': 'Forth', 'bytes': '184405'}, {'name': 'GAP', 'bytes': '72156'}, {'name': 'Groff', 'bytes': '32248806'}, {'name': 'HTML', 'bytes': '6749816'}, {'name': 'IGOR Pro', 'bytes': '6301'}, {'name': 'Java', 'bytes': '112547'}, {'name': 'KRL', 'bytes': '4950'}, {'name': 'Lex', 'bytes': '398817'}, {'name': 'Limbo', 'bytes': '3583'}, {'name': 'Logos', 'bytes': '187900'}, {'name': 'Makefile', 'bytes': '3551839'}, {'name': 'Mathematica', 'bytes': '9556'}, {'name': 'Max', 'bytes': '4178'}, {'name': 'Module Management System', 'bytes': '817'}, {'name': 'NSIS', 'bytes': '3383'}, {'name': 'Objective-C', 'bytes': '836351'}, {'name': 'PHP', 'bytes': '6649'}, {'name': 'Perl', 'bytes': '5530761'}, {'name': 'Perl6', 'bytes': '41802'}, {'name': 'PostScript', 'bytes': '140088'}, {'name': 'Prolog', 'bytes': '29514'}, {'name': 'Protocol Buffer', 'bytes': '61933'}, {'name': 'Python', 'bytes': '299247'}, {'name': 'R', 'bytes': '764'}, {'name': 'Rebol', 'bytes': '738'}, {'name': 'Ruby', 'bytes': '45958'}, {'name': 'Scilab', 'bytes': '197'}, {'name': 'Shell', 'bytes': '10501540'}, {'name': 'SourcePawn', 'bytes': '463194'}, {'name': 'SuperCollider', 'bytes': '80208'}, {'name': 'Tcl', 'bytes': '80913'}, {'name': 'TeX', 'bytes': '719821'}, {'name': 'VimL', 'bytes': '22201'}, {'name': 'XS', 'bytes': '25451'}, {'name': 'XSLT', 'bytes': '31488'}, {'name': 'Yacc', 'bytes': '1857830'}]}
// DATA_TEMPLATE: empty_table oTest.fnStart("sDom"); /* This is going to be brutal on the browser! There is a lot that can be tested here... */ $(document).ready(function () { /* Check the default */ var oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt" }); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Default DOM varaible", null, function () { return oSettings.sDom == "lfrtip"; } ); oTest.fnWaitTest( "Default DOM in document", null, function () { var nNodes = $('#demo div, #demo table'); var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && nNodes[1] == nLength && nNodes[2] == nFilter && nNodes[3] == nTable && nNodes[4] == nInfo && nNodes[5] == nPaging; return bReturn; } ); oTest.fnWaitTest( "Check example 1 in code propagates", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": '<"wrapper"flipt>' }); oSettings = oTable.fnSettings(); }, function () { return oSettings.sDom == '<"wrapper"flipt>'; } ); oTest.fnWaitTest( "Check example 1 in DOM", null, function () { var jqNodes = $('#demo div, #demo table'); var nNodes = []; /* Strip the paging nodes */ for (var i = 0, iLen = jqNodes.length; i < iLen; i++) { if (jqNodes[i].getAttribute('id') != "example_previous" && jqNodes[i].getAttribute('id') != "example_next") { nNodes.push(jqNodes[i]); } } var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var nCustomWrapper = $('div.wrapper')[0]; var bReturn = nNodes[0] == nWrapper && nNodes[1] == nCustomWrapper && nNodes[2] == nFilter && nNodes[3] == nLength && nNodes[4] == nInfo && nNodes[5] == nPaging && nNodes[6] == nTable; return bReturn; } ); oTest.fnWaitTest( "Check example 2 in DOM", function () { oSession.fnRestore(); $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": '<lf<t>ip>' }); }, function () { var jqNodes = $('#demo div, #demo table'); var nNodes = []; var nCustomWrappers = [] /* Strip the paging nodes */ for (var i = 0, iLen = jqNodes.length; i < iLen; i++) { if (jqNodes[i].getAttribute('id') != "example_previous" && jqNodes[i].getAttribute('id') != "example_next") { nNodes.push(jqNodes[i]); } /* Only the two custom divs don't have class names */ if (jqNodes[i].className == "") { nCustomWrappers.push(jqNodes[i]); } } var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && nNodes[1] == nCustomWrappers[0] && nNodes[2] == nLength && nNodes[3] == nFilter && nNodes[4] == nCustomWrappers[1] && nNodes[5] == nTable && nNodes[6] == nInfo && nNodes[7] == nPaging; return bReturn; } ); oTest.fnWaitTest( "Check no length element", function () { oSession.fnRestore(); $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": 'frtip' }); }, function () { var nNodes = $('#demo div, #demo table'); var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && null == nLength && nNodes[1] == nFilter && nNodes[2] == nTable && nNodes[3] == nInfo && nNodes[4] == nPaging; return bReturn; } ); oTest.fnWaitTest( "Check no filter element", function () { oSession.fnRestore(); $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": 'lrtip' }); }, function () { var nNodes = $('#demo div, #demo table'); var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && nNodes[1] == nLength && null == nFilter && nNodes[2] == nTable && nNodes[3] == nInfo && nNodes[4] == nPaging; return bReturn; } ); /* Note we don't test for no table as this is not supported (and it would be fairly daft! */ oTest.fnWaitTest( "Check no info element", function () { oSession.fnRestore(); $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": 'lfrtp' }); }, function () { var nNodes = $('#demo div, #demo table'); var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && nNodes[1] == nLength && nNodes[2] == nFilter && nNodes[3] == nTable && null == nInfo && nNodes[4] == nPaging; return bReturn; } ); oTest.fnWaitTest( "Check no paging element", function () { oSession.fnRestore(); $('#example').dataTable({ "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "sDom": 'lfrti' }); }, function () { var nNodes = $('#demo div, #demo table'); var nWrapper = document.getElementById('example_wrapper'); var nLength = document.getElementById('example_length'); var nFilter = document.getElementById('example_filter'); var nInfo = document.getElementById('example_info'); var nPaging = document.getElementById('example_paginate'); var nTable = document.getElementById('example'); var bReturn = nNodes[0] == nWrapper && nNodes[1] == nLength && nNodes[2] == nFilter && nNodes[3] == nTable && nNodes[4] == nInfo && null == nPaging; return bReturn; } ); oTest.fnComplete(); });
{'content_hash': 'dc9fe17fbb16997867ebd6296a585256', 'timestamp': '', 'source': 'github', 'line_count': 261, 'max_line_length': 96, 'avg_line_length': 35.85057471264368, 'alnum_prop': 0.4888318905632147, 'repo_name': 'johnchronis/exareme', 'id': '33ed1a38317e80d713fcab3bdb32882581ea9c6f', 'size': '9357', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'exareme-master/src/main/static/libs/datatables/media/unit_testing/tests_onhold/3_ajax/sDom.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '66130'}, {'name': 'HTML', 'bytes': '1330883'}, {'name': 'Java', 'bytes': '3743191'}, {'name': 'JavaScript', 'bytes': '6100034'}, {'name': 'PHP', 'bytes': '124335'}, {'name': 'Python', 'bytes': '2480676'}, {'name': 'R', 'bytes': '671'}, {'name': 'Shell', 'bytes': '16037'}]}
package componentconfig import "k8s.io/kubernetes/pkg/api/unversioned" type KubeProxyConfiguration struct { unversioned.TypeMeta // bindAddress is the IP address for the proxy server to serve on (set to 0.0.0.0 // for all interfaces) BindAddress string `json:"bindAddress"` // clusterCIDR is the CIDR range of the pods in the cluster. It is used to // bridge traffic coming from outside of the cluster. If not provided, // no off-cluster bridging will be performed. ClusterCIDR string `json:"clusterCIDR"` // healthzBindAddress is the IP address for the health check server to serve on, // defaulting to 127.0.0.1 (set to 0.0.0.0 for all interfaces) HealthzBindAddress string `json:"healthzBindAddress"` // healthzPort is the port to bind the health check server. Use 0 to disable. HealthzPort int32 `json:"healthzPort"` // hostnameOverride, if non-empty, will be used as the identity instead of the actual hostname. HostnameOverride string `json:"hostnameOverride"` // iptablesMasqueradeBit is the bit of the iptables fwmark space to use for SNAT if using // the pure iptables proxy mode. Values must be within the range [0, 31]. IPTablesMasqueradeBit *int32 `json:"iptablesMasqueradeBit"` // iptablesSyncPeriod is the period that iptables rules are refreshed (e.g. '5s', '1m', // '2h22m'). Must be greater than 0. IPTablesSyncPeriod unversioned.Duration `json:"iptablesSyncPeriodSeconds"` // kubeconfigPath is the path to the kubeconfig file with authorization information (the // master location is set by the master flag). KubeconfigPath string `json:"kubeconfigPath"` // masqueradeAll tells kube-proxy to SNAT everything if using the pure iptables proxy mode. MasqueradeAll bool `json:"masqueradeAll"` // master is the address of the Kubernetes API server (overrides any value in kubeconfig) Master string `json:"master"` // oomScoreAdj is the oom-score-adj value for kube-proxy process. Values must be within // the range [-1000, 1000] OOMScoreAdj *int32 `json:"oomScoreAdj"` // mode specifies which proxy mode to use. Mode ProxyMode `json:"mode"` // portRange is the range of host ports (beginPort-endPort, inclusive) that may be consumed // in order to proxy service traffic. If unspecified (0-0) then ports will be randomly chosen. PortRange string `json:"portRange"` // resourceContainer is the absolute name of the resource-only container to create and run // the Kube-proxy in (Default: /kube-proxy). ResourceContainer string `json:"kubeletCgroups"` // udpIdleTimeout is how long an idle UDP connection will be kept open (e.g. '250ms', '2s'). // Must be greater than 0. Only applicable for proxyMode=userspace. UDPIdleTimeout unversioned.Duration `json:"udpTimeoutMilliseconds"` // conntrackMax is the maximum number of NAT connections to track (0 to leave as-is)") ConntrackMax int32 `json:"conntrackMax"` // conntrackTCPEstablishedTimeout is how long an idle UDP connection will be kept open // (e.g. '250ms', '2s'). Must be greater than 0. Only applicable for proxyMode is Userspace ConntrackTCPEstablishedTimeout unversioned.Duration `json:"conntrackTCPEstablishedTimeout"` } // Currently two modes of proxying are available: 'userspace' (older, stable) or 'iptables' // (newer, faster). If blank, look at the Node object on the Kubernetes API and respect the // 'net.experimental.kubernetes.io/proxy-mode' annotation if provided. Otherwise use the // best-available proxy (currently iptables, but may change in future versions). If the // iptables proxy is selected, regardless of how, but the system's kernel or iptables // versions are insufficient, this always falls back to the userspace proxy. type ProxyMode string const ( ProxyModeUserspace ProxyMode = "userspace" ProxyModeIPTables ProxyMode = "iptables" ) // HairpinMode denotes how the kubelet should configure networking to handle // hairpin packets. type HairpinMode string // Enum settings for different ways to handle hairpin packets. const ( // Set the hairpin flag on the veth of containers in the respective // container runtime. HairpinVeth = "hairpin-veth" // Make the container bridge promiscuous. This will force it to accept // hairpin packets, even if the flag isn't set on ports of the bridge. PromiscuousBridge = "promiscuous-bridge" // Neither of the above. If the kubelet is started in this hairpin mode // and kube-proxy is running in iptables mode, hairpin packets will be // dropped by the container bridge. HairpinNone = "none" ) // TODO: curate the ordering and structure of this config object type KubeletConfiguration struct { // config is the path to the config file or directory of files Config string `json:"config"` // syncFrequency is the max period between synchronizing running // containers and config SyncFrequency unversioned.Duration `json:"syncFrequency"` // fileCheckFrequency is the duration between checking config files for // new data FileCheckFrequency unversioned.Duration `json:"fileCheckFrequency"` // httpCheckFrequency is the duration between checking http for new data HTTPCheckFrequency unversioned.Duration `json:"httpCheckFrequency"` // manifestURL is the URL for accessing the container manifest ManifestURL string `json:"manifestURL"` // manifestURLHeader is the HTTP header to use when accessing the manifest // URL, with the key separated from the value with a ':', as in 'key:value' ManifestURLHeader string `json:"manifestURLHeader"` // enableServer enables the Kubelet's server EnableServer bool `json:"enableServer"` // address is the IP address for the Kubelet to serve on (set to 0.0.0.0 // for all interfaces) Address string `json:"address"` // port is the port for the Kubelet to serve on. Port uint `json:"port"` // readOnlyPort is the read-only port for the Kubelet to serve on with // no authentication/authorization (set to 0 to disable) ReadOnlyPort uint `json:"readOnlyPort"` // tLSCertFile is the file containing x509 Certificate for HTTPS. (CA cert, // if any, concatenated after server cert). If tlsCertFile and // tlsPrivateKeyFile are not provided, a self-signed certificate // and key are generated for the public address and saved to the directory // passed to certDir. TLSCertFile string `json:"tLSCertFile"` // tLSPrivateKeyFile is the ile containing x509 private key matching // tlsCertFile. TLSPrivateKeyFile string `json:"tLSPrivateKeyFile"` // certDirectory is the directory where the TLS certs are located (by // default /var/run/kubernetes). If tlsCertFile and tlsPrivateKeyFile // are provided, this flag will be ignored. CertDirectory string `json:"certDirectory"` // hostnameOverride is the hostname used to identify the kubelet instead // of the actual hostname. HostnameOverride string `json:"hostnameOverride"` // podInfraContainerImage is the image whose network/ipc namespaces // containers in each pod will use. PodInfraContainerImage string `json:"podInfraContainerImage"` // dockerEndpoint is the path to the docker endpoint to communicate with. DockerEndpoint string `json:"dockerEndpoint"` // rootDirectory is the directory path to place kubelet files (volume // mounts,etc). RootDirectory string `json:"rootDirectory"` // seccompProfileRoot is the directory path for seccomp profiles. SeccompProfileRoot string `json:"seccompProfileRoot"` // allowPrivileged enables containers to request privileged mode. // Defaults to false. AllowPrivileged bool `json:"allowPrivileged"` // hostNetworkSources is a comma-separated list of sources from which the // Kubelet allows pods to use of host network. Defaults to "*". HostNetworkSources string `json:"hostNetworkSources"` // hostPIDSources is a comma-separated list of sources from which the // Kubelet allows pods to use the host pid namespace. Defaults to "*". HostPIDSources string `json:"hostPIDSources"` // hostIPCSources is a comma-separated list of sources from which the // Kubelet allows pods to use the host ipc namespace. Defaults to "*". HostIPCSources string `json:"hostIPCSources"` // registryPullQPS is the limit of registry pulls per second. If 0, // unlimited. Set to 0 for no limit. Defaults to 5.0. RegistryPullQPS float64 `json:"registryPullQPS"` // registryBurst is the maximum size of a bursty pulls, temporarily allows // pulls to burst to this number, while still not exceeding registryQps. // Only used if registryQps > 0. RegistryBurst int32 `json:"registryBurst"` // eventRecordQPS is the maximum event creations per second. If 0, there // is no limit enforced. EventRecordQPS float32 `json:"eventRecordQPS"` // eventBurst is the maximum size of a bursty event records, temporarily // allows event records to burst to this number, while still not exceeding // event-qps. Only used if eventQps > 0 EventBurst int32 `json:"eventBurst"` // enableDebuggingHandlers enables server endpoints for log collection // and local running of containers and commands EnableDebuggingHandlers bool `json:"enableDebuggingHandlers"` // minimumGCAge is the minimum age for a finished container before it is // garbage collected. MinimumGCAge unversioned.Duration `json:"minimumGCAge"` // maxPerPodContainerCount is the maximum number of old instances to // retain per container. Each container takes up some disk space. MaxPerPodContainerCount int32 `json:"maxPerPodContainerCount"` // maxContainerCount is the maximum number of old instances of containers // to retain globally. Each container takes up some disk space. MaxContainerCount int32 `json:"maxContainerCount"` // cAdvisorPort is the port of the localhost cAdvisor endpoint CAdvisorPort uint `json:"cAdvisorPort"` // healthzPort is the port of the localhost healthz endpoint HealthzPort int32 `json:"healthzPort"` // healthzBindAddress is the IP address for the healthz server to serve // on. HealthzBindAddress string `json:"healthzBindAddress"` // oomScoreAdj is The oom-score-adj value for kubelet process. Values // must be within the range [-1000, 1000]. OOMScoreAdj int32 `json:"oomScoreAdj"` // registerNode enables automatic registration with the apiserver. RegisterNode bool `json:"registerNode"` // clusterDomain is the DNS domain for this cluster. If set, kubelet will // configure all containers to search this domain in addition to the // host's search domains. ClusterDomain string `json:"clusterDomain"` // masterServiceNamespace is The namespace from which the kubernetes // master services should be injected into pods. MasterServiceNamespace string `json:"masterServiceNamespace"` // clusterDNS is the IP address for a cluster DNS server. If set, kubelet // will configure all containers to use this for DNS resolution in // addition to the host's DNS servers ClusterDNS string `json:"clusterDNS"` // streamingConnectionIdleTimeout is the maximum time a streaming connection // can be idle before the connection is automatically closed. StreamingConnectionIdleTimeout unversioned.Duration `json:"streamingConnectionIdleTimeout"` // nodeStatusUpdateFrequency is the frequency that kubelet posts node // status to master. Note: be cautious when changing the constant, it // must work with nodeMonitorGracePeriod in nodecontroller. NodeStatusUpdateFrequency unversioned.Duration `json:"nodeStatusUpdateFrequency"` // minimumGCAge is the minimum age for a unused image before it is // garbage collected. ImageMinimumGCAge unversioned.Duration `json:"imageMinimumGCAge"` // imageGCHighThresholdPercent is the percent of disk usage after which // image garbage collection is always run. ImageGCHighThresholdPercent int32 `json:"imageGCHighThresholdPercent"` // imageGCLowThresholdPercent is the percent of disk usage before which // image garbage collection is never run. Lowest disk usage to garbage // collect to. ImageGCLowThresholdPercent int32 `json:"imageGCLowThresholdPercent"` // lowDiskSpaceThresholdMB is the absolute free disk space, in MB, to // maintain. When disk space falls below this threshold, new pods would // be rejected. LowDiskSpaceThresholdMB int32 `json:"lowDiskSpaceThresholdMB"` // How frequently to calculate and cache volume disk usage for all pods VolumeStatsAggPeriod unversioned.Duration `json:"volumeStatsAggPeriod"` // networkPluginName is the name of the network plugin to be invoked for // various events in kubelet/pod lifecycle NetworkPluginName string `json:"networkPluginName"` // networkPluginDir is the full path of the directory in which to search // for network plugins NetworkPluginDir string `json:"networkPluginDir"` // volumePluginDir is the full path of the directory in which to search // for additional third party volume plugins VolumePluginDir string `json:"volumePluginDir"` // cloudProvider is the provider for cloud services. CloudProvider string `json:"cloudProvider,omitempty"` // cloudConfigFile is the path to the cloud provider configuration file. CloudConfigFile string `json:"cloudConfigFile,omitempty"` // KubeletCgroups is the absolute name of cgroups to isolate the kubelet in. KubeletCgroups string `json:"kubeletCgroups,omitempty"` // Cgroups that container runtime is expected to be isolated in. RuntimeCgroups string `json:"runtimeCgroups,omitempty"` // SystemCgroups is absolute name of cgroups in which to place // all non-kernel processes that are not already in a container. Empty // for no container. Rolling back the flag requires a reboot. SystemCgroups string `json:"systemContainer,omitempty"` // cgroupRoot is the root cgroup to use for pods. This is handled by the // container runtime on a best effort basis. CgroupRoot string `json:"cgroupRoot,omitempty"` // containerRuntime is the container runtime to use. ContainerRuntime string `json:"containerRuntime"` // runtimeRequestTimeout is the timeout for all runtime requests except long running // requests - pull, logs, exec and attach. RuntimeRequestTimeout unversioned.Duration `json:"runtimeRequestTimeout,omitempty"` // rktPath is the path of rkt binary. Leave empty to use the first rkt in // $PATH. RktPath string `json:"rktPath,omitempty"` // rktApiEndpoint is the endpoint of the rkt API service to communicate with. RktAPIEndpoint string `json:"rktAPIEndpoint,omitempty"` // rktStage1Image is the image to use as stage1. Local paths and // http/https URLs are supported. RktStage1Image string `json:"rktStage1Image,omitempty"` // lockFilePath is the path that kubelet will use to as a lock file. // It uses this file as a lock to synchronize with other kubelet processes // that may be running. LockFilePath string `json:"lockFilePath"` // ExitOnLockContention is a flag that signifies to the kubelet that it is running // in "bootstrap" mode. This requires that 'LockFilePath' has been set. // This will cause the kubelet to listen to inotify events on the lock file, // releasing it and exiting when another process tries to open that file. ExitOnLockContention bool `json:"exitOnLockContention"` // configureCBR0 enables the kublet to configure cbr0 based on // Node.Spec.PodCIDR. ConfigureCBR0 bool `json:"configureCbr0"` // How should the kubelet configure the container bridge for hairpin packets. // Setting this flag allows endpoints in a Service to loadbalance back to // themselves if they should try to access their own Service. Values: // "promiscuous-bridge": make the container bridge promiscuous. // "hairpin-veth": set the hairpin flag on container veth interfaces. // "none": do nothing. // Setting --configure-cbr0 to false implies that to achieve hairpin NAT // one must set --hairpin-mode=veth-flag, because bridge assumes the // existence of a container bridge named cbr0. HairpinMode string `json:"hairpinMode"` // The node has babysitter process monitoring docker and kubelet. BabysitDaemons bool `json:"babysitDaemons"` // maxPods is the number of pods that can run on this Kubelet. MaxPods int32 `json:"maxPods"` // nvidiaGPUs is the number of NVIDIA GPU devices on this node. NvidiaGPUs int32 `json:"nvidiaGPUs"` // dockerExecHandlerName is the handler to use when executing a command // in a container. Valid values are 'native' and 'nsenter'. Defaults to // 'native'. DockerExecHandlerName string `json:"dockerExecHandlerName"` // The CIDR to use for pod IP addresses, only used in standalone mode. // In cluster mode, this is obtained from the master. PodCIDR string `json:"podCIDR"` // ResolverConfig is the resolver configuration file used as the basis // for the container DNS resolution configuration."), [] ResolverConfig string `json:"resolvConf"` // cpuCFSQuota is Enable CPU CFS quota enforcement for containers that // specify CPU limits CPUCFSQuota bool `json:"cpuCFSQuota"` // containerized should be set to true if kubelet is running in a container. Containerized bool `json:"containerized"` // maxOpenFiles is Number of files that can be opened by Kubelet process. MaxOpenFiles uint64 `json:"maxOpenFiles"` // reconcileCIDR is Reconcile node CIDR with the CIDR specified by the // API server. No-op if register-node or configure-cbr0 is false. ReconcileCIDR bool `json:"reconcileCIDR"` // registerSchedulable tells the kubelet to register the node as // schedulable. No-op if register-node is false. RegisterSchedulable bool `json:"registerSchedulable"` // contentType is contentType of requests sent to apiserver. ContentType string `json:"contentType"` // kubeAPIQPS is the QPS to use while talking with kubernetes apiserver KubeAPIQPS float32 `json:"kubeAPIQPS"` // kubeAPIBurst is the burst to allow while talking with kubernetes // apiserver KubeAPIBurst int32 `json:"kubeAPIBurst"` // serializeImagePulls when enabled, tells the Kubelet to pull images one // at a time. We recommend *not* changing the default value on nodes that // run docker daemon with version < 1.9 or an Aufs storage backend. // Issue #10959 has more details. SerializeImagePulls bool `json:"serializeImagePulls"` // experimentalFlannelOverlay enables experimental support for starting the // kubelet with the default overlay network (flannel). Assumes flanneld // is already running in client mode. ExperimentalFlannelOverlay bool `json:"experimentalFlannelOverlay"` // outOfDiskTransitionFrequency is duration for which the kubelet has to // wait before transitioning out of out-of-disk node condition status. OutOfDiskTransitionFrequency unversioned.Duration `json:"outOfDiskTransitionFrequency,omitempty"` // nodeIP is IP address of the node. If set, kubelet will use this IP // address for the node. NodeIP string `json:"nodeIP,omitempty"` // nodeLabels to add when registering the node in the cluster. NodeLabels map[string]string `json:"nodeLabels"` // nonMasqueradeCIDR configures masquerading: traffic to IPs outside this range will use IP masquerade. NonMasqueradeCIDR string `json:"nonMasqueradeCIDR"` // enable gathering custom metrics. EnableCustomMetrics bool `json:"enableCustomMetrics"` // Comma-delimited list of hard eviction expressions. For example, 'memory.available<300Mi'. EvictionHard string `json:"evictionHard,omitempty"` // Comma-delimited list of soft eviction expressions. For example, 'memory.available<300Mi'. EvictionSoft string `json:"evictionSoft,omitempty"` // Comma-delimeted list of grace periods for each soft eviction signal. For example, 'memory.available=30s'. EvictionSoftGracePeriod string `json:"evictionSoftGracePeriod,omitempty"` // Duration for which the kubelet has to wait before transitioning out of an eviction pressure condition. EvictionPressureTransitionPeriod unversioned.Duration `json:"evictionPressureTransitionPeriod,omitempty"` // Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met. EvictionMaxPodGracePeriod int32 `json:"evictionMaxPodGracePeriod,omitempty"` // Maximum number of pods per core. Cannot exceed MaxPods PodsPerCore int32 `json:"podsPerCore"` // enableControllerAttachDetach enables the Attach/Detach controller to // manage attachment/detachment of volumes scheduled to this node, and // disables kubelet from executing any attach/detach operations EnableControllerAttachDetach bool `json:"enableControllerAttachDetach"` } type KubeSchedulerConfiguration struct { unversioned.TypeMeta // port is the port that the scheduler's http service runs on. Port int32 `json:"port"` // address is the IP address to serve on. Address string `json:"address"` // algorithmProvider is the scheduling algorithm provider to use. AlgorithmProvider string `json:"algorithmProvider"` // policyConfigFile is the filepath to the scheduler policy configuration. PolicyConfigFile string `json:"policyConfigFile"` // enableProfiling enables profiling via web interface. EnableProfiling bool `json:"enableProfiling"` // contentType is contentType of requests sent to apiserver. ContentType string `json:"contentType"` // kubeAPIQPS is the QPS to use while talking with kubernetes apiserver. KubeAPIQPS float32 `json:"kubeAPIQPS"` // kubeAPIBurst is the QPS burst to use while talking with kubernetes apiserver. KubeAPIBurst int32 `json:"kubeAPIBurst"` // schedulerName is name of the scheduler, used to select which pods // will be processed by this scheduler, based on pod's annotation with // key 'scheduler.alpha.kubernetes.io/name'. SchedulerName string `json:"schedulerName"` // RequiredDuringScheduling affinity is not symmetric, but there is an implicit PreferredDuringScheduling affinity rule // corresponding to every RequiredDuringScheduling affinity rule. // HardPodAffinitySymmetricWeight represents the weight of implicit PreferredDuringScheduling affinity rule, in the range 0-100. HardPodAffinitySymmetricWeight int `json:"hardPodAffinitySymmetricWeight"` // Indicate the "all topologies" set for empty topologyKey when it's used for PreferredDuringScheduling pod anti-affinity. FailureDomains string `json:"failureDomains"` // leaderElection defines the configuration of leader election client. LeaderElection LeaderElectionConfiguration `json:"leaderElection"` } // LeaderElectionConfiguration defines the configuration of leader election // clients for components that can run with leader election enabled. type LeaderElectionConfiguration struct { // leaderElect enables a leader election client to gain leadership // before executing the main loop. Enable this when running replicated // components for high availability. LeaderElect bool `json:"leaderElect"` // leaseDuration is the duration that non-leader candidates will wait // after observing a leadership renewal until attempting to acquire // leadership of a led but unrenewed leader slot. This is effectively the // maximum duration that a leader can be stopped before it is replaced // by another candidate. This is only applicable if leader election is // enabled. LeaseDuration unversioned.Duration `json:"leaseDuration"` // renewDeadline is the interval between attempts by the acting master to // renew a leadership slot before it stops leading. This must be less // than or equal to the lease duration. This is only applicable if leader // election is enabled. RenewDeadline unversioned.Duration `json:"renewDeadline"` // retryPeriod is the duration the clients should wait between attempting // acquisition and renewal of a leadership. This is only applicable if // leader election is enabled. RetryPeriod unversioned.Duration `json:"retryPeriod"` } type KubeControllerManagerConfiguration struct { unversioned.TypeMeta // port is the port that the controller-manager's http service runs on. Port int32 `json:"port"` // address is the IP address to serve on (set to 0.0.0.0 for all interfaces). Address string `json:"address"` // cloudProvider is the provider for cloud services. CloudProvider string `json:"cloudProvider"` // cloudConfigFile is the path to the cloud provider configuration file. CloudConfigFile string `json:"cloudConfigFile"` // concurrentEndpointSyncs is the number of endpoint syncing operations // that will be done concurrently. Larger number = faster endpoint updating, // but more CPU (and network) load. ConcurrentEndpointSyncs int32 `json:"concurrentEndpointSyncs"` // concurrentRSSyncs is the number of replica sets that are allowed to sync // concurrently. Larger number = more responsive replica management, but more // CPU (and network) load. ConcurrentRSSyncs int32 `json:"concurrentRSSyncs"` // concurrentRCSyncs is the number of replication controllers that are // allowed to sync concurrently. Larger number = more responsive replica // management, but more CPU (and network) load. ConcurrentRCSyncs int32 `json:"concurrentRCSyncs"` // concurrentResourceQuotaSyncs is the number of resource quotas that are // allowed to sync concurrently. Larger number = more responsive quota // management, but more CPU (and network) load. ConcurrentResourceQuotaSyncs int32 `json:"concurrentResourceQuotaSyncs"` // concurrentDeploymentSyncs is the number of deployment objects that are // allowed to sync concurrently. Larger number = more responsive deployments, // but more CPU (and network) load. ConcurrentDeploymentSyncs int32 `json:"concurrentDeploymentSyncs"` // concurrentDaemonSetSyncs is the number of daemonset objects that are // allowed to sync concurrently. Larger number = more responsive daemonset, // but more CPU (and network) load. ConcurrentDaemonSetSyncs int32 `json:"concurrentDaemonSetSyncs"` // concurrentJobSyncs is the number of job objects that are // allowed to sync concurrently. Larger number = more responsive jobs, // but more CPU (and network) load. ConcurrentJobSyncs int32 `json:"concurrentJobSyncs"` // concurrentNamespaceSyncs is the number of namespace objects that are // allowed to sync concurrently. ConcurrentNamespaceSyncs int32 `json:"concurrentNamespaceSyncs"` // lookupCacheSizeForRC is the size of lookup cache for replication controllers. // Larger number = more responsive replica management, but more MEM load. LookupCacheSizeForRC int32 `json:"lookupCacheSizeForRC"` // lookupCacheSizeForRS is the size of lookup cache for replicatsets. // Larger number = more responsive replica management, but more MEM load. LookupCacheSizeForRS int32 `json:"lookupCacheSizeForRS"` // lookupCacheSizeForDaemonSet is the size of lookup cache for daemonsets. // Larger number = more responsive daemonset, but more MEM load. LookupCacheSizeForDaemonSet int32 `json:"lookupCacheSizeForDaemonSet"` // serviceSyncPeriod is the period for syncing services with their external // load balancers. ServiceSyncPeriod unversioned.Duration `json:"serviceSyncPeriod"` // nodeSyncPeriod is the period for syncing nodes from cloudprovider. Longer // periods will result in fewer calls to cloud provider, but may delay addition // of new nodes to cluster. NodeSyncPeriod unversioned.Duration `json:"nodeSyncPeriod"` // resourceQuotaSyncPeriod is the period for syncing quota usage status // in the system. ResourceQuotaSyncPeriod unversioned.Duration `json:"resourceQuotaSyncPeriod"` // namespaceSyncPeriod is the period for syncing namespace life-cycle // updates. NamespaceSyncPeriod unversioned.Duration `json:"namespaceSyncPeriod"` // pvClaimBinderSyncPeriod is the period for syncing persistent volumes // and persistent volume claims. PVClaimBinderSyncPeriod unversioned.Duration `json:"pvClaimBinderSyncPeriod"` // minResyncPeriod is the resync period in reflectors; will be random between // minResyncPeriod and 2*minResyncPeriod. MinResyncPeriod unversioned.Duration `json:"minResyncPeriod"` // terminatedPodGCThreshold is the number of terminated pods that can exist // before the terminated pod garbage collector starts deleting terminated pods. // If <= 0, the terminated pod garbage collector is disabled. TerminatedPodGCThreshold int32 `json:"terminatedPodGCThreshold"` // horizontalPodAutoscalerSyncPeriod is the period for syncing the number of // pods in horizontal pod autoscaler. HorizontalPodAutoscalerSyncPeriod unversioned.Duration `json:"horizontalPodAutoscalerSyncPeriod"` // deploymentControllerSyncPeriod is the period for syncing the deployments. DeploymentControllerSyncPeriod unversioned.Duration `json:"deploymentControllerSyncPeriod"` // podEvictionTimeout is the grace period for deleting pods on failed nodes. PodEvictionTimeout unversioned.Duration `json:"podEvictionTimeout"` // deletingPodsQps is the number of nodes per second on which pods are deleted in // case of node failure. DeletingPodsQps float32 `json:"deletingPodsQps"` // deletingPodsBurst is the number of nodes on which pods are bursty deleted in // case of node failure. For more details look into RateLimiter. DeletingPodsBurst int32 `json:"deletingPodsBurst"` // nodeMontiorGracePeriod is the amount of time which we allow a running node to be // unresponsive before marking it unhealty. Must be N times more than kubelet's // nodeStatusUpdateFrequency, where N means number of retries allowed for kubelet // to post node status. NodeMonitorGracePeriod unversioned.Duration `json:"nodeMonitorGracePeriod"` // registerRetryCount is the number of retries for initial node registration. // Retry interval equals node-sync-period. RegisterRetryCount int32 `json:"registerRetryCount"` // nodeStartupGracePeriod is the amount of time which we allow starting a node to // be unresponsive before marking it unhealty. NodeStartupGracePeriod unversioned.Duration `json:"nodeStartupGracePeriod"` // nodeMonitorPeriod is the period for syncing NodeStatus in NodeController. NodeMonitorPeriod unversioned.Duration `json:"nodeMonitorPeriod"` // serviceAccountKeyFile is the filename containing a PEM-encoded private RSA key // used to sign service account tokens. ServiceAccountKeyFile string `json:"serviceAccountKeyFile"` // enableProfiling enables profiling via web interface host:port/debug/pprof/ EnableProfiling bool `json:"enableProfiling"` // clusterName is the instance prefix for the cluster. ClusterName string `json:"clusterName"` // clusterCIDR is CIDR Range for Pods in cluster. ClusterCIDR string `json:"clusterCIDR"` // serviceCIDR is CIDR Range for Services in cluster. ServiceCIDR string `json:"serviceCIDR"` // NodeCIDRMaskSize is the mask size for node cidr in cluster. NodeCIDRMaskSize int32 `json:"nodeCIDRMaskSize"` // allocateNodeCIDRs enables CIDRs for Pods to be allocated and, if // ConfigureCloudRoutes is true, to be set on the cloud provider. AllocateNodeCIDRs bool `json:"allocateNodeCIDRs"` // configureCloudRoutes enables CIDRs allocated with allocateNodeCIDRs // to be configured on the cloud provider. ConfigureCloudRoutes bool `json:"configureCloudRoutes"` // rootCAFile is the root certificate authority will be included in service // account's token secret. This must be a valid PEM-encoded CA bundle. RootCAFile string `json:"rootCAFile"` // contentType is contentType of requests sent to apiserver. ContentType string `json:"contentType"` // kubeAPIQPS is the QPS to use while talking with kubernetes apiserver. KubeAPIQPS float32 `json:"kubeAPIQPS"` // kubeAPIBurst is the burst to use while talking with kubernetes apiserver. KubeAPIBurst int32 `json:"kubeAPIBurst"` // leaderElection defines the configuration of leader election client. LeaderElection LeaderElectionConfiguration `json:"leaderElection"` // volumeConfiguration holds configuration for volume related features. VolumeConfiguration VolumeConfiguration `json:"volumeConfiguration"` // How long to wait between starting controller managers ControllerStartInterval unversioned.Duration `json:"controllerStartInterval"` // enables the generic garbage collector. MUST be synced with the // corresponding flag of the kube-apiserver. WARNING: the generic garbage // collector is an alpha feature. EnableGarbageCollector bool `json:"enableGarbageCollector"` } // VolumeConfiguration contains *all* enumerated flags meant to configure all volume // plugins. From this config, the controller-manager binary will create many instances of // volume.VolumeConfig, each containing only the configuration needed for that plugin which // are then passed to the appropriate plugin. The ControllerManager binary is the only part // of the code which knows what plugins are supported and which flags correspond to each plugin. type VolumeConfiguration struct { // enableHostPathProvisioning enables HostPath PV provisioning when running without a // cloud provider. This allows testing and development of provisioning features. HostPath // provisioning is not supported in any way, won't work in a multi-node cluster, and // should not be used for anything other than testing or development. EnableHostPathProvisioning bool `json:"enableHostPathProvisioning"` // enableDynamicProvisioning enables the provisioning of volumes when running within an environment // that supports dynamic provisioning. Defaults to true. EnableDynamicProvisioning bool `json:"enableDynamicProvisioning"` // persistentVolumeRecyclerConfiguration holds configuration for persistent volume plugins. PersistentVolumeRecyclerConfiguration PersistentVolumeRecyclerConfiguration `json:"persitentVolumeRecyclerConfiguration"` // volumePluginDir is the full path of the directory in which the flex // volume plugin should search for additional third party volume plugins FlexVolumePluginDir string `json:"flexVolumePluginDir"` } type PersistentVolumeRecyclerConfiguration struct { // maximumRetry is number of retries the PV recycler will execute on failure to recycle // PV. MaximumRetry int32 `json:"maximumRetry"` // minimumTimeoutNFS is the minimum ActiveDeadlineSeconds to use for an NFS Recycler // pod. MinimumTimeoutNFS int32 `json:"minimumTimeoutNFS"` // podTemplateFilePathNFS is the file path to a pod definition used as a template for // NFS persistent volume recycling PodTemplateFilePathNFS string `json:"podTemplateFilePathNFS"` // incrementTimeoutNFS is the increment of time added per Gi to ActiveDeadlineSeconds // for an NFS scrubber pod. IncrementTimeoutNFS int32 `json:"incrementTimeoutNFS"` // podTemplateFilePathHostPath is the file path to a pod definition used as a template for // HostPath persistent volume recycling. This is for development and testing only and // will not work in a multi-node cluster. PodTemplateFilePathHostPath string `json:"podTemplateFilePathHostPath"` // minimumTimeoutHostPath is the minimum ActiveDeadlineSeconds to use for a HostPath // Recycler pod. This is for development and testing only and will not work in a multi-node // cluster. MinimumTimeoutHostPath int32 `json:"minimumTimeoutHostPath"` // incrementTimeoutHostPath is the increment of time added per Gi to ActiveDeadlineSeconds // for a HostPath scrubber pod. This is for development and testing only and will not work // in a multi-node cluster. IncrementTimeoutHostPath int32 `json:"incrementTimeoutHostPath"` }
{'content_hash': '36a3079fa23529c4a15367edd72ceeb5', 'timestamp': '', 'source': 'github', 'line_count': 604, 'max_line_length': 129, 'avg_line_length': 58.102649006622514, 'alnum_prop': 0.7894511882373055, 'repo_name': 'ajohnstone/kubernetes', 'id': '6121048b4761c6bfaaeddae7b18667948761f37a', 'size': '35683', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'pkg/apis/componentconfig/types.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '998'}, {'name': 'Go', 'bytes': '26890967'}, {'name': 'HTML', 'bytes': '1193990'}, {'name': 'Makefile', 'bytes': '61893'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'Protocol Buffer', 'bytes': '240057'}, {'name': 'Python', 'bytes': '34630'}, {'name': 'SaltStack', 'bytes': '55886'}, {'name': 'Shell', 'bytes': '1411112'}]}
// Licensed to the Symphony Software Foundation (SSF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SSF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. namespace SymphonyOSS.RestApiClient.Tests { using System.Security.Cryptography.X509Certificates; using Factories; using Generated.OpenApi.AuthenticatorApi; using Moq; using Xunit; public class AuthenticatorApiFactoryTest { private readonly Mock<X509Certificate2> _certificateMock; public AuthenticatorApiFactoryTest() { _certificateMock = new Mock<X509Certificate2>(); } [Fact] public void EnsureConstructs_AuthenticationApi() { var authenticatorApiFactory = new AuthenticatorApiFactory("https://authurl"); var result = authenticatorApiFactory.CreateAppAuthenticationApi(_certificateMock.Object); Assert.NotNull(result); } } }
{'content_hash': '917cf14ceb37b9ab86d3e809104ada9a', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 101, 'avg_line_length': 35.90909090909091, 'alnum_prop': 0.7158227848101266, 'repo_name': 'symphonyoss/RestApiClient', 'id': '0955ba58517e421b0ddf8db682e2d41eb0866812', 'size': '1582', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'test/SymphonyOSS.RestApiClient.Tests/AuthenticatorApiFactoryTest.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '7671'}, {'name': 'C#', 'bytes': '1992342'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <resources> <color name="title_background">#ff355689</color> <color name="title_text">#ffffffff</color> <color name="title_text_alt">#ff000000</color> <color name="foreground1">#ff355689</color> <color name="foreground2">#ff7081a3</color> <color name="background1">#ffffffff</color> <color name="background2">#ffd5ddeb</color> <color name="background3">#ffe3e8f1</color> <color name="title_separator">#40ffffff</color> <color name="session_foreground_past">#ff999999</color> <color name="pinned_header_background">#ff202020</color> </resources>
{'content_hash': '3c3a9ba7cd1b676ffb6c47846038cd72', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 76, 'avg_line_length': 39.74193548387097, 'alnum_prop': 0.7061688311688312, 'repo_name': 'renjiexu/allblue-all-in-one', 'id': '82feef2f01f0b0318013dcc2595d01bd555c4190', 'size': '1232', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'res/values/colors.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '40438'}]}
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.backend.jvm.tasks.jvm_compile.analysis_parser import (AnalysisParser, ParseError, raise_on_eof) from pants.backend.jvm.tasks.jvm_compile.zinc.zinc_analysis import ZincAnalysis from pants.backend.jvm.zinc.zinc_analysis_parser import ZincAnalysisParser as UnderlyingParser class ZincAnalysisParser(AnalysisParser): """Parses a zinc analysis file. Implemented by delegating to an underlying pants.backend.jvm.zinc.ZincAnalysisParser instance. """ # Implement AnalysisParser properties. empty_test_header = b'products' current_test_header = ZincAnalysis.FORMAT_VERSION_LINE def __init__(self): self._underlying_parser = UnderlyingParser() # Implement AnalysisParser methods. def parse(self, infile): """Parse a ZincAnalysis instance from an open text file.""" with raise_on_eof(infile): try: return ZincAnalysis(self._underlying_parser.parse(infile)) except UnderlyingParser.ParseError as e: raise ParseError(e) def parse_products(self, infile, classes_dir): """An efficient parser of just the products section.""" with raise_on_eof(infile): try: return self._underlying_parser.parse_products(infile) except UnderlyingParser.ParseError as e: raise ParseError(e) def parse_deps(self, infile): with raise_on_eof(infile): try: return self._underlying_parser.parse_deps(infile, "") except UnderlyingParser.ParseError as e: raise ParseError(e) def rebase(self, infile, outfile, pants_home_from, pants_home_to, java_home=None): with raise_on_eof(infile): try: self._underlying_parser.rebase(infile, outfile, pants_home_from, pants_home_to, java_home) except UnderlyingParser.ParseError as e: raise ParseError(e)
{'content_hash': 'f61678e5222c04af171f949ca6f06cfc', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 98, 'avg_line_length': 38.53846153846154, 'alnum_prop': 0.6921157684630739, 'repo_name': 'dbentley/pants', 'id': '26ab90219055b7c4446ebb9f1e047e94172bc7c0', 'size': '2151', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/python/pants/backend/jvm/tasks/jvm_compile/zinc/zinc_analysis_parser.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '781'}, {'name': 'CSS', 'bytes': '11572'}, {'name': 'Cucumber', 'bytes': '919'}, {'name': 'GAP', 'bytes': '2459'}, {'name': 'Go', 'bytes': '1569'}, {'name': 'HTML', 'bytes': '64699'}, {'name': 'Java', 'bytes': '290988'}, {'name': 'JavaScript', 'bytes': '31040'}, {'name': 'Protocol Buffer', 'bytes': '3783'}, {'name': 'Python', 'bytes': '4277407'}, {'name': 'Scala', 'bytes': '84066'}, {'name': 'Shell', 'bytes': '50882'}, {'name': 'Thrift', 'bytes': '2898'}]}